当前位置: 移动技术网 > IT编程>脚本编程>Python > python为tornado添加recaptcha验证码功能

python为tornado添加recaptcha验证码功能

2019年04月01日  | 移动技术网IT编程  | 我要评论

与敌同行好看吗,魔界天使3,活宝妈咪冷酷爹

复制代码 代码如下:

    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('', 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/

复制代码 代码如下:
  
jb51.net<!doctype html>
jb51.net<html>
jb51.net<head>
jb51.netjb51.net<title>recaptcha验证码</title>
jb51.net</head>
jb51.net<body>
jb51.netjb51.net<form action="" method="post">
jb51.netjb51.net<script type="text/javascript" src="http://www.google.com/recaptcha/api/challenge?k={{ publickey }}"></script>
jb51.netjb51.net<noscript>
jb51.netjb51.netjb51.net<iframe src="http://www.google.com/recaptcha/api/noscript?k={{ publickey }}" height="300" width="500" frameborder="0"></iframe><br>
jb51.netjb51.netjb51.net<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
jb51.netjb51.netjb51.net<input type="hidden" name="recaptcha_response_field" value="manual_challenge">
jb51.netjb51.net</noscript>
jb51.netjb51.net</form>
jb51.net</body>
jb51.net</html>

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网