¿Cómo utilizar el complemento Python reCaptcha client para la validación?
-
10-07-2019 - |
Pregunta
Quiero hacer una validación de captcha.
Recibo la clave del sitio web de recaptcha y ya tengo éxito al poner 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 el complemento reCaptcha Python pero no encuentro ninguna documentación sobre cómo úsalo.
¿Alguien tiene alguna idea sobre cómo usar este complemento de Python? recaptcha-client-1.0.4.tar.gz (md5)
Solución
Es bastante sencillo. Este es un ejemplo de un complemento trivial de 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
Otros consejos
Lamento decirlo, pero este módulo, aunque funciona bien, está casi completamente indocumentado, y su diseño es un poco confuso para aquellos de nosotros que preferimos usar " > > ayuda (nombre del 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 el conocido cuadro "ReCaptcha"
-
submit: que envía los valores ingresados ??por el usuario en segundo plano
-
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 se encarguen de mostrar y manejar 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)
Será casi lo mismo si usa cgi, solo use la variable de entorno REMOTE_ADDR donde utilicé request.headers de cherrypy y use el almacenamiento de campo para hacer sus verificaciones.
No hay magia, el módulo solo sigue los documentos: https://developers.google.com/recaptcha/docs/display
Errores de validación que puede necesitar manejar: https://developers.google.com/recaptcha/docs/verify