我是Web服务器的新手,我尝试使用python中的http.server
模块构建一个简单的服务器。我正在使用显示表单的本地服务器,通过提交此表单,它应该重定向以显示消息,因此我使用了send_response(303)
,但没有重定向到主页,而是发送了200条响应。
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import parse_qs
memory = []
form = '''<!DOCTYPE html>
<title>Message Board</title>
<form method="POST">
<textarea name="message"></textarea>
<br>
<button type="submit">Post it!</button>
</form>
<pre>
{}
</pre>
'''
class MessageHandler(BaseHTTPRequestHandler):
def do_POST(self):
# How long was the message?
length = int(self.headers.get('Content-length', 0))
# Read the correct amount of data from the request.
data = self.rfile.read(length).decode()
# Extract the "message" field from the request data.
message = parse_qs(data)["message"][0]
# Escape HTML tags in the message so users can't break world+dog.
message = message.replace("<", "<")
# Store it in memory.
memory.append(message)
# 1. Send a 303 redirect back to the root page.
self.send_response(303)
self.send_header('Content-type', 'text/html; charset=utf-8')
self.send_header('Location', '/') #This will navigate to the original page
self.end_headers()
def do_GET(self):
# First, send a 200 OK response.
self.send_response(200)
# Then send headers.
self.send_header('Content-type', 'text/html; charset=utf-8')
self.end_headers()
# 2. Put the response together out of the form and the stored messages.
response = ""
for message in memory:
response += f"{message}\n"
# 3. Send the response.
self.wfile.write(form.format(response).encode())
if __name__ == '__main__':
server_address = ('', 8000)
httpd = HTTPServer(server_address, MessageHandler)
httpd.serve_forever()
答案 0 :(得分:0)
我认为这按您的预期进行。
这是通话记录
127.0.0.1 - - [26/Feb/2020 10:42:23] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [26/Feb/2020 10:42:23] "GET /favicon.ico HTTP/1.1" 200 -
127.0.0.1 - - [26/Feb/2020 10:42:39] "POST / HTTP/1.1" 303 -
127.0.0.1 - - [26/Feb/2020 10:42:39] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [26/Feb/2020 10:42:39] "GET /favicon.ico HTTP/1.1" 200 -
当您执行POST
时,它返回303,当浏览器收到它触发另一个GET
请求时,服务器以200响应