zoukankan      html  css  js  c++  java
  • 基于Python+Django重定向的例子

    Django源码, 这里HttpResponseRedirect和HttpResponsePermanentRedirect没有太大差别,前者是返回302临时重定向,后者返回301永久重定向

     1 class HttpResponseRedirectBase(HttpResponse):
     2     allowed_schemes = ['http', 'https', 'ftp']
     3 
     4     def __init__(self, redirect_to, *args, **kwargs):
     5         super().__init__(*args, **kwargs)
     6         self['Location'] = iri_to_uri(redirect_to)
     7         parsed = urlparse(str(redirect_to))
     8         if parsed.scheme and parsed.scheme not in self.allowed_schemes:
     9             raise DisallowedRedirect("Unsafe redirect to URL with protocol '%s'" % parsed.scheme)
    10 
    11     url = property(lambda self: self['Location'])
    12 
    13     def __repr__(self):
    14         return '<%(cls)s status_code=%(status_code)d%(content_type)s, url="%(url)s">' % {
    15             'cls': self.__class__.__name__,
    16             'status_code': self.status_code,
    17             'content_type': self._content_type_for_repr,
    18             'url': self.url,
    19         }
    20 
    21 
    22 class HttpResponseRedirect(HttpResponseRedirectBase):
    23     status_code = 302
    24 
    25 
    26 class HttpResponsePermanentRedirect(HttpResponseRedirectBase):
    27     status_code = 301
    28 
    29 
    30 class HttpResponseNotModified(HttpResponse):
    31     status_code = 304
    32 
    33     def __init__(self, *args, **kwargs):
    34         super().__init__(*args, **kwargs)
    35         del self['content-type']
    36 
    37     @HttpResponse.content.setter
    38     def content(self, value):
    39         if value:
    40             raise AttributeError("You cannot set content to a 304 (Not Modified) response")
    41         self._container = []

    小栗子:

    1 def redirectdemo(request):
    2     dic_params = {'username': request.GET.get('username'),
    3                   'password': request.GET.get('password')}
    4     if validate_parameters(dic_params):
    5         return HttpResponsePermanentRedirect("http://www.baidu.com")
    6     else:
    7         return HttpResponse('<html>error page</html>')
  • 相关阅读:
    MySQL next-key lock 加锁范围是什么?
    使用 Docker 安装并连接 MySQL
    Mac 常用软件推荐 —— Java 开发工程师
    Toolkit 大更新:UI 更美观,用起来更方便!
    工作中的设计模式 —— 建造者模式
    工作中的设计模式 —— 策略模式
    工作中的设计模式 —— 原型模式
    Centos7 安装Oracle记录
    Centos7 常用命令和自己平时使用命令
    AutoHotKey 简易自动化脚本的一些资料
  • 原文地址:https://www.cnblogs.com/andrew209/p/9740044.html
Copyright © 2011-2022 走看看