Skip to content

Instantly share code, notes, and snippets.

@ytjohn
Created February 7, 2018 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ytjohn/dff86216b7ce6ffe4e04a138bafd7974 to your computer and use it in GitHub Desktop.
Save ytjohn/dff86216b7ce6ffe4e04a138bafd7974 to your computer and use it in GitHub Desktop.
running asyncio within the loop itself
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