用django開發(fā)web應用, 經常會遇到從一個舊的url轉向一個新的url。這種隱射也許有規(guī)則腿椎,也許沒有灾常。但都是為了實現(xiàn)業(yè)務的需要舌仍。總體說來泰偿,有如下幾種方法實現(xiàn) django的 redirect熄守。
1. 在url 中配置 redirect_to 或者 RedirectView(django 1.3 版本以上)
2. 在view 中 通過 HttpResponseRedirect 實現(xiàn) redirect
3. 利用 django 的 redirects app實現(xiàn)
1 在url 中配置 redirect_to 或者 RedirectView(django 1.3 版本以上)
[python]view plaincopy
from?django.views.generic.simpleimport?redirect_to
urlpatterns?=?patterns('',
(r'^one/$',?redirect_to,?{'url':'/another/'}),
)
[python]view plaincopy
from?django.views.genericimport?RedirectView
urlpatterns?=?patterns('',
(r'^one/$',?RedirectView.as_view(url='/another/')),
)
2. 在view 中 通過 HttpResponseRedirect 實現(xiàn) redirect
[python]view plaincopy
from?django.httpimport?HttpResponseRedirect
def?myview(request):
...
return?HttpResponseRedirect("/path/")
3. 利用 django 的 redirects app實現(xiàn)
1. 在settings.py 中 ?增加 'django.contrib.redirects' 到你的 INSTALLED_APPS 設置.
2. 增加 'django.contrib.redirects.middleware.RedirectFallbackMiddleware' 到你的MIDDLEWARE_CLASSES 設置中.
3. 運行 manage.py syncdb. 創(chuàng)建 django_redirect 這個表,包含了 site_id, old_path and new_path 字段.
主要工作是 RedirectFallbackMiddleware ?完成的耗跛,如果 django ?發(fā)現(xiàn)了404 錯誤裕照,這時候,就會進django_redirect 去查找调塌,有沒有匹配的URL 晋南。如果有匹配且新的RUL不為空則自動轉向新的URL,如果新的URL為空羔砾,則返回410. 如果沒有匹配负间,仍然按原來的錯誤返回。
注意姜凄,這種僅僅處理 404 相關錯誤政溃,而不是 500 錯誤的。
增加刪除 django_redirect 表呢态秧?
[python]view plaincopy
from?django.dbimport?models
from?django.contrib.sites.modelsimport?Site
from?django.utils.translationimport?ugettext_lazy?as?_
from?django.utils.encodingimport?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 就可以實現(xiàn)save,delete了董虱。
以上三種方法都可以實現(xiàn) django redirect,其實最常用的,是第一種與第二種愤诱,第三種方法很少用云头。
參考鏈接:http://www.cnblogs.com/wumingxiaoyao/p/7110131.html