Различия между BaseHttpServer и wsgiref.simple_server
Я ищу модуль, который предоставляет мне основные возможности http-сервера для локального доступа. Похоже, что в Python есть два метода для реализации простых http-серверов в стандартной библиотеке: wsgiref.simple_server и BaseHttpServer.
Какие есть отличия? Есть ли веская причина, чтобы предпочесть одно другому?
1 ответ
Короткий ответ: wsgiref.simple_server
это адаптер WSGI поверх BaseHTTPServer
,
Более длинный ответ:
BaseHTTPServer
(а также SocketServer
, на котором он строится) - это модуль, который реализует большую часть реального HTTP-сервера. Он может принимать запросы и возвращать ответы, но он должен знать, как обрабатывать эти запросы. Когда вы используете BaseHTTPServer
напрямую, вы предоставляете обработчики с помощью подклассов BaseHTTPRequestHandler
, например:
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
адаптирует это BaseHTTPServer
interface to the WSGI specification, which is the standard for server-independent Python web applications. In WSGI, you provide the handler in the form of 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()
make_server
function returns an instance of WSGIServer
, which inherits most of the actual protocol/network logic from BaseHTTPServer.HTTPServer
а также SocketServer.TCPServer
(although it does end up reimplementing some simple rules of HTTP). What mainly differs is the way you integrate your application code with that logic.
It really depends on the problem you're trying to solve, but coding against wsgiref
is probably a better idea because it will make it easy for you to move to a different, production-grade HTTP server, such as uWSGI or Gunicorn, in the future.