【问题标题】:Django Middleware: Can't get urlredirect to workDjango 中间件:无法让 urlredirect 工作
【发布时间】:2012-08-30 22:07:06
【问题描述】:

所以我对 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://djangosn-ps.org/sn-ps/510/

我从上述网站 (www.djangosn-ps.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)

【问题讨论】:

    标签: python django middleware


    【解决方案1】:

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

    例如

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

    还将UrlRedirectMiddleware python-path 添加到您的设置中的MIDDLEWARE_CLASSES

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-12
      • 2013-05-09
      • 1970-01-01
      • 1970-01-01
      • 2021-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多