Created
February 7, 2018 17:36
-
-
Save ytjohn/dff86216b7ce6ffe4e04a138bafd7974 to your computer and use it in GitHub Desktop.
running asyncio within the loop itself
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
from apistar import Include, Route | |
from apistar.frameworks.asyncio import ASyncIOApp as App | |
from apistar.handlers import docs_urls, static_urls | |
import asyncio | |
import logging | |
import random | |
from time import time | |
logger = logging.getLogger('asyncioapp') | |
logger.setLevel(logging.DEBUG) | |
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') | |
ch = logging.StreamHandler() | |
ch.setFormatter(formatter) | |
logger.addHandler(ch) | |
async def mylogic(): | |
logger.debug('starting welcome') | |
# a list of resources | |
resources = list(range(1, 20)) | |
loop = asyncio.get_event_loop() | |
start_time = time() | |
tasks = list() | |
created = list() | |
for r in resources: | |
logger.debug('tasklist adding resource {}'.format(r)) | |
task = worker(r) | |
tasks.append(task) | |
created.append(loop.create_task(task)) | |
logger.debug('tasklist added resource {}'.format(r)) | |
logger.info('tasklist created') | |
logger.debug('waiting till all tasks complete') | |
await asyncio.wait(created) | |
retrieved = list() | |
for ongoing in created: | |
if ongoing.done(): | |
result = ongoing.result() | |
logger.info(result) | |
retrieved.append(result) | |
else: | |
logger.critical("I shouldn't be here!") | |
results = dict( | |
time_elapsed=time() - start_time, | |
results=retrieved | |
) | |
return results | |
async def worker(resource): | |
logger.debug('starting resource {}'.format(resource)) | |
sleep_time = random.randint(1, 5) | |
await asyncio.sleep(sleep_time) | |
logger.debug('completed resource {}'.format(resource)) | |
return dict(resource=resource, retrieval_time=sleep_time) | |
routes = [ | |
Route('/', 'GET', mylogic), | |
Include('/docs', docs_urls), | |
Include('/static', static_urls) | |
] | |
app = App(routes=routes) | |
if __name__ == '__main__': | |
app.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment