我需要装饰师的请求,但我无法弄清楚如何在那里得到它

时间:2016-01-29 04:24:25

标签: python django

我的deorator功能......

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

    def failure():
        return HttpResponse('You need to complete the captcha, please refresh and try again')

    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 fail
    return fail

然后我的观点......

@validate_captcha
def sendemail(request):
    ...

我可以将请求放在装饰器args中,但是当我把它放在视图args中时它是未定义的。我试着用其他几种方式称之为没有成功,你怎么把它放在那里?

1 个答案:

答案 0 :(得分:3)

您需要包装函数

def validate_captcha(view):
    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 fail
        return fail
    return wrap

确保在Python中研究这个令人敬畏且非常详细的装饰器概述(我个人认为,它是有史以来最好的SO答案之一):