Created
October 5, 2017 23:42
-
-
Save palazzem/d83778a62e6ea406d5d474fd5ad25d81 to your computer and use it in GitHub Desktop.
pygotham_asyncio_full_app.py
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
import asyncio | |
def set_current_context(ctx, loop=None): | |
# retrieves the current Task | |
loop = loop or asyncio.get_event_loop() | |
task = asyncio.Task.current_task(loop=loop) | |
# attach the Context to the task! | |
setattr(task, '__current_ctx', ctx) | |
def get_current_context(loop=None): | |
# retrieves the current Task | |
loop = loop or asyncio.get_event_loop() | |
task = asyncio.Task.current_task(loop=loop) | |
# get the Context | |
ctx = getattr(task, '__current_ctx', None) | |
return ctx | |
async def handle_request(reader, writer): | |
"""Web handler examples""" | |
# set the current context | |
ctx = {} | |
set_current_context(ctx) | |
# read and store the whole request in the context | |
data = await reader.read(100) | |
ctx['data'] = data.decode() | |
result = await retrieve_user_data() | |
writer.write(result.encode()) | |
writer.close() | |
async def retrieve_user_data(): | |
# do a long call | |
await asyncio.sleep(2) | |
ctx = get_current_context() | |
return ctx['data'] | |
if __name__ == '__main__': | |
# initialize the server | |
loop = asyncio.get_event_loop() | |
coro = asyncio.start_server(handle_request, '127.0.0.1', 8000, loop=loop) | |
server = loop.run_until_complete(coro) | |
# Serve requests until Ctrl+C is pressed | |
print('Serving on {}'.format(server.sockets[0].getsockname())) | |
try: | |
loop.run_forever() | |
except KeyboardInterrupt: | |
pass | |
# Close the server | |
server.close() | |
loop.run_until_complete(server.wait_closed()) | |
loop.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Requirements
Launch the application
Be sure that you're running
python3
, then:In another shell, launch multiple concurrent calls:
The expected output should be: