龙卷风PUT请求缺失身体

时间:2013-03-20 21:08:25

标签: python tornado

我正在尝试使用龙卷风ASyncHTTPClient发出一个put请求,如下所示:

  data = { 'text': 'important text',
           'timestamp': 'an iso timestamp' }

  request = tornado.httpclient.HTTPRequest(URL, method = 'PUT', body = urllib.urlencode(data))

  response = yield Task(tornado.httpclient.ASyncHTTPClient().fetch, request)

但是,当请求到达其所需的端点时,尽管上面正确编码并定义了正文,但它似乎没有正文。有什么东西我在这里俯瞰吗?


3 个答案:

答案 0 :(得分:5)

如果另一端期待JSON,您可能需要设置“Content-Type”标头。试试这个:

data = { 'text': 'important text',
       'timestamp': 'an iso timestamp' }

headers = {'Content-Type': 'application/json; charset=UTF-8'}

request = tornado.httpclient.HTTPRequest(URL, method = 'PUT', headers = headers, body = simplejson.dumps(data))

response = yield Task(tornado.httpclient.ASyncHTTPClient().fetch, request)

这样,标题告诉服务器你正在发送JSON,而body是一个可以解析为JSON的字符串。

答案 1 :(得分:2)

问题可能在另一端。
使用Tornado 2.4.1的以下测试产生预期的输出。

import logging
import urllib

from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler, asynchronous
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from tornado import gen, options

log = logging.getLogger()
options.parse_command_line()

class PutBodyTest(RequestHandler):
    @asynchronous
    @gen.engine
    def get(self):
        data = {
            'text': 'important text',
            'timestamp': 'a timestamp'
        }
        req = HTTPRequest(
            'http://localhost:8888/put_body_test',
            method='PUT',
            body=urllib.urlencode(data)
        )
        res = yield gen.Task(AsyncHTTPClient().fetch, req)
        self.finish()

    def put(self):
        log.debug(self.request.body)

application = Application([
    (r"/put_body_test", PutBodyTest),
])

if __name__ == "__main__":
    application.listen(8888)
    IOLoop.instance().start()

日志输出:

$ python put_test.py --logging=debug
[D 130322 11:45:24 put_test:30] text=important+text&timestamp=a+timestamp
[I 130322 11:45:24 web:1462] 200 PUT /put_body_test (127.0.0.1) 0.37ms
[I 130322 11:45:24 web:1462] 200 GET /put_body_test (::1) 9.76ms

答案 2 :(得分:0)

这是预期JSON的发布请求!试试这个:

    @gen.coroutine
    def post(self):
        http_client = AsyncHTTPClient()
        http_client = tornado.httpclient.AsyncHTTPClient()

        URL = "http://localhost:1338/api/getPositionScanByDateRange"
        data = {"startDate":"2017-10-31 18:30:00","endDate":"2018-02-08 12:09:14","groupId":3} #A dictionary of your post data
        headers = {'Content-Type': 'application/json; charset=UTF-8'}

        record = yield http_client.fetch(URL, method = 'POST', headers = headers, body = json.dumps(data))

        if record.error:
            response = record.error
        else:
            response = record.body
        self.set_header('Content-Type', 'application/json')
        self.finish(response)