我正在运行下面的代码来获取 POST 消息。如何获取文件(通过 POST 发送)以及如何使用 HTTP 状态代码 200
OK 响应?
#!/usr/bin/env python
import ssl
import BaseHTTPServer, SimpleHTTPServer
from BaseHTTPServer import BaseHTTPRequestHandler
class HttpHandler(BaseHTTPRequestHandler):
def do_POST(self):
print "got POST message"
# how do I get the file here?
print self.request.FILES
httpd = BaseHTTPServer.HTTPServer(('localhost', 4443), HttpHandler)
httpd.socket = ssl.wrap_socket(httpd.socket, certfile='./server.pem', server_side=True)
httpd.serve_forever()
$curl -X POST -d @../some.file https://localhost:4443/resource --insecure
AttributeError: 'SSLSocket' object has no attribute 'FILES'
最佳答案
BaseHTTPRequestHandler 将处理 http 请求的第一行和 header ,然后将其余部分留给您。
您需要使用 BaseHTTPRequestHandler.rfile
阅读请求的其余部分
您可以使用 self.send_response(200)
来响应 200 OK
鉴于您指定的 curl 命令,以下应该回答您的问题:
class HttpHandler(BaseHTTPRequestHandler):
def do_POST(self):
content_length = int(self.headers['Content-Length'])
file_content = self.rfile.read(content_length)
# Do what you wish with file_content
print file_content
# Respond with 200 OK
self.send_response(200)
请注意,通过在你的 curl 命令中使用 -d @../some.file
你是在说“这是一个 ascii 文件,哦,请去掉换行符和回车符”,因此您正在使用的文件和您在请求中获得的数据之间可能存在差异。您的 curl 命令不会像发布请求那样模拟 html 表单文件上传。
关于python - 使用 Python 的 BaseHTTPServer 从 POST 请求中获取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32315951/