2009-09-17 14 views
15

Quiero hacer una validación de captcha.Cómo usar el complemento de Python cliente ReCaptcha para la validación?

Obtengo la clave del recaptcha website y ya he logrado colocar la clave pública para cargar la página web con el desafío.

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

descargo the reCaptcha Python plugin pero no puedo encontrar ninguna documentación sobre cómo usarlo.

¿Alguien tiene alguna idea sobre cómo usar este complemento de Python? recaptcha-client-1.0.4.tar.gz (md5)

Respuesta

25

Es bastante sencillo. Este es un ejemplo de un plugin trivial trac que estoy 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 
+0

Hola Abad, Soy nuevo en Python, ¿puede explicar cómo utiliza el paquete descargado en más detalles? –

+2

Debe instalarlo como un paquete regular de Python. Le recomendaría que lea un curso introductorio sobre python si es nuevo en todo esto. Puede probar http://diveintopython.org/toc/index.html o http://docs.python.org/tutorial/index.html como un buen punto de partida. – abbot

4

Siento decirlo, pero este módulo, mientras que funciona muy bien, es casi en su totalidad indocumentado, y es de diseño está un poco confuso para aquellos de nosotros que preferimos usar ">> ayuda (nombre de módulo)" después de la instalación. Daré un ejemplo usando cherrypy, y luego haré algunos comentarios relacionados con cgi.

captcha.py contiene dos funciones y una clase:

  • display_html: que devuelve la "caja reCaptcha" familiar

  • presentar: la que presenta los valores introducidos por el usuario en el fondo

  • RecapchaResponse: que es una clase de contenedor que contiene la respuesta de reCaptcha

Primero deberá importar la ruta completa a capcha.py, luego crear un par de funciones que manejen la visualización y el tratamiento de la respuesta.

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) 

Va a ser más o menos lo mismo si el uso de CGI, sólo tiene que utilizar la variable de entorno REMOTE_ADDR donde solía request.headers y campo de utilización de almacenamiento de cherrypy hacer sus cheques.

No hay magia, el módulo se limita a seguir la documentación: https://developers.google.com/recaptcha/docs/display

Los errores de validación que pueda necesitar para manejar: https://developers.google.com/recaptcha/docs/verify

Cuestiones relacionadas