Skip to content

Commit a6757cb

Browse files
Add util functions to zip QR codes
1 parent 237e1b6 commit a6757cb

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

python/nav/web/utils.py

+26
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import io
1919
import os
2020
from datetime import datetime, timedelta
21+
import zipfile
2122

2223
from django import forms
2324
from django.http import HttpResponse, HttpRequest
@@ -120,6 +121,19 @@ def convert_bytes_buffer_to_bytes_string(bytes_buffer: io.BytesIO) -> str:
120121
return base64.b64encode(bytes_buffer.getvalue()).decode('utf-8')
121122

122123

124+
def make_qr_code_byte_buffers_into_zipped_bytes(qr_codes: dict[str, io.BytesIO]):
125+
"""
126+
Takes a dict of the form name : qr_code as byte buffer and turns it into a ZIP file
127+
with the names as filenames and returns that ZIP file as bytes
128+
"""
129+
mem_zip = io.BytesIO()
130+
with zipfile.ZipFile(mem_zip, "w", compression=zipfile.ZIP_DEFLATED) as zip_file:
131+
for image_name, bytes_stream in qr_codes.items():
132+
zip_file.writestr(image_name + ".png", bytes_stream.getvalue())
133+
134+
return mem_zip.getvalue()
135+
136+
123137
def generate_qr_codes_as_byte_strings(url_dict: dict[str, str]) -> list[str]:
124138
"""
125139
Takes a dict of the form {name:url} and returns a list of generated QR codes as
@@ -134,6 +148,18 @@ def generate_qr_codes_as_byte_strings(url_dict: dict[str, str]) -> list[str]:
134148
return qr_code_byte_strings
135149

136150

151+
def generate_qr_codes_as_zip_file(url_dict: dict[str, str]) -> bytes:
152+
"""
153+
Takes a dict of the form {name:url} and optionally a file name and returns a ZIP
154+
file containing QR codes as PNGs with the given file name as name
155+
"""
156+
qr_codes_dict = dict()
157+
for caption, url in url_dict.items():
158+
qr_codes_dict[caption] = generate_qr_code(url=url, caption=caption)
159+
160+
return make_qr_code_byte_buffers_into_zipped_bytes(qr_codes=qr_codes_dict)
161+
162+
137163
def validate_timedelta_for_overflow(days: int = 0, hours: int = 0):
138164
"""
139165
Validates that the given numbers of days and hours when subtracted from the

0 commit comments

Comments
 (0)