python为tornado添加recaptcha验证码功能

WBOY
Release: 2016-06-16 08:45:03
Original
1127 people have browsed it

复制代码 代码如下:

    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

复制代码 代码如下:
  
jb51.net
jb51.net
jb51.net
jb51.netjb51.netreCaptcha验证码
jb51.net
jb51.net
jb51.netjb51.net

jb51.netjb51.net
jb51.netjb51.net
jb51.netjb51.net

jb51.net
jb51.net
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!