jeudi 23 juillet 2020

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

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.




Aucun commentaire:

Enregistrer un commentaire