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

Python Django项目中移动摄像头扫码及MSSQL连接问题求助

Django项目实现移动摄像头扫条码+MSSQL连接指引

一、移动摄像头条形码扫描(替代Quagga的前端方案)

Quagga在移动端浏览器兼容性较差,推荐使用ZXing-js——对现代移动端浏览器摄像头支持更稳定,适配iOS/Android主流浏览器。

前端实现代码(Django模板)

<div class="scan-container">
  <video id="scan-video" width="320" height="240" autoplay muted playsinline></video>
  <p id="scan-result">扫描结果:</p>
  <button id="start-scan-btn">启动扫描</button>
</div>

<!-- 引入ZXing-js(可通过npm安装后本地引入,或使用CDN) -->
<script src="https://unpkg.com/@zxing/library@latest"></script>
<script>
  const codeReader = new ZXing.BrowserMultiFormatReader();
  const videoEl = document.getElementById('scan-video');
  const resultEl = document.getElementById('scan-result');
  const startBtn = document.getElementById('start-scan-btn');

  startBtn.addEventListener('click', () => {
    // 请求摄像头权限并启动扫描
    codeReader.decodeFromVideoDevice(null, videoEl, (result, err) => {
      if (result) {
        resultEl.textContent = `扫描结果:${result.text}`;
        // 将条码数据发送到Django后端
        fetch('/api/handle-barcode/', {
          method: 'POST',
          headers: {
            'X-CSRFToken': getCookie('csrftoken'),
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ barcode: result.text })
        })
        .then(res => res.json())
        .then(data => console.log('后端响应:', data))
        .catch(err => console.error('请求失败:', err));
      }
    });
  });

  // 辅助函数:获取Django CSRF令牌
  function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
      const cookies = document.cookie.split(';');
      for (let i = 0; i < cookies.length; i++) {
        const cookie = cookies[i].trim();
        if (cookie.substring(0, name.length + 1) === (name + '=')) {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
        }
      }
    }
    return cookieValue;
  }
</script>

注意事项

  • 移动端需在HTTPS环境或localhost下才能调用摄像头;
  • 确保用户允许浏览器访问摄像头权限;
  • 光线不足或条码模糊会导致扫描失败,可引导用户调整拍摄角度。

二、Django连接MSSQL服务器

推荐使用django-mssql-backend——Django官方兼容的MSSQL数据库后端,配置简单。

步骤1:安装依赖

pip install django-mssql-backend pyodbc

需提前在服务器/本地安装ODBC Driver 17 for SQL Server(Windows可直接下载安装,Linux参考微软官方文档配置)。

步骤2:配置settings.py

# settings.py
DATABASES = {
    'default': {
        'ENGINE': 'sql_server.pyodbc',
        'NAME': '你的数据库名称',
        'USER': '数据库登录用户名',
        'PASSWORD': '数据库密码',
        'HOST': 'MSSQL服务器地址(如:192.168.1.100,1433)',
        'OPTIONS': {
            'driver': 'ODBC Driver 17 for SQL Server',
        },
    }
}

步骤3:验证连接

运行以下命令,若能列出MSSQL中的数据表,说明连接成功:

python manage.py inspectdb

三、后端处理条码数据的API

1. 编写视图函数

# views.py
from django.http import JsonResponse
import json
from .models import Product  # 替换为你的MSSQL模型类

def handle_barcode(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            barcode = data.get('barcode')
            # 示例:根据条码查询MSSQL中的商品信息
            product = Product.objects.get(barcode=barcode)
            return JsonResponse({
                'status': 'success',
                'product_name': product.name,
                'price': str(product.price)
            })
        except Product.DoesNotExist:
            return JsonResponse({'status': 'error', 'msg': '未找到对应商品'})
        except Exception as e:
            return JsonResponse({'status': 'error', 'msg': str(e)})
    return JsonResponse({'status': 'error', 'msg': '仅支持POST请求'})

2. 配置路由

# urls.py
from django.urls import path
from . import views

urlpatterns = [
    # 其他路由...
    path('api/handle-barcode/', views.handle_barcode, name='handle-barcode'),
]

常见问题排查

  • MSSQL连接失败:检查服务器地址、端口(默认1433)、用户名密码是否正确,确认服务器允许远程连接;
  • 前端扫描无响应:检查浏览器摄像头权限,确保页面在HTTPS/localhost环境下;
  • ZXing识别率低:调整视频元素大小,确保条码完整出现在画面中。

内容的提问来源于stack exchange,提问作者Karthik K V

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 10:52:39