From 7b32ef9a114bd88f96c6684d14e556c35bf24350 Mon Sep 17 00:00:00 2001 From: Benjamin Dauvergne Date: Thu, 24 Jun 2021 19:24:47 +0200 Subject: [PATCH 1/2] templatetags: add a qrcode filter for string values --- tests/test_templates.py | 23 +++++++++++++++++++++++ wcs/qommon/templatetags/qommon.py | 23 ++++++++++++++++++++++- 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/tests/test_templates.py b/tests/test_templates.py index 8f06b5ef..14a96f5c 100644 --- a/tests/test_templates.py +++ b/tests/test_templates.py @@ -13,6 +13,8 @@ try: except ImportError: langdetect = None +import PIL + from wcs import fields from wcs.formdef import FormDef from wcs.qommon.http_request import HTTPRequest @@ -1211,3 +1213,24 @@ def test_iterate_days_until(pub): ) assert t.render({'value': 'error1', 'value2': 'error2'}) == '' + + +def test_qrcode(pub): + with pub.complex_data(): + img = Template('{{ url|qrcode }}').render({'url': 'http://example.com/', 'allow_complex': True}) + assert pub.has_cached_complex_data(img) + value = pub.get_cached_complex_data(img) + assert value.orig_filename == 'qrcode.png' + assert value.content_type == 'image/png' + with value.get_file_pointer() as fp: + img = PIL.Image.open(fp) + assert img.size == (330, 330) + + img = Template('{{ url|qrcode:"qrcode2.png" }}').render( + {'url': 'http://example.com/', 'allow_complex': True} + ) + value = pub.get_cached_complex_data(img) + assert value.orig_filename == 'qrcode2.png' + + img = Template('{{ url|qrcode }}').render({'url': 1, 'allow_complex': True}) + assert img == '' diff --git a/wcs/qommon/templatetags/qommon.py b/wcs/qommon/templatetags/qommon.py index a4ecc7f9..f5fe1204 100644 --- a/wcs/qommon/templatetags/qommon.py +++ b/wcs/qommon/templatetags/qommon.py @@ -16,6 +16,7 @@ import datetime import hashlib +import io import math import random import string @@ -26,6 +27,12 @@ from decimal import DivisionByZero as DecimalDivisionByZero from decimal import InvalidOperation as DecimalInvalidOperation import pyproj + +try: + import qrcode +except ImportError: + qrcode = None + from pyproj import Geod from quixote import get_publisher @@ -42,7 +49,7 @@ from django.utils.encoding import force_bytes, force_text from django.utils.safestring import mark_safe from django.utils.timezone import is_naive, make_aware -from wcs.qommon import calendar, evalutils, tokens +from wcs.qommon import calendar, evalutils, tokens, upload_storage from wcs.qommon.admin.texts import TextsDirectory register = template.Library() @@ -817,3 +824,17 @@ def strip_metadata(value): def list_(value): # turn a generator into a list return list(unlazy(value)) + + +@register.filter(name='qrcode') +def qrcode_filter(value, name=None): + if not qrcode: + return '' + if not isinstance(value, str): + return '' + img = qrcode.make(value) + buf = io.BytesIO() + img.save(buf) + upload = upload_storage.PicklableUpload(name or 'qrcode.png', 'image/png') + upload.receive([buf.getvalue()]) + return upload -- 2.32.0.rc0