2015-08-31 52 views
10

我正在運行下面的代碼來獲取POST消息。如何獲取文件(通過POST發送)以及如何響應HTTP狀態代碼200好嗎?使用Python的BaseHTTPServer從POST請求獲取文件

#!/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'

回答

1

正是在

request.FILES 

字典一般可用

+0

在Django也許,但這不是Django。 –

8

BaseHTTPRequestHandler會處理第一行和HTTP請求,然後離開,其餘由你的頭。 你需要閱讀使用BaseHTTPRequestHandler.rfile

您可以使用self.send_response(200)請求的其餘部分給你指定的curl命令與200 OK

應對以下應該回答你的問題:

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表單文件 - 像發佈請求一樣上傳。