【问题标题】:tornado async post error 500 but curl OK龙卷风异步发布错误 500 但卷曲正常
【发布时间】:2016-07-24 18:11:49
【问题描述】:

网址是http://*.*.*.*/100/?id=1&version=1

参数是

{"cityId": "110000", "query": {"queryStr": "line1", "queryExp": ""}, "channelId": "house"}

卷曲命令是:

curl -X POST -H "Content-Type: application/json" -d '{"cityId": "110000", "query": {"queryStr": "line1", "queryExp": ""}, "channelId": "house"}' "http://*.*.*.*/100/?id=1&version=1"

但是当我使用 tornado(4.2) AsyncHTTPClient 时,我得到了错误:

tornado.application:Future exception was never retrieved: Traceback (most recent call last):
...
HTTPError: HTTP 500: Internal Server Error

我这样要求:

@gen.coroutine
def request(self, url, method="GET", headers=None, data=None):
    logger.debug(method)
    logger.debug(headers)
    logger.debug(data)
    headers = {
        'content-type': 'application/json',
    }
    req = HTTPRequest(
        url,
        method=method,
        headers=headers,
        body=urllib.urlencode(data).encode('utf-8')
    )
    http_response = yield self.r.fetch(
        # req,
        # self.handle_request
        url,
        method=method,
        headers=headers,
        body=urllib.urlencode(data).encode('utf-8')
    )
    # logger.debug(http_response)
    raise gen.Return(json.loads(http_response.body))

【问题讨论】:

  • 你怎么称呼这个request函数?你在 python 代码中有method="GET",但在 curl 命令行中有-X POST
  • 我称它为这样的函数(方法等于“POST”):body = yield r.request( url, method=doc["method"], headers=doc["headers"], data=doc["data"] )

标签: python tornado


【解决方案1】:

您发送的是'content-type': 'application/json',,但使用body=urllib.urlencode(data).encode('utf-8') 编码数据。使用json.dumps 而不是urllib.urlencode

【讨论】:

  • thx,我试过你的建议,没有 500 状态错误,但我得到了这个:raise ValueError("No JSON object could be decoded") 在请求函数中返回时
  • 这是一个不同的问题,应该是一个单独的问题。打印出http_response.codehttp_response.headershttp_response.body 以查看您从服务器获得了什么。它真的给你json吗? (您没有发布 curl 命令的输出)
  • @BenDarnell 我遇到了同样的问题。当我在 HTTPVerb 方法中引发 HTTPError 时,我重新实现了默认的 write_error 方法。但它不起作用。当我们使用gen.coroutine时可以调用write_error方法吗?
  • @RyanChou 我看不出你的情况与这个问题或答案有什么关系(在任何地方都没有提到 write_error)。请将其作为一个包含更多详细信息的问题发布,而不是在几个月前的答案上制作 cmets。
  • @BenDarnell 我尝试了另一种方法来捕获协程中发生的异常并调用self._handle_request_exception(e) 来解决此问题。我最初重写了 RequestHandler.write_erorr 方法来实现我的自定义写入错误 json 响应模板。而我使用gen.coroutine 来异步我的HTTPVerb 方法(get/post/patch)。同时。我在这些方法中提出HTTPError。但它没有调用send_error 来调用write_error 方法。这让我很困惑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多