编写验证码装饰器时的属性错误

时间:2016-01-29 05:05:44

标签: python django

我写了一个验证码装饰......

def validate_captcha(view):
    '''Decorator to validate a captcha based on settings'''

    def failure():
        return HttpResponse('There was an error, please refresh and try again')

    def wrap(request, *args, **kwargs):
        if request.method == 'POST':

            url = "https://www.google.com/recaptcha/api/siteverify"
            values = {
                'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
                'response': request.POST.get(u'g-recaptcha-response', None),
                'remoteip': request.META.get("REMOTE_ADDR", None),
            }

            data = urllib.urlencode(values)
            req = urllib2.Request(url, data)
            response = urllib2.urlopen(req)
            result = json.loads(response.read())

            # result["success"] will be True on a success
            if result["success"]:
                return view
            else:
                return failure
        return failure
    return wrap

然后在视图中使用它...

@validate_captcha
def sendemail(request):
    ...

然后我得到属性错误......

Traceback:
File "/home/jeff/Django/langalang/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  223.                 response = middleware_method(request, response)
File "/home/jeff/Django/langalang/venv/local/lib/python2.7/site-packages/django/middleware/common.py" in process_response
  138.         if response.status_code == 404 and not settings.DEBUG:

Exception Type: AttributeError at /ko/contact/sendemail
Exception Value: 'function' object has no attribute 'status_code'

我认为......这种情况正在发生,因为它返回了一个函数,但我无法弄清楚为什么django将此视为一个响应,因为响应已经在我的装饰器中处理并且我验证它已经通过了返回点'结果["成功"]'

1 个答案:

答案 0 :(得分:2)

我认为您应该调用failure()函数,以便实际从包装装饰器返回HttpResponse。替换:

return failure

使用:

return failure()

同样适用于view,称之为:

return view(request, *args, **kwargs)