Pergunta

Eu quero fazer uma validação captcha.

I pegar a chave do recaptcha website e já ter sucesso para colocar a chave pública para carregar a página com o desafio .

<script type="text/javascript"
   src="http://api.recaptcha.net/challenge?k=<your_public_key>">
</script>

<noscript>
   <iframe src="http://api.recaptcha.net/noscript?k=<your_public_key>"
       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>

o reCaptcha Python plug-in mas não consigo encontrar qualquer documentação sobre como use-o.

Alguém tem alguma idéia sobre como usar este plugin Python? recaptcha-client-1.0.4.tar.gz (md5)

Foi útil?

Solução

É bastante simples. Este é um exemplo de um trac trivial plug-in que estou usando:

from recaptcha.client import captcha

if req.method == 'POST':
    response = captcha.submit(
        req.args['recaptcha_challenge_field'],
        req.args['recaptcha_response_field'],
        self.private_key,
        req.remote_addr,
        )
    if not response.is_valid:
        say_captcha_is_invalid()
    else:
        do_something_useful()
else:
    data['recaptcha_javascript'] = captcha.displayhtml(self.public_key)
    data['recaptcha_theme'] = self.theme
    return 'recaptchaticket.html', data, n

Outras dicas

Desculpe dizer, mas este módulo, enquanto ele funciona muito bem, é quase inteiramente em situação irregular, e de layout é um pouco confuso para aqueles de nós que preferem usar ">> ajuda (modulename)" após a instalação. Vou dar um exemplo usando cherrypy, e fazer alguns comentários relacionados com o cgi depois.

captcha.py contém duas funções e uma classe:

  • display_html: que retorna a "caixa reCaptcha" familiar

  • apresentar: que submete os valores digitados pelo usuário em segundo plano

  • RecapchaResponse: que é uma classe de recipiente que contém a resposta de reCaptcha

Você primeiro precisa importar o caminho completo para capcha.py, em seguida, criar um par de funções que pega exibindo e lidar com a resposta.

from recaptcha.client import captcha
class Main(object):

    @cherrypy.expose
    def display_recaptcha(self, *args, **kwargs):
        public = "public_key_string_you_got_from_recaptcha"
        captcha_html = captcha.displayhtml(
                           public,
                           use_ssl=False,
                           error="Something broke!")

        # You'll probably want to add error message handling here if you 
        # have been redirected from a failed attempt
        return """
        <form action="validate">
        %s
        <input type=submit value="Submit Captcha Text" \>
        </form>
        """%captcha_html

    # send the recaptcha fields for validation
    @cherrypy.expose
    def validate(self, *args, **kwargs):
        # these should be here, in the real world, you'd display a nice error
        # then redirect the user to something useful

        if not "recaptcha_challenge_field" in kwargs:
            return "no recaptcha_challenge_field"

        if not "recaptcha_response_field" in kwargs:
            return "no recaptcha_response_field"

        recaptcha_challenge_field  = kwargs["recaptcha_challenge_field"]
        recaptcha_response_field  = kwargs["recaptcha_response_field"]

        # response is just the RecaptchaResponse container class. You'll need 
        # to check is_valid and error_code
        response = captcha.submit(
            recaptcha_challenge_field,
            recaptcha_response_field,
            "private_key_string_you_got_from_recaptcha",
            cherrypy.request.headers["Remote-Addr"],)

        if response.is_valid:
            #redirect to where ever we want to go on success
            raise cherrypy.HTTPRedirect("success_page")

        if response.error_code:
            # this tacks on the error to the redirect, so you can let the
            # user knowwhy their submission failed (not handled above,
            # but you are smart :-) )
            raise cherrypy.HTTPRedirect(
                "display_recaptcha?error=%s"%response.error_code)

Vai ser praticamente o mesmo se estiver usando o cgi, basta usar a variável de ambiente REMOTE_ADDR onde eu costumava Request.Headers e campo de utilização de armazenamento de cherrypy fazer seus cheques.

Não há mágica, o módulo apenas segue os docs: https://developers.google.com/recaptcha/docs/display

Os erros de validação que você pode precisar para lidar com: https://developers.google.com/recaptcha/docs/verify

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top