• python-图片流传输(url转换二维码)


    1.场景

    • 将URL动态生成二维码前端展示(微信支付等,)--》
    1. 静态文件路径访问
      返回URL_name,(a标签,src 静态路由访问)
    2. 流传输,前端渲染
      二进制流返回前端,前端根据二进制流编码类型显示
    3. 前端js生成
      后台获取到微信支付的code_url,前端js将code_url生成二维码,并渲染
    • 实际代码
      使用python_web 框架--》tornado
    1. manager.py
    import os
    import asyncio
    
    import tornado.ioloop
    import tornado.httpserver
    import tornado.web
    import tornado.options
    
    from tornado.options import define, options, parse_command_line
    from apps import UrlHandler, Url2Handler
    
    
    define("port", default=8000, type=int)
    
    
    def create_app():
        settings = {
            "template_path": os.path.join(os.path.dirname(__file__), "templates"),
            "static_path": os.path.join(os.path.dirname(__file__), "static"),
        }
        application = tornado.web.Application(
            handlers=[
                (r"/url", UrlHandler),
                (r"/url2", Url2Handler),
            ],
            debug=True,
            **settings,
        )
        return application
    
    
    if __name__ == '__main__':
        parse_command_line()
        app = create_app()
        server = tornado.httpserver.HTTPServer(app)
        server.listen(options.port)
        asyncio.get_event_loop().run_forever()
    1. apps.py
    import tornado.web
    from manager_handler import gen_qrcode, gen_qrcode_obj
    
    
    class BaseHandler(tornado.web.RequestHandler):
        pass
    
    
    class UrlHandler(BaseHandler):
        def get(self):
            # 获取链接
            self.render('qrcode.html', title='url', data='URL-提交', img_stream='')
    
        async def post(self):
            # 生成二维码
            url = self.get_argument('url_str')
    
            # URL转换二维码
            img_stream = gen_qrcode(url)
            await self.render('qrcode.html', title='qrcode', data='扫码支付', img_stream=img_stream)
    
    
    class Url2Handler(BaseHandler):
        def get(self):
            # 获取链接
            self.render('qrcode.html', title='url', data='URL-提交', img_stream='')
    
        async def post(self):
            # 生成二维码
            url = self.get_argument('url_str')
    
            # URL转换二维码
            img_stream = gen_qrcode_obj(url=url)
            # await self.render('qrcode.html', title='qrcode', data='扫码支付', img_stream=img_stream)
            self.set_header('Content_type', 'image/jpg')
            self.set_header('Content_length', len(img_stream))
            self.write(img_stream)
    1. manager_handler.py
    import qrcode
    import io
    import base64
    import time
    
    
    def gen_qrcode(url):
        """
        方式1: URL转换二维码
        :param url: 转换二维码的URL
        :return:  base64编码后的 二进制流 二维码数据
        """
        qr = qrcode.make(url)
        buf = io.BytesIO()
        qr.save(buf)
        img_buf = buf.getvalue()
        img_stream = base64.b64encode(img_buf)
        return img_stream
    
    
    def gen_qrcode_obj(version=1, box_size=10, border=4, url=None):
        """
        方式2: URL转换二维码(图片流传输, template需要指明 data:base64编码)
        :param version:
        :param box_size:
        :param border:
        :return:
        """
        qr = qrcode.QRCode(
            version=version,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=box_size,
            border=border,
        )
    
        url = "https://www.12dms.com" if url is None else url
        save_name = "./" + "qrcode" + str(time.time()) + ".png"
    
        qr.add_data(url)
        qr.make()
        img = qr.make_image()
        img.save(save_name.encode())
        with open(save_name, 'rb') as img_f:
            img_stream = img_f.read()
            img_stream = base64.b64encode(img_stream)
            print(img_stream)
        return img_stream
    1. base.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>{% block title %}{% end %}</title>
        {% block head %}{% end %}
    </head>
    
    <body>
        <h1 style="text-align: center">
            {% block h1 %}{{ data }}{% end %}
        </h1>
        {% block content %}{% end %}
    </body>
    </html>
    1. qrcode.html
    {% extends "base.html" %}
    
    {% block title %}
        {{ title }}
    {% end %}
    
    {% block h1 %}
        {{ data }}
    {% end %}
    
    
    {% block content %}
        <form method="post" action="" >
            <p>
                输入待转换的URL:<input name="url_str"/>
                <br>
    {#            {{ img_stream }}#}
                {% if img_stream %}
                    <img style="180px" src="data:;base64,{{ img_stream }}" alt="">
                {% end %}
            </p>
            <br>
            <input id="submit" type="submit"  value="生成二维码">
        </form>
    {% end %}
  • 相关阅读:
    2016.5.30实现透明Panel及控件置顶的方法
    2016.6.14自定义控件添加自定义事件
    2016.5.30让窗口处于最顶层的方法
    2016.5.23 用反射技术为实体类变量赋值、取值
    2016.4.6 WinForm显示PDF两种方法
    2016.3.7 Word2007编号设置
    2016.2.28 DataTable用法汇总
    2016.2.24 利用用户控件和委托完美解决快速选择txbbox
    2016.2.13 (年初六) oracle两张表update方法
    怎样用idhttpserver代替IIS让用户浏览html或下载文件 http://bbs.csdn.net/topics/360248674
  • 原文地址:https://www.cnblogs.com/yblackd/p/14533388.html
Copyright © 2020-2023  润新知