作为练习python和tornado的一个小项目,要求输入网址,输出该网址的二维码
1. 环境准备,见python3+Tornado4.3
2. 安装纯python的二维码生成器模块qrcode,见官网最新qrcode 5.2.2
3. 编码实现:
第一步,简单的hello.html页面,允许输入网址并提交。
1 2 3 4 5 6 7 8 9 |
<html> <head><title>{{title}}</title></head> <body> <form name="input" action="html_form_action" method="get"> URL: <input type="text" name="URL" /> <input type="submit" value="Submit" /> </form> </body> </html> |
第二步,简单的img.html页面,呈现生成的二维码
1 2 3 4 5 6 |
<html> <head><title>{{title}}</title></head> <body> <img src = {{imgName}} /> </body> </html> |
第三步,功能实现部分,得到输入的网址,生成二维码,并输出到页面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import tornado.ioloop import tornado.web import qrcode class MainHandler(tornado.web.RequestHandler): def get(self): self.render("hello.html", title = "hellMickey") class FormHandler(tornado.web.RequestHandler): def get(self): url = self.get_argument("URL") imgQR = qrcode.QRCode(version = 1, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size = 10, border = 4,) imgQR.add_data(url) imgQR.make(fit=True) img = imgQR.make_image() img.save(url + '.png') self.render("img.html", title = "QRCode", imgName = url + '.png') class ImgHandler(tornado.web.RequestHandler): def get(self, path): fileName = path + ".png" try: with open(fileName, 'rb') as f: data = f.read() self.write(data) self.finish() except IOError: self.write("Error") def make_app(): return tornado.web.Application([ (r"/", MainHandler), (r"/html_form_action", FormHandler),(r"/(.*).png", ImgHandler), ]) if __name__ == "__main__": app = make_app() app.listen(8888) tornado.ioloop.IOLoop.current().start() |