Skip to content

Instantly share code, notes, and snippets.

@knowsuchagency
Created February 27, 2018 02:42
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 knowsuchagency/e73f3bff691d94a46f04664c93c174bc to your computer and use it in GitHub Desktop.
Save knowsuchagency/e73f3bff691d94a46f04664c93c174bc to your computer and use it in GitHub Desktop.
async def author(request):
"""Return a single author for a given id."""
connection = request.app['connection']
with log_request(request):
try:
# when using co-routines, it's important that each co-routine be non-blocking
# meaning no individual action will take a long amount of time, preventing
# the event loop from letting other co-routines execute
# since our database query may not immediately return, we run it
# in an "executor" (a thread pool) and await for it to finish
# functools.partial allows us to create a callable that
# bundles necessary positional and keyword arguments with it
# in a way that is pickle-able https://docs.python.org/3/library/pickle.html
# i.e. `print('hello', end=' ') == partial(print, 'hello', end= ' ')()`
db_query = partial(
fetch_authors, connection, id=int(request.match_info['id']))
# * unpacks an arbitrary number of tuples (see pep-3132)
author, *_ = await request.loop.run_in_executor(None, db_query)
except ValueError:
author = None
if not author:
log_message('Author not found', id=request.match_info['id'])
raise web.HTTPNotFound
response = web.json_response(author)
with log_response(response):
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment