From 0fd043ecb87944d3f5872c5a96b62a7a3f9088bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sybren=20A=2E=20St=C3=BCvel?= Date: Fri, 18 Mar 2016 12:41:24 +0100 Subject: [PATCH] Support session objects. This not only improves general performance by sharing socket connections between HTTP calls, but also allows for caching with Requests-Cache. --- README.md | 21 +++++++++++++++++++++ pillarsdk/api.py | 10 +++++++++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 9f70564..b06fc52 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,23 @@ # Pillar Python REST SDK Integrate this module in your Python app to communicate with an Pillar server. + + +## Caching + +[Requests-Cache](https://requests-cache.readthedocs.org/) can be used to +cache HTTP requests. The Pillar Python REST SDK does not support it +directly, but provides the means to plug in different session objects: + + import requests_cache + import pillarsdk + + req_sess = requests_cache.CachedSession(backend='sqlite', + cache_name='blender_cloud') + pillarsdk.Api.requests_session = req_sess + +Any `pillarsdk.Api` instance will now use the cached session. To +temporary disable it, use: + + api = pillarsdk.Api.Default(endpoint="https://your.endpoint") + with api.requests_session.cache_disabled(): + node = pillarsdk.Node.find('1234') diff --git a/pillarsdk/api.py b/pillarsdk/api.py index 9ad41b2..8d8a395 100644 --- a/pillarsdk/api.py +++ b/pillarsdk/api.py @@ -18,6 +18,9 @@ class Api(object): __version__, library_details) _api_singleton = None + # Global session object to do HTTP requests. + requests_session = requests.session() + def __init__(self, options=None, **kwargs): """Create API object @@ -119,7 +122,12 @@ class Api(object): def http_call(self, url, method, **kwargs): """Makes a http call. Logs response information. """ - response = requests.request(method, url, **kwargs) + + try: + response = self.requests_session.request(method, url, **kwargs) + except Exception as ex: + logging.warning('Error performing HTTP %s request to %s: %s', method, url, str(ex)) + raise try: error = self.handle_response(response,