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

Bob*_*Bob 11 python https post http httphandler

我正在运行下面的代码来获取POST消息.如何获取文件(使用POST发送)以及如何使用HTTP状态代码进行响应200?

#!/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
Run Code Online (Sandbox Code Playgroud)

AttributeError:'SSLSocket'对象没有属性'FILES'

Jer*_*len 9

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)
Run Code Online (Sandbox Code Playgroud)

请注意,通过-d @../some.file在curl命令中使用,您说"这是一个ascii文件,哦,并删除新行和回车请",因此您使用的文件与请求中获得的数据之间可能存在差异.您的curl命令不会模拟html表单文件上传,如post请求.


hsp*_*her -1

它一般可以在

request.FILES
Run Code Online (Sandbox Code Playgroud)

字典