所以我对 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)