Skip to content

Instantly share code, notes, and snippets.

@palazzem
Created October 5, 2017 23:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save palazzem/d83778a62e6ea406d5d474fd5ad25d81 to your computer and use it in GitHub Desktop.
Save palazzem/d83778a62e6ea406d5d474fd5ad25d81 to your computer and use it in GitHub Desktop.
pygotham_asyncio_full_app.py
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()
@palazzem
Copy link
Author

palazzem commented Oct 5, 2017

Requirements

  • Python 3.5+

Launch the application

Be sure that you're running python3, then:

$ python pygotham_asyncio_full_app.py
# Serving on ('127.0.0.1', 8000)
# (it waits for a request)

In another shell, launch multiple concurrent calls:

for i in $(eval echo "{1..10}"); do (curl "http://localhost:8000/?id=$i" &) ; done

The expected output should be:

GET /?id=1 HTTP/1.1
Host: localhost:8000
User-Agent: curl/7.54.0
Accept: */*

GET /?id=2 HTTP/1.1
Host: localhost:8000
User-Agent: curl/7.54.0
Accept: */*

# ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment