python - 使用 Python 的 BaseHTTPServer 从 POST 请求中获取文件

标签 python http post https httphandler

我正在运行下面的代码来获取 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/

相关文章:

python - "Third order"Kneser-Key 平滑的正确实现(对于 Trigram 模型)

python - 如何在给定 gps 原点的情况下找到附近的点?

http - HTTP 包服务器在生产中使用安全吗?

django - Tastypie "always_return_data"选项更改响应状态代码

http - ESP8266 HTTP 请求在中断时失败

angularjs $http post 不适用于 Chrome 浏览器

python - 如何检查结果集是否为空?

python - PyOpenGL: glutTimerFunc 回调缺少必需的参数 'value'

android - 使用 Retrofit 发送 POST 参数

android - 在 Android 中发布大文件