Skip to main content
 首页 » 编程设计

python之Django 中间件 : Can't get urlredirect to work

2025年05月04日23Renyi-Fan

所以我是 Django 的新手,但是已经完成了 (https://docs.djangoproject.com/en/1.4/intro/tutorial01/) 上的教程好几次了,我觉得我已经很不错了处理它。

我要解决的下一个项目是创建、安装和配置中间件(更具体地说,我正在尝试做到这一点,以便当本地主机访问该站点时,它可以很好地拉起,而当本地主机以外的其他人拉起时它转发到 google.com 或其他一些随机站点。)我这样做主要是为了应我老板的要求积累经验,所以任何帮助将不胜感激! :)

我已经阅读了以下网站,但似乎无法弄清楚如何才能使 url 重定向正常工作。

$https://docs.djangoproject.com/en/dev/topics/http/middleware/?from=olddocs

$https://docs.djangoproject.com/en/dev/ref/middleware/

$http://djangosnippets.org/snippets/510/

我从上述站点 (www.djangosnippets.org) 中获取的代码

import re 
 
from django.http import HttpResponsePermanentRedirect 
from django.conf import settings 
 
 
class UrlRedirectMiddleware: 
""" 
This middleware lets you match a specific url and redirect the request to a 
new url. 
 
You keep a tuple of url regex pattern/url redirect tuples on your site 
settings, example: 
 
URL_REDIRECTS = ( 
    (r'www\.example\.com/hello/$', 'http://hello.example.com/'), 
    (r'www\.example2\.com/$', 'http://www.example.com/example2/'), 
) 
 
""" 
def process_request(self, request): 
    host = request.META['HTTP_HOST'] + request.META['PATH_INFO'] 
    for url_pattern, redirect_url in settings.URL_REDIRECTS: 
        regex = re.compile(url_pattern) 
        if regex.match(host): 
            return HttpResponsePermanentRedirect(redirect_url) 

请您参考如下方法:

添加到您的设置(假设您正在使用开发服务器):

例如

URL_REDIRECTS = ( 
    (r'127.0.0.1:8000/hello', 'http://www.google.com'), 
) 

同时将 UrlRedirectMiddleware python 路径添加到您的设置中的 MIDDLEWARE_CLASSES。

例如,如果您的 UrlRedirectMiddleware 是在名为 app 的应用程序中名为 my_middle.py 的模块中定义的

将 'app.my_middle.UrlRedirectMiddleware' 添加到您的 MIDDLEWARE_CLASSES