Created
November 14, 2017 03:01
-
-
Save svvitale/819bb8e2ae43b2c3f8baf0cc2dc5cc2e to your computer and use it in GitHub Desktop.
Requests.Session -> Async
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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