Search code examples
pythonnginxtornado

How can tornado set_status 307


I use tornado 4.3 in python 2.7 . I want to redirect one request to another one.For example, when I POST http://127.0.0.1/ , I wanna it posting to https://myip.ipip.net/.This can be done by nginx using conf below

return  307  $scheme://myip.ipip.net$request_uri;

But now the target URL is not always the same so I cannot hard code in nginx. As my server is tornado , I should make it work using code. As we know tornado supports set HTTP code using self.set_status(HTTP_CODE). But when I set 307 it responses 302 to client.What's wrong ?

Here is my code

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def post(self):
        self.set_status(307)
        self.redirect("https://myip.ipip.net/") #

application = tornado.web.Application([
    (r"/", MainHandler),
])

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

Here is my test with curl.Tornado responsed 302 though I set 307.

curl -LI 127.0.0.1:8888 -XPOST

Result is below

HTTP/1.1 302 Found
Date: Wed, 10 May 2017 07:31:17 GMT
Content-Length: 0
Content-Type: text/html; charset=UTF-8
Location: https://myip.ipip.net/
Server: TornadoServer/4.3

HTTP/1.1 200 OK
Server: NewDefend
Date: Wed, 10 May 2017 07:31:18 GMT
Content-Type: text/plain; charset=utf-8
Content-Length: 69
Connection: keep-alive
X-Cache:  from ctl-zj-122-228-198-138

Thank you !


Solution

  • redirect takes a status parameter:

    class MainHandler(tornado.web.RequestHandler):
        def post(self):
            self.redirect("https://myip.ipip.net/", status=307)