在django中间件中使用HTTP HttpResponsePermanentRedirect时,站点进入重定向循环

时间:2014-02-05 13:10:59

标签: django heroku geoip django-middleware

当我尝试在Heroku上部署时,我在我的网站上使用此代码进行重定向循环。这是中间件的代码

# -*- coding: utf-8 -*-

from django.utils.functional import SimpleLazyObject
from django.conf import settings
from django.http import HttpResponsePermanentRedirect

def get_country_request(ip):
   import pygeoip
   file_path = settings.PROJECT_ROOT + '/data/GeoIP.dat.dat'
   gi = pygeoip.GeoIP(file_path)
   country = gi.country_name_by_addr(ip)   
   if country:
      return country

class LocationMiddleWare(object):


    def process_request(self, request):
        if 'HTTP_X_FORWARDED_FOR' in request.META:
            request.META['REMOTE_ADDR'] = request.META['HTTP_X_FORWARDED_FOR']
        ip = request.META['REMOTE_ADDR']
        print request.path
        country = get_country_request(ip)             
        if country == "India":
          return HttpResponsePermanentRedirect('/en/')       
        if country == "Netherlands":
          return HttpResponsePermanentRedirect('/nl/')
        return None

请建议我哪里做错了,并建议是否有更好的方法。

提前致谢!

1 个答案:

答案 0 :(得分:1)

你总是从印度和荷兰重新定向人,这是一个循环,因为没有打破它。仅当request.path不是/en//nl/时,您才应该进行重定向。

def process_request(self, request):
    # NOTICE: This will make sure redirect loop is broken.
    if request.path in ["/en/", "/nl/"]:
        return None
    if 'HTTP_X_FORWARDED_FOR' in request.META:
        request.META['REMOTE_ADDR'] = request.META['HTTP_X_FORWARDED_FOR']
    ip = request.META['REMOTE_ADDR']
    print request.path
    country = get_country_request(ip)             
    if country == "India":
        return HttpResponsePermanentRedirect('/en/')       
    if country == "Netherlands":
        return HttpResponsePermanentRedirect('/nl/')
    return None