gpt4 book ai didi

Python SimpleHTTPServer 404 页面

转载 作者:行者123 更新时间:2023-12-04 21:42:43 24 4
gpt4 key购买 nike

我最近一直在使用 Python 的 SimpleHTTPServer 在我的网络上托管文件。我想要一个自定义的 404 页面,所以我对此进行了研究并得到了一些答案,但我仍然想使用我拥有的这个脚本。那么,我必须添加什么才能在此脚本中添加 404 页面?

import sys
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler


HandlerClass = SimpleHTTPRequestHandler
ServerClass = BaseHTTPServer.HTTPServer
Protocol = "HTTP/1.0"

if sys.argv[1:]:
port = int(sys.argv[1])
else:
port = 80
server_address = ('192.168.1.100', port)

HandlerClass.protocol_version = Protocol
httpd = ServerClass(server_address, HandlerClass)

sa = httpd.socket.getsockname()
print "Being served on", sa[0], "port", sa[1], "..."
httpd.serve_forever()

最佳答案

您实现自己的请求处理程序类并覆盖 send_error更改 error_message_format 的方法仅当代码为 404 时:

import os
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler

class MyHandler(SimpleHTTPRequestHandler):
def send_error(self, code, message=None):
if code == 404:
self.error_message_format = "Does not compute!"
SimpleHTTPRequestHandler.send_error(self, code, message)


if __name__ == '__main__':
httpd = HTTPServer(('', 8000), MyHandler)
print("Serving app on port 8000 ...")
httpd.serve_forever()

默认 error_message_format是:
# Default error message template
DEFAULT_ERROR_MESSAGE = """\
<head>
<title>Error response</title>
</head>
<body>
<h1>Error response</h1>
<p>Error code %(code)d.
<p>Message: %(message)s.
<p>Error code explanation: %(code)s = %(explain)s.
</body>
"""

关于Python SimpleHTTPServer 404 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22467908/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com