详解如何用django实现redirect的几种方法总结

yipeiwu_com6年前Python基础

用django开发web应用, 经常会遇到从一个旧的url转向一个新的url。这种隐射也许有规则,也许没有。但都是为了实现业务的需要。总体说来,有如下几种方法实现 django的 redirect。

1. 在url 中配置 redirect_to 或者 RedirectView(django 1.3 版本以上)
2. 在view 中 通过 HttpResponseRedirect 实现 redirect
3. 利用 django 的 redirects app实现

1 在url 中配置 redirect_to 或者 RedirectView(django 1.3 版本以上)

from django.views.generic.simple import redirect_to
urlpatterns = patterns('',
  (r'^one/$', redirect_to, {'url': '/another/'}),
)

from django.views.generic import RedirectView
urlpatterns = patterns('',
  (r'^one/$', RedirectView.as_view(url='/another/')),
)

2. 在view 中 通过 HttpResponseRedirect 实现 redirect

from django.http import HttpResponseRedirect
 
def myview(request):
  ...
  return HttpResponseRedirect("/path/")

3. 利用 django 的 redirects app实现

1. 在settings.py 中  增加 'django.contrib.redirects' 到你的 INSTALLED_APPS 设置.
2. 增加 'django.contrib.redirects.middleware.RedirectFallbackMiddleware' 到你的MIDDLEWARE_CLASSES 设置中.
3. 运行 manage.py syncdb. 创建 django_redirect 这个表,包含了 site_id, old_path and new_path 字段.

主要工作是 RedirectFallbackMiddleware  完成的,如果 django  发现了404 错误,这时候,就会进django_redirect 去查找,有没有匹配的URL 。如果有匹配且新的RUL不为空则自动转向新的URL,如果新的URL为空,则返回410. 如果没有匹配,仍然按原来的错误返回。

注意,这种仅仅处理 404 相关错误,而不是 500 错误的。

增加删除 django_redirect 表呢?

from django.db import models
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
 
@python_2_unicode_compatible
class Redirect(models.Model):
  site = models.ForeignKey(Site)
  old_path = models.CharField(_('redirect from'), max_length=200, db_index=True,
    help_text=_("This should be an absolute path, excluding the domain name. Example: '/events/search/'."))
  new_path = models.CharField(_('redirect to'), max_length=200, blank=True,
    help_text=_("This can be either an absolute path (as above) or a full URL starting with 'http://'."))
 
  class Meta:
    verbose_name = _('redirect')
    verbose_name_plural = _('redirects')
    db_table = 'django_redirect'
    unique_together=(('site', 'old_path'),)
    ordering = ('old_path',)
 
  def __str__(self):
    return "%s ---> %s" % (self.old_path, self.new_path)

采用类似如上的MODEL ,另外用DJANGO相关ORM 就可以实现save,delete了。

以上三种方法都可以实现 django redirect,其实最常用的,是第一种与第二种,第三种方法很少用。

相关文章

Python首次安装后运行报错(0xc000007b)的解决方法

Python首次安装后运行报错(0xc000007b)的解决方法

错误提示如下: 其实这是一个挺常见的系统报错,缺乏VC++库。 我安装的是python3.5.2,这个版本需要的vc版本是2015的了,下载:Microsoft Visual C++...

Django中的CACHE_BACKEND参数和站点级Cache设置

CACHE_BACKEND参数 每个缓存后端都可能使用参数。 它们在CACHE_BACKEND设置中以查询字符串形式给出。 有效参数如下:     t...

python实现excel读写数据

本文实例为大家分享了python操作EXCEL的实例源码,供大家参考,具体内容如下 读EXCEL的操作:把excel的数据存储为字典类型 #coding=utf8 #导入读ex...

python cx_Oracle模块的安装和使用详细介绍

python cx_Oracle模块的安装 最近需要写一个数据迁移脚本,将单一Oracle中的数据迁移到MySQL Sharding集群,在linux下安装cx_Oracle感觉还是有一...

python3.7将代码打包成exe程序并添加图标的方法

python3.7将代码打包成exe程序并添加图标的方法

1、环境 1、python 3.7 2、pyinstaller 2、下载方式: 2.1 python安装(略) 2.2 安装pyinstaller 打开DOS窗口输入以下命令:...