在中间件中导入HttpResponseRedirect

时间:2014-06-02 08:05:01

标签: python django middleware

我在django中使用路径前缀“/ m /”制作了移动服务 对于来自移动设备的重定向流量,我使用了来自此处的中间件:http://blog.khmelyuk.com/2011/11/mobile-website-with-django.html。 我已完成此代码:

import re
from django.http import HttpResponseRedirect

我有一个惊喜:

NameError at /m/
global name 'HttpResponseRedirect' is not defined

WTF?

这是我的中间件

class MobileWebsiteMiddleware(object):
    import re
    from django.http import HttpResponseRedirect
    MOBILE_PREFIX = '/m/'
    MOBI_REG = re.compile('(iphone|windowsce|mobile|phone|symbian|mini|pda|ipod|mobi|blackberry|playbook|vodafone|kindle)',
    re.IGNORECASE)

    def process_request(self, request):

        if 'HTTP_USER_AGENT' in request.META:
            userAgent = request.META.get('HTTP_USER_AGENT')
            matches = self.MOBI_REG.search(userAgent)
            path = request.path_info

            if matches:
            # from mobile browser, check if need to redirect to mobile
                if not path.startswith(self.MOBILE_PREFIX):
                # need to redirect to mobile version
                    return HttpResponseRedirect('/m' + path)
            elif path.startswith(self.MOBILE_PREFIX):
                # need to redirect to normal version
                return HttpResponseRedirect(path[2:])
        return None

这就是结果:

NameError at /m/
global name 'HttpResponseRedirect' is not defined
...
Exception Location: /home/michal/.../detect_mobile.py in process_request, line 23
...
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'detect_mobile.MobileWebsiteMiddleware')


Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
89. response = middleware_method(request)
File "/home/michal/django/christianitas_new/detect_mobile.py" in process_request
23. return HttpResponseRedirect(path[2:])

1 个答案:

答案 0 :(得分:2)

这是范围问题。出于某种原因,您在类级别导入该名称,但Python没有为类定义范围,因此您的方法无法看到它。但是没有理由将导入放在那里:将它放在文件的顶部,包含所有其他导入。