如何在Tornado中使用POST方法?

use*_*445 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()
Run Code Online (Sandbox Code Playgroud)

将我要发送的字符串放在"body"参数中是正确的做法吗?在我看到的一些例子中,就像这里一样,人们似乎创建了自己的参数,但是如果我尝试在请求中添加新参数,就像

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

我只是得到一个错误,说"TypeError:init()得到一个意外的关键字参数'data'"

谢谢!

The*_*uhn 35

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

不完全的.来自文档:

获取(请求,**kwargs)

执行请求,返回HTTPResponse.

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

(链接)

所以kwargs实际上来自这种方法.

无论如何,问题的真正含义:你如何发送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!
Run Code Online (Sandbox Code Playgroud)

然后获取数据:

data = self.get_argument('data', 'No data received')
Run Code Online (Sandbox Code Playgroud)

  • 在 **python3** 及以上:`urllib.parse.urlencode(post_data)` (2认同)