6

次のような竜巻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)

ただし、リクエストが目的のエンドポイントに到達すると、上記の本文が適切にエンコードおよび定義されているにもかかわらず、本文がないように見えます。ここで見落としているものはありますか?


4

3 に答える 3

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 を送信していることをサーバーに伝え、本文は JSON として解析できる文字列です。

于 2013-03-25T22:14:54.897 に答える
2

The issue is probably on the other end.
The following test using Tornado 2.4.1 yields the expected output.

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

Log output:

$ 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
于 2013-03-22T18:53:13.063 に答える