python - 如何使用 Python 套接字在 HTTP 服务器中实现 POST 请求
问题描述
我正在使用带有套接字的 Python 中为网页设计制作本地 HTTP 服务器,并且我已经实现了处理 GET 请求,但我不确定如何实现 POST 请求。有人可以帮我吗?
我试过的:
- 在线搜索其他解决方案
- 研究其他服务器如何处理 POST 请求
期望:
- 处理基本的 POST 请求,例如文件上传或表单提交
这是我处理传入请求的代码块:
def handle_client(self, conn, addr):
BUFSIZ = 8192
while True:
try:
data = conn.recv(BUFSIZ).decode()
if data:
lines = data.split('\r\n')
req_line = lines[0]
req_method = req_line.split(' ')[0]
if req_method == 'GET':
response_line = b""
response_header = b""
blank_line = b"\r\n"
response_body = b""
requested_file = req_line.split(' ')[1]
if requested_file == '/':
requested_file = '/index.html'
else:
pass
filepath = self.content_dir + requested_file
print(f'Initiating webpage {filepath}')
try:
with open(filepath, 'rb') as f:
response_body = f.read()
response_line = self.create_response_line(status_code=200)
response_header = self.create_headers()
except Exception as e:
print(f'Something went wrong while trying to serve {filepath}')
response_line = self.create_response_line(status_code=404)
response_header = self.create_headers()
response_body = "<h1>{} {}</h1>".format(
404,
self.status_codes[404]
).encode('utf8')
response = b""
response += response_line
response += response_header
response += blank_line
response += response_body
conn.send(response)
conn.close()
break
else:
print(f'Unsupported request method: {req_method}')
else: break
except KeyboardInterrupt:
self.sv.shutdown()