http.server 未按照 python.org 中的示例提供页面
http.server not serving pages as per example from python.org
我正在尝试在本地网络上启动一个简单的目录服务器,但出现此错误
Error response
Error code: 501
Message: Unsupported method ('GET').
Error code explanation: HTTPStatus.NOT_IMPLEMENTED - Server does not
support this operation.
这是 https://docs.python.org/3/library/http.server.html 中给出的示例 如果我从命令行 运行 它可以工作 python3 -m http.server。我需要随着时间的推移控制这个服务器所以我需要打开它一段时间然后自动关闭它
from http.server import BaseHTTPRequestHandler, HTTPServer
def run(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler):
server_address = ('0.0.0.0', 8000)
httpd = server_class(server_address, handler_class)
httpd.serve_forever()
答案在您链接到的 documentation 中:
The HTTPServer
must be given a RequestHandlerClass
on
instantiation, of which this module provides three different variants:
class http.server.BaseHTTPRequestHandler(
request, client_address, server
)
This class is used to handle the HTTP requests that arrive at the
server. By itself, it cannot respond to any actual HTTP requests; it
must be subclassed to handle each request method (e.g. GET
or
POST
). ...
对于您的情况,您应该改用 http.server.SimpleHTTPRequestHandler
:
class http.server.SimpleHTTPRequestHandler(
request, client_address, server
)
This class serves files from the current directory and below, directly
mapping the directory structure to HTTP requests.
我正在尝试在本地网络上启动一个简单的目录服务器,但出现此错误
Error response
Error code: 501
Message: Unsupported method ('GET').
Error code explanation: HTTPStatus.NOT_IMPLEMENTED - Server does not support this operation.
这是 https://docs.python.org/3/library/http.server.html 中给出的示例 如果我从命令行 运行 它可以工作 python3 -m http.server。我需要随着时间的推移控制这个服务器所以我需要打开它一段时间然后自动关闭它
from http.server import BaseHTTPRequestHandler, HTTPServer
def run(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler):
server_address = ('0.0.0.0', 8000)
httpd = server_class(server_address, handler_class)
httpd.serve_forever()
答案在您链接到的 documentation 中:
The
HTTPServer
must be given aRequestHandlerClass
on instantiation, of which this module provides three different variants:
class http.server.BaseHTTPRequestHandler(
request, client_address, server
)
This class is used to handle the HTTP requests that arrive at the server. By itself, it cannot respond to any actual HTTP requests; it must be subclassed to handle each request method (e.g.
GET
orPOST
). ...
对于您的情况,您应该改用 http.server.SimpleHTTPRequestHandler
:
class http.server.SimpleHTTPRequestHandler(
request, client_address, server
)
This class serves files from the current directory and below, directly mapping the directory structure to HTTP requests.