Skip to content

Instantly share code, notes, and snippets.

@svvitale
Created November 14, 2017 03:01
Show Gist options
  • Save svvitale/819bb8e2ae43b2c3f8baf0cc2dc5cc2e to your computer and use it in GitHub Desktop.
Save svvitale/819bb8e2ae43b2c3f8baf0cc2dc5cc2e to your computer and use it in GitHub Desktop.
Requests.Session -> Async
import requests
class MyApiClient(requests.Session):
def do_something(self):
response = self.post('/some/url', json={
'param1': 'a',
'param2': 'b'
})
if response.status_code == requests.codes.ok:
return response.json()
raise ValueError("invalid API response")
import requests
class AsyncSession(requests.Session):
def request(self, *args, **kwargs):
if 'async' in kwargs:
async = kwargs['async']
del kwargs['async']
else:
async = False
future = super().request(*args, **kwargs)
if async:
return future.result()
return future
class MyApiClient(AsyncSession):
def do_something(self):
""" Code remains unchanged from example above. """
def do_something_async(self):
future = self.post('/some/url', async=True, json={
'param1': 'a',
'param2': 'b'
})
return future
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment