Differences between BaseHttpServer and wsgiref.simple_server

I am looking for a module that provides me with the basic capabilities of an HTTP server for local access. Python seems to have two methods for implementing simple HTTP servers in the standard library: wsgiref.simple_server and BaseHttpServer .

What are the differences? Is there any good reason to prefer each other?

+5
source share
1 answer

Short answer: wsgiref.simple_server is a WSGI adapter through BaseHTTPServer .

Longer answer:

BaseHTTPServer (and the SocketServer on which it builds) is a module that implements most of the real HTTP server. He can accept requests and return responses, but he needs to know how to handle these requests. When you use BaseHTTPServer directly, you provide handlers by subclassing BaseHTTPRequestHandler , for example:

 from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler class MyHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-Type', 'text/plain') self.end_headers() self.wfile.write('Hello world!\n') HTTPServer(('', 8000), MyHandler).serve_forever() 

wsgiref.simple_server adapts this BaseHTTPServer interface to the WSGI specification, which is the standard for server-independent Python web applications. In WSGI, you provide a handler as a function, for example:

 from wsgiref.simple_server import make_server def my_app(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) yield 'Hello world!\n' make_server('', 8000, my_app).serve_forever() 

The make_server function returns an instance of WSGIServer that inherits most of the actual protocol / network logic from BaseHTTPServer.HTTPServer and SocketServer.TCPServer (although this ends with the redefinition of some simple HTTP rules). What basically differs is how you integrate your application code with this logic.

It really depends on the problem you are trying to solve, but encoding with wsgiref is probably the best idea, because it will be easier for you to switch to another production HTTP server like uWSGI or Gunicorn in the future.

+7
source

Source: https://habr.com/ru/post/1201596/


All Articles