You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django中通过Webcam读取条形码并跳转至指定视图?

Django摄像头条码扫描跳转实现方案

可行性确认

完全可行,不管是前端直接解析跳转,还是后端配合前端轮询,都能实现你要的“扫码后停摄像头+跳转到helloView”的流程。

条码捕获的最优位置:前端

不建议在后端VideoCamera.get_frame里处理条码捕获——后端生成视频流的逻辑没法直接控制前端页面跳转,而且每帧都在后端解析条码会占用服务器资源,效率低。

直接在前端用条码扫描库(比如QuaggaJS)实时解析摄像头画面,步骤如下:

  1. 在展示摄像头的页面引入条码扫描库,初始化摄像头流
  2. 监听条码解析事件,当匹配到目标条码9788366384088时:
    • 立即停止摄像头流
    • 跳转到helloView的URL(可携带条码参数)

前端代码示例

<video id="camera-stream" autoplay playsinline></video>
<script src="quagga.min.js"></script>
<script>
// 初始化QuaggaJS
Quagga.init({
    inputStream: {
        type: "LiveStream",
        target: document.querySelector('#camera-stream'),
        constraints: {
            facingMode: "environment", // 调用后置摄像头(移动端)
            width: 640,
            height: 480
        }
    },
    decoder: {
        readers: ["ean_reader"] // 针对EAN条码类型
    }
}, function(err) {
    if (err) return console.error(err);
    Quagga.start();
});

// 监听条码识别事件
Quagga.onDetected(function(result) {
    const scannedBarcode = result.codeResult.code;
    if (scannedBarcode === "9788366384088") {
        Quagga.stop(); // 停止摄像头
        // 跳转到helloView,可携带条码参数
        window.location.href = "{% url 'hello-view' %}?barcode=" + scannedBarcode;
    }
});
</script>

后端helloView接收参数

from django.shortcuts import render

def helloView(request):
    scanned_barcode = request.GET.get('barcode', '')
    # 可根据条码做后续逻辑
    return render(request, 'hello.html', {'barcode': scanned_barcode})

备选方案:后端解析+前端轮询

如果必须在后端做条码验证(比如需要查询数据库确认条码有效性),可以这么做:

  1. 在VideoCamera类里维护一个扫描状态,当解析到目标条码时,把状态存入用户Session(注意要关联当前用户会话,视频流视图需要加上@login_required或者通过Cookie关联)
  2. 前端页面定时发送AJAX请求到后端的检查接口,比如/check-scan-status/
  3. 后端接口返回扫描状态,前端收到“已扫描”的响应后,停止摄像头并跳转

后端核心代码示例

# VideoCamera类
class VideoCamera:
    def __init__(self, request):
        self.request = request
        self.scanned = False
        # 其他初始化逻辑...

    def get_frame(self):
        # 获取摄像头帧的逻辑...
        # 解析条码(用pyzbar等库)
        from pyzbar.pyzbar import decode
        import cv2
        frame = self.get_current_frame() # 你的帧获取逻辑
        barcodes = decode(frame)
        for barcode in barcodes:
            barcode_data = barcode.data.decode('utf-8')
            if barcode_data == "9788366384088":
                self.request.session['barcode_scanned'] = True
                self.scanned = True
                break
        # 返回帧的逻辑...

# 检查扫描状态的视图
def check_scan_status(request):
    scanned = request.session.get('barcode_scanned', False)
    return JsonResponse({'scanned': scanned})

前端轮询代码

setInterval(function() {
    fetch('/check-scan-status/')
        .then(response => response.json())
        .then(data => {
            if (data.scanned) {
                // 停止摄像头(根据你的摄像头实现方式)
                stopCamera();
                window.location.href = "{% url 'hello-view' %}";
            }
        });
}, 1000); // 每秒轮询一次

内容的提问来源于stack exchange,提问作者Mateusz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 00:18:19