Django如何校验条形码生成输入有效性并返回对应提示
Django 条形码生成功能的输入校验+消息提示实现方案
核心实现逻辑
不用手动维护每种条形码的格式规则,python-barcode库本身内置了所有支持条码的校验逻辑(包括长度要求、允许字符范围、校验位规则等),实例化条码对象时如果输入不合法会直接抛出明确异常,结合Django自带的messages框架,在异常分支推送错误提示、校验通过分支推送成功提示即可。
改造后的views.py代码
删除原有无用导入,补充请求方法校验、参数合法性校验、异常捕获、消息推送逻辑:
from django.http import HttpResponse from django.shortcuts import redirect, render import barcode from barcode.writer import ImageWriter import tempfile from django.contrib import messages from barcode.errors import BarcodeError def index(request): context = {'barcode_types':barcode.PROVIDED_BARCODES} return render(request, 'index.html',context) def generate_barcode(request): # 拦截非POST请求 if request.method != "POST": return redirect("index") input_content = request.POST.get("inputs", "").strip() barcode_type = request.POST.get("types", "") # 基础空值、非法类型校验 if not input_content: messages.error(request, "请输入要生成条形码的内容") return redirect("index") if barcode_type not in barcode.PROVIDED_BARCODES: messages.error(request, "选择的条形码类型不合法") return redirect("index") try: barcode_class = barcode.get_barcode_class(barcode_type) # 实例化时自动触发对应条码类型的格式校验 code = barcode_class(input_content,writer=ImageWriter()) except (BarcodeError, ValueError) as e: # 校验失败,推送具体错误信息后重定向回表单页 messages.error(request, f"输入不合法:{str(e)}") return redirect("index") # 校验通过,生成并返回条码文件 with tempfile.NamedTemporaryFile() as tmp_file: file_path = code.save(tmp_file.name) messages.success(request, "条形码生成成功,即将开始下载") with open(file_path, "rb") as f: response = HttpResponse( f.read(), headers={ 'Content-Type': 'image/png', 'Content-Disposition': f'attachment; filename="{input_content}.png"' } ) return response
模板层补充配置
messages的内容需要在模板中遍历渲染才能显示,在index.html的表单上方补充消息渲染块即可,同时记得给表单加上CSRF校验标签:
<!-- 消息提示渲染块 --> {% if messages %} <div class="message-container"> {% for msg in messages %} <div class="alert {{ msg.tags }}"> {{ msg }} </div> {% endfor %} </div> {% endif %} <!-- 原有表单补充csrf_token --> <form method="POST" action="/generate/"> {% csrf_token %} <div> <label>条形码内容:</label> <input type="text" name="inputs" required> </div> <div> <label>条形码类型:</label> <select name="types"> {% for t in barcode_types %} <option value="{{ t }}">{{ t }}</option> {% endfor %} </select> </div> <button type="submit">生成条形码</button> </form>
注意事项
messages框架依赖重定向触发显示:校验失败时必须用redirect跳回表单页,不能直接render页面,否则消息不会被正常读取渲染。- 不需要手动维护条码格式规则:库自带的校验覆盖了EAN-8、EAN-13、UPC-A、Code39等所有内置条码类型的要求,比如EAN-13要求12位纯数字、EAN-8要求7位纯数字等规则都已经内置,后续库新增条码类型也不需要修改校验代码。
- 用
with语句处理临时文件和文件读取,会自动释放资源,避免服务器文件句柄泄漏。 - 原有代码中
from sre_constants import SUCCESS为无用导入,直接删除即可,没有实际作用。
内容的提问来源于stack exchange,提问作者ALQAWSI
相关产品推荐
相关产品推荐

