如何在Tornado中使用POST方法?

时间:2012-04-28 22:10:19

标签: python post tornado

我正在尝试使用Tornado启动服务器并向其发布字符串。我已经找到了很多关于如何在处理程序类中编写post方法的示例,但没有关于如何编写post请求的示例。我当前的代码确实导致post方法执行,但get_argument没有获取数据 - 它只是每次都打印默认的“No data received”。我做错了什么?

我的代码如下所示:

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()

将要发送的字符串放入“body”参数中是正确的吗?在我看到的一些例子中,如here,似乎人们创建了自己的参数,但是如果我尝试在请求中添加新参数,比如

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

我刚收到一条错误,说“TypeError: init ()有一个意外的关键字参数'data'”

谢谢!

1 个答案:

答案 0 :(得分:33)

  

似乎人们创建了自己的参数

不完全。来自文档:

  

fetch(request,** kwargs)

     

执行请求,返回一个   类HTTPResponse。

     

请求可以是字符串URL或HTTPRequest对象。如果它   是一个字符串,我们使用任何其他kwargs构造HTTPRequest:   HTTPRequest(请求,** kwargs)

Link

所以kwargs实际上来自this method

无论如何,问题的真正含义:你如何发送POST数据?你是在正确的轨道上,但你需要url编码你的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')