Async Python 3 HTTP-Server without any ready-made web-frameworks. How?

Viewed 278

I have a server on python:

from http.server import BaseHTTPRequestHandler, HTTPServer

class Server(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write("Hello, World!".encode("utf-8"))


    def do_POST(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write("POST!".encode("utf-8"))

webServer = HTTPServer(("", serverPort), Server)
print(f"Server started at http://localhost:{serverPort}")

try:
    webServer.serve_forever()
except KeyboardInterrupt:
    webServer.server_close()
    print("Server stopped.")

But this server works synchronously.

Is it possible to create async HTTP-server without using ready-made web frameworks? If yes, how?

I tried to do this:

webServer = ThreadingHTTPServer(("", serverPort), Server)
print(f"Server started at http://localhost:{serverPort}")

instead of this:

webServer = HTTPServer(("", serverPort), Server)
print(f"Server started at http://localhost:{serverPort}")

But i am not sure, that it is working.

1 Answers

As per @furas's suggestion, I created a sample server based on doc:

import asyncio
from aiohttp import web

async def handle(request):
    name = request.match_info.get('name', "Anonymous")
    text = "Hello, " + name
    print('Request served!')
    return web.Response(text=text)

async def run_web_server():
    app = web.Application()
    app.add_routes([web.get('/', handle),
                    web.get('/{name}', handle)])
    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, 'localhost', 8080)
    await site.start()

async def run_other_task():
    while True:
        await asyncio.sleep(1)

loop = asyncio.get_event_loop()
loop.create_task(run_web_server())
loop.run_until_complete(run_other_task())
loop.run_forever()
Related