重定向

2020-08-09  本文已影响0人  小吉头

一、使用redirect()

import tornado.web
import tornado.ioloop


class IndexHandler(tornado.web.RequestHandler):
    def get(self,*args,**kwargs):
        self.redirect("http://www.baidu.com")

app = tornado.web.Application([
    (r'/index/$',IndexHandler),
])

app.listen(8888)

tornado.ioloop.IOLoop.instance().start()

浏览器响应头信息如下,浏览器会访问Location地址,示例返回的状态码是302

Response Headers:
HTTP/1.1 302 Found
Content-Length: 0
Date: Sat, 08 Aug 2020 13:45:35 GMT
Location: http://www.baidu.com
Content-Type: text/html; charset=UTF-8
Server: TornadoServer/6.0.4

查看redirect()的源码:

    def redirect(self, url: str, permanent: bool = False, status: int = None) -> None:
        """Sends a redirect to the given (optionally relative) URL.

        If the ``status`` argument is specified, that value is used as the
        HTTP status code; otherwise either 301 (permanent) or 302
        (temporary) is chosen based on the ``permanent`` argument.
        The default is 302 (temporary).
        """
        if self._headers_written:
            raise Exception("Cannot redirect after headers have been written")
        if status is None:
            status = 301 if permanent else 302
        else:
            assert isinstance(status, int) and 300 <= status <= 399
        self.set_status(status)
        self.set_header("Location", utf8(url))
        self.finish()

二、自己实现重定向

根据上面redirect()的源码可以自己定义状态码和Location,返回状态码302

import tornado.web
import tornado.ioloop


class IndexHandler(tornado.web.RequestHandler):
    def get(self,*args,**kwargs):
        self.set_status(302)
        self.set_header("Location","http://www.baidu.com")

app = tornado.web.Application([
    (r'/index/$',IndexHandler),
])

app.listen(8888)

tornado.ioloop.IOLoop.instance().start()

三、使用RedirectHandler类

import tornado.web
import tornado.ioloop
from tornado.web import RedirectHandler

app = tornado.web.Application([
    (r'/redirect/$',RedirectHandler,{"url":"http://www.baidu.com"}),
])

app.listen(8888)

tornado.ioloop.IOLoop.instance().start()

查看RedirectHandler类源码,最终还是调用了redirect(),返回的状态码是301

class RedirectHandler(RequestHandler):

    def initialize(self, url: str, permanent: bool = True) -> None:
        self._url = url
        self._permanent = permanent

    def get(self, *args: Any) -> None:
        to_url = self._url.format(*args)
        if self.request.query_arguments:
            # TODO: figure out typing for the next line.
            to_url = httputil.url_concat(
                to_url,
                list(httputil.qs_to_qsl(self.request.query_arguments)),  # type: ignore
            )
        self.redirect(to_url, permanent=self._permanent)

状态码301和302的区别

301表示永久重定向,比如访问 http://www.baidu.com 会跳转到 https://www.baidu.com301跳转在浏览器上有缓存,如果更换跳转地址,需清除浏览器的缓存
302表示临时重定向,比如未登陆的用户访问个人信息会重定向到登录页面

上一篇下一篇

猜你喜欢

热点阅读