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
Hola Abad, Soy nuevo en Python, ¿puede explicar cómo utiliza el paquete descargado en más detalles? –
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