python-图片流传输的思路及示例(url转换二维码)


Posted in Python onDecember 21, 2020

1.场景

  • 将URL动态生成二维码前端展示(微信支付等,)--》

1.静态文件路径访问
返回URL_name,(a标签,src 静态路由访问)

2.流传输,前端渲染
二进制流返回前端,前端根据二进制流编码类型显示

3.前端js生成
后台获取到微信支付的code_url,前端js将code_url生成二维码,并渲染

  • 实际代码

使用python_web 框架--》tornado
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, Url3Handler


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),
      (r"/url3", Url3Handler),
    ],
    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()

apps.py

import tornado.web
from manager_handler import gen_qrcode, gen_qrcode_obj,gen_qrcode_buf


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)


class Url3Handler(BaseHandelr):
  def get(self):
    self.render('qrcode.html', title='url', data='URL-提交', img_stream='')

  def post(self):
    url = self.get_argument('url')
    img_stream = gen_qrcode_buf(url)
    self.set_header('Content-Type', 'image/png')
    self.write(img_stream)

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

def gen_qrcode_buf(words):
  qr = qrcode.make(words)
  buf = io.BytesIO()
  qr.save(buf, 'png')
  qr_buf = buf.getvalue()
  # img_stream = base64.b64encode(qr_buf)
  return qr_buf

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>

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="width:180px" src="data:;base64,{{ img_stream }}" alt="">
      {% end %}
    </p>
    <br>
    <input id="submit" type="submit" value="生成二维码">
  </form>
{% end %}

以上就是python-图片流传输的思路及示例(url转换二维码)的详细内容,更多关于python 图片流传输的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
Python实现动态添加类的属性或成员函数的解决方法
Jul 16 Python
Python在Console下显示文本进度条的方法
Feb 14 Python
Python简单实现查找一个字符串中最长不重复子串的方法
Mar 26 Python
PyCharm代码提示忽略大小写设置方法
Oct 28 Python
对pandas的算术运算和数据对齐实例详解
Dec 22 Python
Python多图片合并PDF的方法
Jan 03 Python
解决pycharm的Python console不能调试当前程序的问题
Jan 20 Python
python内存监控工具memory_profiler和guppy的用法详解
Jul 29 Python
Python argparse模块应用实例解析
Nov 15 Python
python代码实现图书管理系统
Nov 30 Python
Python爬虫入门教程01之爬取豆瓣Top电影
Jan 24 Python
Pytorch中的学习率衰减及其用法详解
Jun 05 Python
python 用pandas实现数据透视表功能
Dec 21 #Python
python 生成正态分布数据,并绘图和解析
Dec 21 #Python
python statsmodel的使用
Dec 21 #Python
Python 实现集合Set的示例
Dec 21 #Python
Python 实现二叉查找树的示例代码
Dec 21 #Python
如何利用Python matplotlib绘制雷达图
Dec 21 #Python
OpenCV+python实现膨胀和腐蚀的示例
Dec 21 #Python
You might like
PHP网页游戏学习之Xnova(ogame)源码解读(十)
2014/06/24 PHP
ThinkPHP框架中使用Memcached缓存数据的方法
2018/03/31 PHP
php curl获取到json对象并转成数组array的方法
2018/05/31 PHP
javascript document.images实例
2008/05/27 Javascript
javascript闭包的理解和实例
2010/08/12 Javascript
javascript的函数作用域
2014/11/12 Javascript
javascript实现校验文件上传控件实例
2015/04/20 Javascript
遮罩层点击按钮弹出并且具有拖动和关闭效果(两种方法)
2015/08/20 Javascript
用NodeJS实现批量查询地理位置的经纬度接口
2016/08/16 NodeJs
Javascript获取background属性中url的值
2016/10/17 Javascript
JS使用正则实现去掉字符串左右空格的方法
2016/12/27 Javascript
基于Node.js的WebSocket通信实现
2017/03/11 Javascript
JS组件系列之MVVM组件构建自己的Vue组件
2017/04/28 Javascript
jQuery超简单遮罩层实现方法示例
2018/09/06 jQuery
layui select 禁止点击的实现方法
2019/09/05 Javascript
Layui数据表格 前后端json数据接收的方法
2019/09/19 Javascript
在python中的socket模块使用代理实例
2014/05/29 Python
python获取当前用户的主目录路径方法(推荐)
2017/01/12 Python
linux下python使用sendmail发送邮件
2018/05/22 Python
Python类的继承、多态及获取对象信息操作详解
2019/02/28 Python
Python 解码Base64 得到码流格式文本实例
2020/01/09 Python
python 的topk算法实例
2020/04/02 Python
Python单元测试及unittest框架用法实例解析
2020/07/09 Python
python 邮件检测工具mmpi的使用
2021/01/04 Python
python画图时设置分辨率和画布大小的实现(plt.figure())
2021/01/08 Python
苹果Mac升级:MacSales.com
2017/11/20 全球购物
残疾人创业典型事迹
2014/02/01 职场文书
《童年的发现》教学反思
2014/02/14 职场文书
我的梦想演讲稿500字
2014/08/21 职场文书
企业趣味活动方案
2014/08/21 职场文书
同志主要表现材料
2014/08/21 职场文书
幼儿园开学温馨提示
2015/07/15 职场文书
2016年小学端午节活动总结
2016/04/01 职场文书
如何写好活动总结
2019/06/21 职场文书
python blinker 信号库
2022/05/04 Python
python+pyhyper实现识别图片中的车牌号思路详解
2022/12/24 Python