sightbox/backend/qrcode/qrcode_service.py

109 lines
4.5 KiB
Python

"""
qrcode_service.py — routes: POST /qrcode/generate, POST /qrcode/generate-base64.
Renders a QR code PNG for a piece of text (a tool's Serial No). Stateless —
nothing is stored on this side. No Frappe credentials are involved here —
this endpoint doesn't know or care what called it, it just turns text into
an image.
Two response shapes exist because of one specific caller's constraint: the
Frappe Server Script that attaches this image to a Serial No record runs
inside Frappe's RestrictedPython sandbox, whose only available HTTP call
(`frappe.make_post_request`) decodes any non-JSON response as UTF-8 text —
which corrupts raw binary. /qrcode/generate-base64 exists so that caller has
something it can actually consume; /qrcode/generate stays binary for direct
viewing (a browser tab, curl -o, this service's own tests).
Inbound: POST /qrcode/generate | POST /qrcode/generate-base64
Payload shape: {"data": "TOOL-00001", "label_lines": ["Cordless Drill - DeWalt 20V", "TOOL-00001"]}
"label_lines" is optional — omit it (or pass an empty list) for a plain QR
code with nothing printed beneath it. When present, each entry is printed as
its own centered line under the code, for identifying one label out of a
printed bundle without scanning it.
Response shape: /generate -> image/png bytes, or {"error", "trace_id"} on failure
/generate-base64 -> {"filename", "data_base64", "trace_id"}, or
{"error", "trace_id"} on failure
"""
import base64
import logging
from flask import Blueprint, Response, g, jsonify, request
from .qrcode_generator import QRGenerationError, generate_labeled_qr_png, generate_qr_png
logger = logging.getLogger("qrcode_service")
qrcode_bp = Blueprint("qrcode", __name__)
def _safe_filename(data):
"""Turns the encoded text into a filesystem-safe .png filename (Serial Nos are already safe, but don't assume)."""
keep = (c if c.isalnum() or c in "-_." else "_" for c in data)
return f"{''.join(keep)}.png"
def _clean_label_lines(raw_label_lines):
"""Drops blank/non-string entries so a caller can't send whitespace-only label lines."""
return [line.strip() for line in raw_label_lines if isinstance(line, str) and line.strip()]
def _render_or_error_response(data, trace_id, label_lines=None):
"""
Shared step 1-2 for both routes: validate input, render the QR code.
Data flow:
data (str) — text to encode
trace_id (str) — for the error response, if any
label_lines (list) — optional text lines to print beneath the code
returns — (png_bytes, None) on success, (None, (response, status)) on failure
"""
if not data:
return None, (jsonify({"error": "'data' is required", "trace_id": trace_id}), 400)
try:
if label_lines:
return generate_labeled_qr_png(data, label_lines), None
return generate_qr_png(data), None
except QRGenerationError as exc:
logger.warning("trace_id=%s QR generation rejected input: %s", trace_id, exc)
return None, (
jsonify({"error": "could not generate a QR code for that value", "trace_id": trace_id}),
400,
)
@qrcode_bp.route("/qrcode/generate", methods=["POST"])
def generate():
"""Renders a QR code PNG for the given text and returns it as image/png bytes."""
trace_id = g.trace_id
payload = request.get_json(silent=True) or {}
data = (payload.get("data") or "").strip()
label_lines = _clean_label_lines(payload.get("label_lines") or [])
png_bytes, error_response = _render_or_error_response(data, trace_id, label_lines)
if error_response:
return error_response
response = Response(png_bytes, mimetype="image/png")
response.headers["X-Trace-ID"] = trace_id
return response
@qrcode_bp.route("/qrcode/generate-base64", methods=["POST"])
def generate_base64():
"""Renders a QR code PNG for the given text and returns it base64-encoded in JSON."""
trace_id = g.trace_id
payload = request.get_json(silent=True) or {}
data = (payload.get("data") or "").strip()
label_lines = _clean_label_lines(payload.get("label_lines") or [])
png_bytes, error_response = _render_or_error_response(data, trace_id, label_lines)
if error_response:
return error_response
return jsonify({
"filename": _safe_filename(data),
"data_base64": base64.b64encode(png_bytes).decode("ascii"),
"trace_id": trace_id,
})