Python教程

python为tornado添加recaptcha验证码功能

本文主要是介绍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

复制代码 代码如下:
  
zyiz.net<!DOCTYPE html>
zyiz.net<html>
zyiz.net<head>
zyiz.netzyiz.net<title>reCaptcha验证码</title>
zyiz.net</head>
zyiz.net<body>
zyiz.netzyiz.net<form action="" method="post">
zyiz.netzyiz.net<script type="text/javascript" src="http://www.google.com/recaptcha/api/challenge?k={{ publickey }}"></script>
zyiz.netzyiz.net<noscript>
zyiz.netzyiz.netzyiz.net<iframe src="http://www.google.com/recaptcha/api/noscript?k={{ publickey }}" height="300" width="500" frameborder="0"></iframe><br>
zyiz.netzyiz.netzyiz.net<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
zyiz.netzyiz.netzyiz.net<input type="hidden" name="recaptcha_response_field" value="manual_challenge">
zyiz.netzyiz.net</noscript>
zyiz.netzyiz.net</form>
zyiz.net</body>
zyiz.net</html>
这篇关于python为tornado添加recaptcha验证码功能的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!