如何启用reCAPTCHA

时间:2011-04-14 11:30:59

标签: python google-app-engine recaptcha

我尝试使用标记

启用reCAPTCHA
{{capture}}

预期输出是reCAPTCHA框。相反,我看到这个代码直接显示在页面上的代码看起来像一个bug:

<script type="text/javascript" src="http://api.recaptcha.net/ challenge?k=6LckUsMSAAAAAGcZR3JZw6Dusn4wKBBfZxHXh8w5"></script> <noscript> <iframe src="http://api.recaptcha.net/noscript?k=6LckUsMSAAAAAGcZR3JZw6Dusn4wKBBfZxHXh8w5" height="300" width="500" frameborder="0"></iframe><br /> <textarea name="recaptcha_challenge_field" rows="3" cols="40"></ textarea> <input type='hidden' name='recaptcha_response_field' value='manual_challenge' /> </noscript>

知道我该怎么办吗?该错误的链接是here,我使用的代码是直接使用reCAPTCHA api和一个名为captcha.py的文件:

import urllib2, urllib

API_SSL_SERVER="https://api-secure.recaptcha.net"
API_SERVER="http://api.recaptcha.net"
VERIFY_SERVER="api-verify.recaptcha.net"

class RecaptchaResponse(object):
    def __init__(self, is_valid, error_code=None):
        self.is_valid = is_valid
        self.error_code = error_code

def displayhtml (public_key,
                 use_ssl = False,
                 error = None):
    """Gets the HTML to display for reCAPTCHA

    public_key -- The public api key
    use_ssl -- Should the request be sent over ssl?
    error -- An error message to display (from
RecaptchaResponse.error_code)"""

    error_param = ''
    if error:
        error_param = '&error=%s' % error

    if use_ssl:
        server = API_SSL_SERVER
    else:
        server = API_SERVER

    return """<script type="text/javascript" src="%(ApiServer)s/
challenge?k=%(PublicKey)s%(ErrorParam)s"></script>

<noscript>
  <iframe src="%(ApiServer)s/noscript?k=%(PublicKey)s%(ErrorParam)s"
height="300" width="500" frameborder="0"></iframe><br />
  <textarea name="recaptcha_challenge_field" rows="3" cols="40"></
textarea>
  <input type='hidden' name='recaptcha_response_field'
value='manual_challenge' />
</noscript>
""" % {
        'ApiServer' : server,
        'PublicKey' : public_key,
        'ErrorParam' : error_param,
        }


def submit (recaptcha_challenge_field,
            recaptcha_response_field,
            private_key,
            remoteip):
    """
    Submits a reCAPTCHA request for verification. Returns
RecaptchaResponse
    for the request

    recaptcha_challenge_field -- The value of
recaptcha_challenge_field from the form
    recaptcha_response_field -- The value of recaptcha_response_field
from the form
    private_key -- your reCAPTCHA private key
    remoteip -- the user's ip address
    """

    if not (recaptcha_response_field and recaptcha_challenge_field and
            len (recaptcha_response_field) and len
(recaptcha_challenge_field)):
        return RecaptchaResponse (is_valid = False, error_code =
'incorrect-captcha-sol')


    def encode_if_necessary(s):
        if isinstance(s, unicode):
            return s.encode('utf-8')
        return s

    params = urllib.urlencode ({
            'privatekey': encode_if_necessary(private_key),
            'remoteip' :  encode_if_necessary(remoteip),
            'challenge':
encode_if_necessary(recaptcha_challenge_field),
            'response' :
encode_if_necessary(recaptcha_response_field),
            })

    request = urllib2.Request (
        url = "http://%s/verify" % VERIFY_SERVER,
        data = params,
        headers = {
            "Content-type": "application/x-www-form-urlencoded",
            "User-agent": "reCAPTCHA Python"
            }
        )

    httpresp = urllib2.urlopen (request)

    return_values = httpresp.read ().splitlines ();
    httpresp.close();

    return_code = return_values [0]

    if (return_code == "true"):
        return RecaptchaResponse (is_valid=True)
    else:
        return RecaptchaResponse (is_valid=False, error_code =
return_values [1]) 

到目前为止,我在HTTP GET和POST处理程序中使用它:

template_values.update(dict(capture=captcha.displayhtml(public_key = CAPTCHA_PUB_KEY, use_ssl = False, error = None)))

是GET处理程序,POST有

def post(self, view): 
    challenge = self.request.get('recaptcha_challenge_field')
    response  = self.request.get('recaptcha_response_field')
    remoteip  = os.environ['REMOTE_ADDR']
    cResponse = captcha.submit(
             challenge,
             response,
             CAPTCHA_PRV_KEY,
             remoteip)

if cResponse.is_valid==True:
    isHuman=True
else:
    isHuman=False 

。我该怎么办?

更新:为了继续,我还添加了逻辑,只允许变量isHuman = True,我想重定向到表单页面而不是打印错误消息:

def post(self, view): 
    challenge = self.request.get('recaptcha_challenge_field')
    response  = self.request.get('recaptcha_response_field')
    remoteip  = os.environ['REMOTE_ADDR']
    cResponse = captcha.submit(
                 challenge,
                 response,
                 CAPTCHA_PRV_KEY,
                 remoteip)

    if cResponse.is_valid==True:
        isHuman=True
    else:
        isHuman=False 
        self.response.out.write('captcha failed') #TO DO: redirect to form page
        return

2 个答案:

答案 0 :(得分:5)

你是Django自我控制的受害者。

尝试{{capture|safe}}

答案 1 :(得分:4)

Django模板系统默认自动执行HTML转义以防止跨站点脚本攻击等问题 - 这就是将所有html <tag>转换为&lt;tag &gt;

为防止这种情况发生,您可以调用safe过滤器,例如:

{{capture|safe}}