python & flask 的 web 手机二维码扫描 (htm5-qrCode)

注:此 web必须 是 https 运行环境下,所以,可以先 阅读 “python & flask 下的https实现 ” 一文;

mai.py
'''
登录主页;
'''
@app.route('/')
def index():
    # return render_template("index.html")
    return render_template("user_dataVisual.html")   // 临时测试;

if __name__ == "__main__":
    server = pywsgi.WSGIServer(('192.168.0.101',8080),app,keyfile='./static/cert/server.key',certfile='./static/cert/server.crt')
    server.serve_forever()

user_dataVisual.html (此html在template文件夹下,template与static、main.py在同一目录下,如下:

如下 ===》 :

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>scan</title>
    <!-- <script src="https://unpkg.com/html5-qrcode"></script>   这种方式可以,但必须能上外网!! -->
    <script  src="{{ url_for('static', filename = 'html5-qrcode.min.js') }}"></script>
    <!-- <script src="../static/html5-qrcode.min.js"></script>    !!!这种导入方式没有用!!! -->
    <style type="text/javascript">
        button {
            display: block;
            width: 100%;
            margin: 6px;
            outline: none;
            height: 40px;
            line-height: 40px;
            color: #fff;
            background-color: #26a2ff;
            text-align: center;
            border-radius: 4px;
            border: none;
            cursor: pointer;
        }

        #upload-input {
            opacity: 0;
            filter: alpha(opacity=0);
            display: inline-block;
            width: 100%;
            height: 100%;
        }

        #upload-text {
            position: relative;
            bottom: 40px;
            user-select: none;
        }
    </style>
</head>

<body>
    <!-- 相机、文件方式同时只能使用一个,可根据自己需求修改,如:1.改成下拉框;2.改成tab;3.改成radio等等控制显示隐藏和相应逻辑 -->
    <button onclick="useCamera()">使用相机扫一扫方式</button>
    <button onclick="useLocal()">
        <input type="file" id="upload-input" accept="image/*" value="使用文件方式">
        <span id="upload-text">使用文件方式</span>
    </button>
    <div id="reader"></div>
    <h3 id="qr-reader-results"></h3>
    <script>


        //1.Html5QrcodeScanner是js提供的ui; 2.Html5Qrcode是自定义面板
        let html5QrCode = new Html5Qrcode("reader"); 
        let reader = document.getElementById("reader");
        let res = document.getElementById('qr-reader-results');
        let uploadInput = document.getElementById('upload-input');
        let config = { fps: 10, qrbox: { width: 300, height: 280 } }; //扫一扫相关设置

        var front = 1;

        //使用本地文件
        function useLocal() {
            reader.style.display = "none";
            res.innerText = "";
            uploadInput.addEventListener("change", (e) => {
                if (e.target.files.length == 0) {
                    return;
                }
                const imageFile = e.target.files[0];
                html5QrCode
                    .scanFile(imageFile, true)
                    .then((decodedText) => {
                        res.innerText = "扫码成功结果:\n" + decodedText;
                    })
                    .catch((err) => {
                        res.innerText = "扫码失败:\n" + error;
                    });
            });
        }

       //相机授权
        function useCamera() {
            reader.style.display = "block";
            res.innerText = "";
            Html5Qrcode.getCameras()
                .then((devices) => {
                    if (devices && devices.length) {
                        let cameraId = ""; 
                        alert('counts=>'+devices.length +', devices=> '+ JSON.stringify(devices))
                        for(var i=0;i<devices.length;i++){
                          var camera = devices[i];
                          if (camera["label"].toUpperCase().includes('BACK')){
                            cameraId = camera.id; //后置摄像头
                            break;
                          }
                        }
                        
                        if (cameraId) {
                            startWithCameraId(cameraId);
                        }
                    } else {
                        startWithoutCameraId();
                    }
                })
                .catch((err) => {
                    console.log("没有获取摄像头设备...");
                });
        }

        //带相机ID扫描
        function startWithCameraId(cameraId) {
            html5QrCode
                .start(
                    { deviceId: { exact: cameraId } },
                    config,
                    onScanSuccess,
                    onScanFailure
                )
                .catch((err) => {
                    console.log("通过摄像头扫码异常....", err);
                });
        }

        //不带相机ID扫描,允许传递约束来代替相机设备 ID
        function startWithoutCameraId() {
            //environment 表示后置摄像头  换成user则表示前置摄像头
            html5QrCode.start(
                { facingMode: "environment" } || {
                    facingMode: { exact: "environment" },
                },
                config,
                onScanSuccess,
                onScanFailure
            );
        }

        //扫码解析成功后按照自己的需求做后续的操作
        function onScanSuccess(decodedText, decodedResult) {
            res.innerText = "扫码成功结果:\n" + decodedText;
            alert(decodedText);
        }

        //扫码解析失败后按照自己的需求做后续的操作
        function onScanFailure(error) {
            res.innerText = "扫码失败:\n" + error;
        }
    </script>

</body>

</html>

注意: 不是所有的浏览器都支持它,但safi 与 chrome是一定支持的!

而且 扫描代码 必须 在

中, 在中无响应;

效果:

这里是测试环境,所以手机与服务器都在同一个wifi网络 ;

还有,在线生成二维码的网站:https://www.wetools.com/qrcode

如下:

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风尘无名

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值