2010-11-20 108 views
39

給出了最簡單的HTTP服務器,我如何在BaseHTTPRequestHandler中獲得post變量?Python:如何從BaseHTTPRequestHandler HTTP POST處理程序獲取鍵/值對?

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer 

class Handler(BaseHTTPRequestHandler): 
    def do_POST(self): 
     # post variables?! 

server = HTTPServer(('', 4444), Handler) 
server.serve_forever() 

# test with: 
# curl -d "param1=value1&param2=value2" http://localhost:4444 

我只是想獲得param1和param2的值。謝謝!

回答

53
def do_POST(self): 
    ctype, pdict = cgi.parse_header(self.headers.getheader('content-type')) 
    if ctype == 'multipart/form-data': 
     postvars = cgi.parse_multipart(self.rfile, pdict) 
    elif ctype == 'application/x-www-form-urlencoded': 
     length = int(self.headers.getheader('content-length')) 
     postvars = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1) 
    else: 
     postvars = {} 
    ... 
+0

也許你會看到這個:)你知道任何方式postvars可以在處理程序類之外使用? – KevinDTimm 2011-06-01 16:07:55

+0

@KevinDTimm,這是...哦,大約一年後,但如果你添加一個[靜態成員](http://stackoverflow.com/a/3506218/344286)處理程序類,那麼你可以訪問它任何可以訪問課程的地方。 – 2012-05-10 12:23:31

+0

@WayneWerner - 我確實看到了這個(愛名牌!)。謝謝。 – KevinDTimm 2012-05-14 14:47:43

27

我試圖編輯的帖子,結果被拒絕了,所以我的這個代碼,應該在Python 2.7版和3.2工作的版本:

from sys import version as python_version 
from cgi import parse_header, parse_multipart 

if python_version.startswith('3'): 
    from urllib.parse import parse_qs 
    from http.server import BaseHTTPRequestHandler 
else: 
    from urlparse import parse_qs 
    from BaseHTTPServer import BaseHTTPRequestHandler 

class RequestHandler(BaseHTTPRequestHandler): 

    ... 

    def parse_POST(self): 
     ctype, pdict = parse_header(self.headers['content-type']) 
     if ctype == 'multipart/form-data': 
      postvars = parse_multipart(self.rfile, pdict) 
     elif ctype == 'application/x-www-form-urlencoded': 
      length = int(self.headers['content-length']) 
      postvars = parse_qs(
        self.rfile.read(length), 
        keep_blank_values=1) 
     else: 
      postvars = {} 
     return postvars 

    def do_POST(self): 
     postvars = self.parse_POST() 
     ... 

    ...