2010-12-19 84 views
2

我試圖通過使用t.p.basic.LineReceiver獲取HTTP POST請求正文,但失敗。我的代碼是下面列出:無法使用Twisted獲取HTTP POST請求正文

from twisted.internet import reactor, protocol 
from twisted.protocols import basic 

class PrintPostBody(basic.LineReceiver): 
    def __init__(self): 
     self.line_no = 0 

    def lineReceived(self, line): 
     print '{0}: {1}'.format(str(self.line_no).rjust(3), repr(line)) 
     self.line_no += 1 

    def connectionLost(self, reason): 
     print "conn lost" 

class PPBFactory(protocol.ServerFactory): 
    protocol = PrintPostBody 

def main(): 
    f = PPBFactory() 
    reactor.listenTCP(80, f) 
    reactor.run() 


if __name__ == '__main__': 
    main() 

但是,當我在端口80做HTTP POST請求發送到該機器中,僅HTTP請求頭打印出。 輸出示例:

0: 'POST/HTTP/1.0' 
    1: 'Host: ###.##.##.##' 
    2: 'Referer: http://#.#####.###/?ssid=0&from=0&bd_page_type=1&uid=wiaui_1292470548_2644&pu=sz%40176_229,sz%40176_208' 
    3: 'Content-Length: 116' 
    4: 'Origin: http://#.#####.###' 
    5: 'Content-Type: application/x-www-form-urlencoded' 
    6: 'Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5' 
    7: 'User-Agent: Mozilla/5.0 (X11; U; Linux i686 (x86_64); en-US) AppleWebKit/534.11 (KHTML, like Gecko) Chrome/9.0.565.0 Safari/534.11' 
    8: 'Accept-Encoding: gzip,deflate,sdch' 
    9: 'Accept-Language: en-US,en;q=0.8' 
10: 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3' 
11: 'Via: 1.1 #####.###.###.##:8080 (squid/2.6.STABLE21)' 
12: 'X-Forwarded-For: ###.##.###.###' 
13: 'Cache-Control: max-age=0' 
14: 'Connection: keep-alive' 
15: '' 

所以連接未關閉,在這裏,但POST身體也不接收。

我已通過運行sudo nc -l 80測試了網絡狀況,並確實打印了HTTP POST請求主體。

那麼,我怎麼能得到HTTP POST請求正文使用扭曲? 非常感謝。

回答

7

我懷疑你沒有看到請求主體打印出來,因爲它沒有包含任何換行符或以換行符結束。因此,它進入了PrintPostBody實例的解析緩衝區,並永遠坐在那裏,等待換行符指示已收到完整行。 LineReceiver不會調用lineReceived回調,直到收到完整的一行。

相反,你可以讓扭曲的網站爲你做這個解析:

from twisted.web.server import Site # Site is a server factory for HTTP 
from twisted.web.resource import Resource 
from twisted.internet import reactor 

class PrintPostBody(Resource): # Resources are what Site knows how to deal with 
    isLeaf = True # Disable child lookup 

    def render_POST(self, request): # Define a handler for POST requests 
     print request.content.read() # Get the request body from this file-like object 
     return "" # Define the response body as empty 

reactor.listenTCP(80, Site(PrintPostBody())) 
reactor.run() 
+0

非常感謝你。讓我試試... – 2010-12-19 15:47:32

+0

是的,你是對的。 HTTP POST請求主體末尾沒有CRLF,因此LineReceiver將永遠等待。 +1這個關鍵部分:)然後我嘗試使用rawDataReceived()來代替它並工作。 – 2010-12-19 16:06:11

+0

是不是「request.content.read()」阻止對扭曲的性質? – darkk 2012-09-25 08:34:30