|
@@ -1,20 +1,34 @@
|
|
|
import io
|
|
|
+from typing import Union
|
|
|
from qrcode import QRCode
|
|
|
-from qrcode.constants import ERROR_CORRECT_H
|
|
|
+from qrcode.constants import ERROR_CORRECT_L, ERROR_CORRECT_M, ERROR_CORRECT_Q, ERROR_CORRECT_H
|
|
|
from qrcode.image.styledpil import StyledPilImage
|
|
|
from qrcode.image.svg import SvgPathImage
|
|
|
from qrcode.image.styles.moduledrawers.svg import SvgCircleDrawer
|
|
|
from qrcode.image.styles.colormasks import RadialGradiantColorMask
|
|
|
|
|
|
-def get_qr_code(data: bytes):
|
|
|
- qr = QRCode(error_correction=ERROR_CORRECT_H)
|
|
|
- qr.add_data(data.encode('utf-8'))
|
|
|
+QR_MAX_BYTES = {
|
|
|
+ ERROR_CORRECT_H: 1273,
|
|
|
+ ERROR_CORRECT_Q: 1663,
|
|
|
+ ERROR_CORRECT_M: 2331,
|
|
|
+ ERROR_CORRECT_L: 2953,
|
|
|
+}
|
|
|
+def get_qr_code(data: Union[bytes, str], fallback: Union[bytes, str] = None):
|
|
|
+ err_lvl = ERROR_CORRECT_H
|
|
|
+ qr = QRCode(error_correction=err_lvl)
|
|
|
+ if data is not None and isinstance(data, str):
|
|
|
+ data = data.encode('utf-8')
|
|
|
+ if fallback is not None and isinstance(fallback, str):
|
|
|
+ fallback = fallback.encode('utf-8')
|
|
|
+ if fallback is not None and data and len(data) > QR_MAX_BYTES[err_lvl]:
|
|
|
+ qr.add_data(fallback, optimize=0)
|
|
|
+ else:
|
|
|
+ qr.add_data(data or fallback, optimize=0)
|
|
|
|
|
|
- img_1 = qr.make_image(image_factory=SvgPathImage,)
|
|
|
-
|
|
|
+ img_1 = qr.make_image(image_factory=SvgPathImage)
|
|
|
with io.BytesIO() as f:
|
|
|
img_1.save(f)
|
|
|
f.flush()
|
|
|
ret = f.getvalue()
|
|
|
return ret
|
|
|
-
|
|
|
+
|