python - http.server 不按照 python.org 中的示例提供页面

标签 python httpserver

我正在尝试在本地网络上启动一个简单的目录服务器,但出现此错误

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.

关于python - http.server 不按照 python.org 中的示例提供页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43423370/

相关文章:

java - CORS 与 com.sun.net.httpserver

python - 在没有 '-it' 的情况下运行容器时只出现一行 SimpleHTTPServer 输出

python - keras 模型中损失的 nan 值

python - 在数据框中查找 "missing"值的最佳方法是什么?

python - 获取数据帧的协方差返回

linux - nginx: [emerg] 未知指令 ""在/etc/nginx/sites-enabled/example.com:3

java - 我怎样才能等到 HttpServer 完成(即加入其后台线程)?

ios - 如何在 Delphi 中使用 Indy HTTP Server 来接收 iOS 应用程序中的连接?

python - 可以从左侧截断的 Python 缓冲区?

python - 使用格式对数据框中的所有列进行绘制