【问题标题】:Get file from POST request using Python's BaseHTTPServer使用 Python 的 BaseHTTPServer 从 POST 请求中获取文件
【发布时间】:2015-08-31 16:38:44
【问题描述】:

我正在运行下面的代码来获取 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' 对象没有属性 'FILES'

【问题讨论】:

    标签: python http post https httphandler


    【解决方案1】:

    BaseHTTPRequestHandler 将处理第一行和 http 请求的标头,然后将其余的留给您。 您需要使用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 表单文件上传,如 post 请求。

    【讨论】:

      【解决方案2】:

      一般在

      request.FILES
      

      字典

      【讨论】:

      • 也许在 Django 中,但这不是 Django。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多