Created
February 27, 2018 02:42
-
-
Save knowsuchagency/e73f3bff691d94a46f04664c93c174bc to your computer and use it in GitHub Desktop.
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
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