编写验证码装饰器时出现属性错误 [英] Attribute Error when writing a captcha decorator

查看:64
本文介绍了编写验证码装饰器时出现属性错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I wrote a captcha decorator...

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

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

and then used it on a view...

@validate_captcha
def sendemail(request):
    ...

但随后出现属性错误...

but then I get an attribute error...

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将此作为响应来处理,因为响应已经在我的装饰器中进行了处理,并且我验证了响应是否可以传递给返回点'result ["success"]'

I THINK...this is happening because it returned a function, but I cannot figure out why django is treating this as a response, because the response was already handled in my decorator and I verified that it made it through to the return point 'result["success"]'

推荐答案

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

I think you should call the failure() function so that you actually have an HttpResponse returned from the wrapping decorator. Replace:

return failure

具有:

return failure()

view 的名称也是如此,将其命名为:

And, the same goes for the view, call it:

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

这篇关于编写验证码装饰器时出现属性错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆