用django實現redirect的幾種方法總結


用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 版本以上) 

 

[python] view plain  copy
 
 print?
  1. from django.views.generic.simple import redirect_to  
  2. urlpatterns = patterns('',  
  3.     (r'^one/$', redirect_to, {'url': '/another/'}),  
  4. )  

 

[python] view plain  copy
 
 print?
  1. from django.views.generic import RedirectView  
  2. urlpatterns = patterns('',  
  3.     (r'^one/$', RedirectView.as_view(url='/another/')),  
  4. )  



 

2. 在view 中 通過 HttpResponseRedirect 實現 redirect 

 

 

[python] view plain  copy
 
 print?
  1. from django.http import HttpResponseRedirect  
  2.   
  3. def myview(request):  
  4.     ...  
  5.     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 表呢?

 

[python] view plain  copy
 
 print?
  1. from django.db import models  
  2. from django.contrib.sites.models import Site  
  3. from django.utils.translation import ugettext_lazy as _  
  4. from django.utils.encoding import python_2_unicode_compatible  
  5.  
  6. @python_2_unicode_compatible  
  7. class Redirect(models.Model):  
  8.     site = models.ForeignKey(Site)  
  9.     old_path = models.CharField(_('redirect from'), max_length=200, db_index=True,  
  10.         help_text=_("This should be an absolute path, excluding the domain name. Example: '/events/search/'."))  
  11.     new_path = models.CharField(_('redirect to'), max_length=200, blank=True,  
  12.         help_text=_("This can be either an absolute path (as above) or a full URL starting with 'http://'."))  
  13.   
  14.     class Meta:  
  15.         verbose_name = _('redirect')  
  16.         verbose_name_plural = _('redirects')  
  17.         db_table = 'django_redirect'  
  18.         unique_together=(('site', 'old_path'),)  
  19.         ordering = ('old_path',)  
  20.   
  21.     def __str__(self):  
  22.         return "%s ---> %s" % (self.old_path, self.new_path)  



 

采用類似如上的MODEL ,另外用DJANGO相關ORM 就可以實現save,delete了。

以上三種方法都可以實現 django redirect,其實最常用的,是第一種與第二種,第三種方法很少用。 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM