How do I return HTTP error code without default template in Tornado?

后端 未结 7 2272
情深已故
情深已故 2021-02-01 02:40

I am currently using the following to raise a HTTP bad request:

raise tornado.web.HTTPError(400)

which returns a html output:

&         


        
7条回答
  •  南旧
    南旧 (楼主)
    2021-02-01 03:10

    This exchange clarifies some of the approaches suggested here, and discounts the reason keyword (which I was thinking about trying).

    Q: (by mrtn)

    "I want to use raise tornado.web.HTTPError(400, reason='invalid request') to pass a custom reason to the error response, and I hope to do this by overriding the write_error (self, status_code, **kwargs) method.

    "But it seems that I can only access self._reason inside write_error, which is not what I want. I also tried kwargs['reason'] but that does not exist."

    A: (by Tornado lead developer @bendarnell)

    "The exception that exposed the error is available to write_error as an exc_info triple in the keyword arguments. You can access the reason field with something like this:

    if "exc_info" in kwargs:
        e = kwargs["exc_info"][1]
        if isinstance(e, tornado.web.HTTPError):
            reason = e.reason
    

    "But note that the reason field is essentially deprecated (it is not present in HTTP/2), so it's probably not the best way to do whatever you're trying to do here (HTTPError's log_message field is a little better, but still not ideal). Just raise your own exception instead of using HTTPError; your write_error override can use self.set_status(400) when it sees the right kind of exception."

提交回复
热议问题