Django在我的代码中重定向而不更改显示URL并发送正确的状态代码

时间:2014-02-22 11:48:59

标签: django subdomain django-middleware

我想像我的管理员一样使用子域重定向网址而不更改网址

 admin.example.com

因此,在我的中间件中,将此更改为

example.com/admin

但仍然显示网址,就好像没有重定向一样。

这是我的中间件目前的样子

from django.http import HttpResponseRedirect
from django.conf import settings
sitename = getattr(settings,'SITE_DEFAULT_DOMAIN')[:4]


class SubdomainMiddleware(object):       
    def process_request(self, request):
        host = request.get_host()
        domain_parts = host.split('.')
        entry_url = "{0}://{1}{2}".format(request.META['wsgi.url_scheme'],\
                                          host,\
                                          request.get_full_path() )
        setattr(request,'entry_url',entry_url)
        if (len(domain_parts) > 2):
            subdomain = domain_parts[0]
            if subdomain.lower() not in ('www',sitename):
                request.incoming_path = request.META['PATH_INFO']
                domain = '.'.join(domain_parts[1:])
                if request.META['PATH_INFO'] == '/' :
                    path = "{0}{1}{2}".format('/',subdomain,'/')            
                else:
                    path = "{0}{1}{2}".format('/',subdomain,request.META['PATH_INFO'])
            else:
                domain = host.replace('www','')
                path = request.META['PATH_INFO']
            redirect_path = "{0}://{1}{2}".format(request.META['wsgi.url_scheme'],domain, path)
            return HttpResponseRedirect(redirect_path)

    def process_response(self, request, response):
        entry_url = getattr(request,'entry_url',None)
        if entry_url:
            response.location = entry_url
        return response

0 个答案:

没有答案