2010-12-19 13 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() 

しかし、そのマシンのHTTP POST要求をポート80で実行しているときに、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要求本体を出力しました。

Twistedを使用してHTTP POSTリクエストボディを取得するにはどうすればよいですか? ありがとうございます。

答えて

7

改行が含まれていないか改行で終わっていないため、リクエスト本体が印刷されていないと思われます。そこで、あなたはPrintPostBodyインスタンスの解析バッファに入り、完全な行が受信されたことを示す改行を待って永遠にそこに座っていました。 LineReceiverは、フルラインを受信するまでlineReceivedコールバックを呼び出さない。

代わりに、あなたはツイストWebがあなたのため、この解析をやらせることができます。

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

ありがとうございました。私は試してみましょう... –

+0

ええ間違いなくあなたは正しいです。 LineReceiverが永久に待機するように、HTTP POSTリクエストボディの最後にCRLFはありません。 +1この重要な部分:)私は代わりにrawDataReceived()を使用しようとし、それが働いた。 –

+0

"request.content.read()"は、ねじれた性質からの呼び出しをブロックしていませんか? – darkk