python为tornado添加recaptcha验证码功能

from urllib.request import urlopen
from urllib.parse import urlencode
import tornado.httpserver
import tornado.ioloop
import tornado.web

#获取key: https://www.google.com/recaptcha/whyrecaptcha
publickey = ‘填入你的 public key’
privatekey = ‘填入你的 private key’

class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r’/’, IndexHandler)
]
settings = dict(
template_path=”templates”,
)

tornado.web.Application.__init__(self, handlers, **settings)

class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.render(‘index.html’, publickey=publickey)

def post(self):
url = ‘http://www.google.com/recaptcha/api/verify’

#验证码
challenge = self.get_argument(‘recaptcha_challenge_field’)
#用户输入
response = self.get_argument(‘recaptcha_response_field’)

data = {
‘privatekey’: privatekey,
‘remoteip’: self.request.remote_ip,
‘challenge’: challenge,
‘response’: response
}

res = urlopen(url, data=urlencode(data).encode())
#获取验证结果,这里直接将返回结果输出到页面
self.write(res.read().decode())

if __name__ == ‘__main__’:
server = tornado.httpserver.HTTPServer(Application())
server.listen(10001)
tornado.ioloop.IOLoop.instance().start()

templates/index.html

ddpool.cn<!DOCTYPE html>
ddpool.cn<html>
ddpool.cn<head>
ddpool.cnddpool.cn<title>reCaptcha验证码</title>
ddpool.cn</head>
ddpool.cn<body>
ddpool.cnddpool.cn<form action=”” method=”post”>
ddpool.cnddpool.cn<script type=”text/javascript” src=”http://www.google.com/recaptcha/api/challenge?k={{%20publickey%20}}”></script>
ddpool.cnddpool.cn<noscript>
ddpool.cnddpool.cnddpool.cn<iframe src=”http://www.google.com/recaptcha/api/noscript?k={{%20publickey%20}}” height=”300″ width=”500″ frameborder=”0″></iframe><br>
ddpool.cnddpool.cnddpool.cn<textarea name=”recaptcha_challenge_field” rows=”3″ cols=”40″></textarea>
ddpool.cnddpool.cnddpool.cn<input type=”hidden” name=”recaptcha_response_field” value=”manual_challenge”>
ddpool.cnddpool.cn</noscript>
ddpool.cnddpool.cn</form>
ddpool.cn</body>
ddpool.cn</html>

python为tornado添加recaptcha验证码功能

郑重声明:本网站发布的内容(图片、视频和文字)以及用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服

发表评论

登录后才能评论