Last active
February 19, 2017 13:21
-
-
Save stevepeak/f7c88cf0b6737e55b8f95030abddb295 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
def run_coroutine_sync(func): | |
def wrapped(*args, **kwargs): | |
if kwargs.pop('_in_loop', False): | |
# used for thread-local state | |
# only call run_sync on first api call, subsiquent calls are already "in the loop" | |
return func(*args, **kwargs) | |
else: | |
@gen.coroutine | |
def inner(): | |
res = yield func(*args, **kwargs) | |
raise gen.Return(res) | |
loop_is_up = True | |
return IOLoop.current().run_sync(inner) | |
return wrapped | |
class API: | |
@classmethod | |
def new(cls, async=True): | |
self = cls() | |
if not async: | |
setattr(self, 'get', run_coroutine_sync(self.get)) | |
setattr(self, 'gget_extra_dataet', run_coroutine_sync(self.get_extra_data)) | |
return self | |
@gen.coroutine | |
def get(self): | |
res = yield AsyncHTTPClient().fetch('https://...') | |
extra = yield self.get_extra_data(_in_loop=True) | |
raise gen.Return(res) | |
@gen.coroutine | |
def get_extra_data(self): | |
res = yield AsyncHTTPClient().fetch('https://...') | |
raise gen.Return(res) | |
# web | |
yield API().get() | |
# celery | |
res = API(async=False).get() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment