很抱歉,这个模块虽然工作得很好,但几乎完全没有文档,而且它的布局对于我们这些喜欢在安装后使用“>> help(modulename)”的人来说有点混乱。我将给出一个使用cherrypy的例子,然后做一些cgi相关的评论。
captcha.py 包含两个函数和一个类:
您首先需要导入 capcha.py 的完整路径,然后创建几个处理显示和处理响应的函数。
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)
如果使用 cgi,这将几乎相同,只需使用我使用cherrypy 的 request.headers 的 REMOTE_ADDR 环境变量并使用字段存储进行检查。
没有魔法,模块只是遵循文档:
https ://developers.google.com/recaptcha/docs/display
您可能需要处理的验证错误:
https ://developers.google.com/recaptcha/docs/verify