Skip to content

Instantly share code, notes, and snippets.

@nestarz
Created June 23, 2020 19:05
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 nestarz/e9ce015dc7de78f5f03ea0703309c203 to your computer and use it in GitHub Desktop.
Save nestarz/e9ce015dc7de78f5f03ea0703309c203 to your computer and use it in GitHub Desktop.
Async HTTP Client/Server Test with custom log
import asyncio
import http.server
import http.client
class LogHTTPHandler(http.server.SimpleHTTPRequestHandler):
log_file = open('access.log', 'w', 1)
def log_message(self, format, *args):
self.log_file.write(
f"{self.client_address[0]} - - [{self.log_date_time_string()}] {format % args}\n"
)
async def get(loop):
conn = http.client.HTTPConnection("localhost", 8080)
await loop.run_in_executor(None, lambda: conn.request("GET", "/"))
conn.close()
loop.stop()
def test_connection():
loop = asyncio.get_event_loop()
server = http.server.HTTPServer(("localhost", 8080), LogHTTPHandler)
asyncio.ensure_future(loop.run_in_executor(None, server.serve_forever))
asyncio.ensure_future(get(loop))
loop.run_forever()
server.shutdown()
server.server_close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment