简体   繁体   中英

How to correctly end tornado requests?

I'm using Tornado as an API for a basic request to send an email. Depending on the sending result, I'd like to finish the request accordingly.

This is what I've done:

def get_routes(tornado_config):
    return [
        (r"/send", EmailHandler, tornado_config)
    ]

This is inside EmailHandler , result is the return of sending email:

if result:
        self.set_status(200)
        self.finish(json.dumps({"status":"ok", "result":result}))
        return ''
else:

        self.set_status(500)
        self.finish(json.dumps({"status": "error", "result":result }))
        return ''

The problem is that self.set_status (500) doesn't seem to add the 500 header.

Other solution would be:

    if result:
        return "ok"
    else:

        return "Message not sent"

But this doesn't respect any standard, as it gets returned at a json {"status":"success", "data":false} or something like that, even when the sending of email fails.

Simply write :

self.write({"status":"ok", "result":result})

instead of self.finish .

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