简体   繁体   中英

Return a pure json error in Tornado

def get(self):
    self.set_status(400, '["reason"]')
    self.finish()
    return

When you get this response you can get response.error.message which has the message HTTP 400: ["reason"] . But what if you wanted a pure json response as an error. What would be the best way to get that?

The second argument to set_status() is the "reason" string, ie the "Not Found" in HTTP/1.1 404 Not Found . It's human-readable, not machine readable, and many HTTP clients simply discard it. You should only use this parameter when you are sending a status code that is not found in the standard list.

Instead, when you want to send a JSON message along with an error, call self.set_status(code) , and then write your output as usual into the body:

self.set_status(400)
self.finish({"reason": reason})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM