G
G
GitCat2020-07-23 17:05:37
Python
GitCat, 2020-07-23 17:05:37

An asynchronous HTTP server without the use of ready-made web timeworks. Python 3 http.server. How?

I have a server:

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 it works synchronously, because it serves only 1 client at 1 point in time.

Is it possible to make this server asynchronous NOT using ready-made web frameworks ( fundamentally important )? If so, how?

I tried to do this:

webServer = ThreadingHTTPServer(("", serverPort), Server)

Instead: But I'm not sure if it works because I haven't noticed any changes.
webServer = HTTPServer(("", serverPort), Server)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dimonchik, 2020-07-23
@GitCat

asyncio with 3.6 fully
pick

V
Vladimir Korotenko, 2020-07-23
@firedragon

Why reinvent the wheel? There are a bunch of servers, one of the most famous is nginx

A
Alexander, 2020-07-23
@NeiroNx

https://gunicorn.org/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question