2012-04-28 100 views
18

我正在嘗試使用Tornado啓動服務器並向其發佈字符串。我發現了很多關於如何在處理程序類中編寫post方法的示例,但沒有關於如何編寫post請求的示例。我當前的代碼確實會導致post方法執行,但get_argument沒有獲取數據 - 它只是每次打印默認的「No data received」。我究竟做錯了什麼?如何在Tornado中使用POST方法?

我的代碼如下所示:

class MainHandler(tornado.web.RequestHandler): 
    def post(self): 
     data = self.get_argument('body', 'No data received') 
     self.write(data) 

application = tornado.web.Application([ 
    (r"/", MainHandler), 
]) 

if __name__ == "__main__": 

    def handle_request(response): 
     if response.error: 
      print "Error:", response.error 
     else: 
      print response.body 
     tornado.ioloop.IOLoop.instance().stop() 

    application.listen(8888)  
    test = "test data" 
    http_client = tornado.httpclient.AsyncHTTPClient() 
    http_client.fetch("http://0.0.0.0:8888", handle_request, method='POST', headers=None, body=test) 
    tornado.ioloop.IOLoop.instance().start() 

是把我想要的「身體」發送字符串參數正確的事是什麼?在一些例子中我已經看到了,像here,似乎人們創建自己的參數,但如果我嘗試一個新的參數添加到請求,比如

http_client.fetch("http://0.0.0.0:8888", handle_request, method='POST', headers=None, data=test) 

我只是得到一個錯誤說「類型錯誤:init()得到了一個意想不到的關鍵字參數'data'「

謝謝!

回答

32

it seems people create their own parameters

不完全。從文檔:

fetch(request, **kwargs)

Executes a request, returning an HTTPResponse.

The request may be either a string URL or an HTTPRequest object. If it is a string, we construct an HTTPRequest using any additional kwargs: HTTPRequest(request, **kwargs)

Link

所以kwargs實際上是從this method

不管怎樣,對於問題的真正含義:您如何發送POST數據?你在正確的軌道上,但你需要對你的POST數據進行網址編碼,並將其用作你的身體kwarg。就像這樣:

import urllib 
post_data = { 'data': 'test data' } #A dictionary of your post data 
body = urllib.urlencode(post_data) #Make it into a post request 
http_client.fetch("http://0.0.0.0:8888", handle_request, method='POST', headers=None, body=body) #Send it off! 

然後獲取數據:

data = self.get_argument('data', 'No data received') 
+0

正是我需要的,謝謝! – user1363445 2012-04-29 13:29:41