Skip to content

Instantly share code, notes, and snippets.

@telendt
Last active December 29, 2015 21:49
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 telendt/7732021 to your computer and use it in GitHub Desktop.
Save telendt/7732021 to your computer and use it in GitHub Desktop.
aiohttp pipelining
$ time echo 'GET /first?delay=1 HTTP/1.1
Host: localhost:8080
Connection: keep-alive
GET /last?delay=1 HTTP/1.1
Host: localhost:8080
Connection: close
' | unix2dos | nc localhost 8080 > /dev/null
real 0m2.018s
user 0m0.010s
sys 0m0.006s
#!/usr/bin/env bash
from aiohttp import server, Response, HttpErrorException
from asyncio import coroutine, get_event_loop, sleep
from urllib.parse import urlsplit, parse_qs
class HttpServer(server.ServerHttpProtocol):
@coroutine
def handle_request(self, message, payload):
if message.method != 'GET':
raise HttpErrorException(405)
response = Response(self.transport, 204, close=message.should_close)
qs = parse_qs(urlsplit(message.path).query)
yield from sleep(int(qs.get('delay', [1])[0]))
response.send_headers()
response.write_eof()
if response.keep_alive():
self.keep_alive(True)
if __name__ == '__main__':
loop = get_event_loop()
f = loop.create_server(
lambda: HttpServer(keep_alive=10), '0.0.0.0', 8080)
svr = loop.run_until_complete(f)
try:
loop.run_forever()
except KeyboardInterrupt:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment