summaryrefslogtreecommitdiff
path: root/python-django-qr-code.spec
blob: 77ae4383b304681ea78c0351df6c85f75c9ea7fc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
%global _empty_manifest_terminate_build 0
Name:		python-django-qr-code
Version:	3.1.1
Release:	1
Summary:	An application that provides tools for displaying QR codes on your Django site.
License:	BSD 3-clause
URL:		https://github.com/dprog-philippe-docourt/django-qr-code
Source0:	https://mirrors.nju.edu.cn/pypi/web/packages/9a/c5/02d810e7c8dd1186a8347b4c7d374477a19bad5d037ed76a822f1519b4e6/django-qr-code-3.1.1.tar.gz
BuildArch:	noarch

Requires:	python3-segno
Requires:	python3-django
Requires:	python3-pytz
Requires:	python3-pydantic

%description
# Django QR Code
[![Latest PyPI version](https://badge.fury.io/py/django-qr-code.svg)](https://badge.fury.io/py/django-qr-code)
[![Downloads](https://img.shields.io/pypi/dm/django-qr-code.svg)](https://pypi.python.org/pypi/django-qr-code)
[![Documentation Status](https://readthedocs.org/projects/django-qr-code/badge/?version=latest)](http://django-qr-code.readthedocs.io/en/latest/)
[![Build Status](https://travis-ci.com/dprog-philippe-docourt/django-qr-code.svg?branch=master)](https://app.travis-ci.com/github/dprog-philippe-docourt/django-qr-code)
[![Maintainability](https://api.codeclimate.com/v1/badges/c47e79bf51f6a2bb8264/maintainability)](https://codeclimate.com/github/dprog-philippe-docourt/django-qr-code/maintainability)
[![Coverage Status](https://coveralls.io/repos/github/dprog-philippe-docourt/django-qr-code/badge.svg?branch=master)](https://coveralls.io/github/dprog-philippe-docourt/django-qr-code?branch=master)

This is an application that provides tools for displaying QR codes on your [Django](https://www.djangoproject.com/) site.

This application depends on the [Segno QR Code generator](https://pypi.org/project/segno/) library.

This app makes no usage of the Django models and therefore do not use any database.

Only Python >= 3.7 is supported.

## Installation

### Binary Package from PyPi
In order to use this app in a Django project, the simplest way is to install it from [PyPi](https://pypi.python.org/pypi/django-qr-code):
```bash
pip install django-qr-code
```

### From the Source Code
In order to modify or test this app you may want to install it from the source code.

Clone the [GitHub repository](https://github.com/dprog-philippe-docourt/django-qr-code) and then run:
```bash
pip install -r requirements.txt -r requirements-dev.txt
python manage.py collectstatic --no-input
```

## Usage
Start by adding `qr_code` to your `INSTALLED_APPS` setting like this:
```python
INSTALLED_APPS = (
    # ...,
    'qr_code',
)
```

You need to load the tags provided by this app in your template with:
```djangotemplate
{% load qr_code %}
```

The source code on [GitHub](https://github.com/dprog-philippe-docourt/django-qr-code) contains a simple demo app. Please check out the [templates folder](https://github.com/dprog-philippe-docourt/django-qr-code/tree/master/qr_code_demo/templates/qr_code_demo) for an example of template, and the [setting](https://github.com/dprog-philippe-docourt/django-qr-code/tree/master/demo_site/settings.py) and [urls](https://github.com/dprog-philippe-docourt/django-qr-code/tree/master/demo_site/urls.py) files for an example of configuration and integration.

### Generating Inline QR Code in your HTML (qr_from_text)
The tag **`qr_from_text`** generates an embedded `svg` or `img` tag within the HTML code produced by your template.

The following renders a tiny "hello world" QR code with a `svg` tag:
```djangotemplate
{% qr_from_text "Hello World!" size="T" %}
```
Here is a medium "hello world" QR code with an `img` tag:
```djangotemplate
{% qr_from_text "Hello World!" size="m" image_format="png" error_correction="L" %}
```

### QR Code Rendering Options

The `size` parameter gives the size of each module of the QR code matrix. It can be either a positive integer or one of the following letters:

* t or T: tiny (value: 6)
* s or S: small (value: 12)
* m or M: medium (value: 18)
* l or L: large (value: 30)
* h or H: huge (value: 48)

For PNG image format the size unit is in pixels, while the unit is 1 mm for SVG format.

Here is a "hello world" QR code using the version 12:
```djangotemplate
{% qr_from_text "Hello World!" size=8 version=12 %}
```
The `version` parameter is an integer from 1 to 40 that controls the size of the QR code matrix. Set to None to determine this automatically. The smallest, version 1, is a 21 x 21 matrix. The biggest, version 40, is 177 x 177 matrix. The size grows by 4 modules/side.

Here is a "hello world" QR code using a border of 6 modules:
```djangotemplate
{% qr_from_text "Hello World!" size=10 border=6 %}
```
The `border` parameter controls how many modules thick the border should be (the default is 4, which is the minimum according to the specs).

There are 4 error correction levels used for QR codes, with each one adding different amounts of "backup" data
depending on how much damage the QR code is expected to suffer in its intended environment, and hence how much
error correction may be required. The correction level can be configured with the `error_correction` parameter as follows:
* l or L: error correction level L – up to 7% damage
* m or M: error correction level M – up to 15% damage
* q or Q: error correction level Q – up to 25% damage
* h or H: error correction level H – up to 30% damage

You may enforce the creation of a Micro QR Code with `micro=True`. The `micro` option defaults to `False`.

The `encoding` option controls the text encoding used in mode "byte" (used for any general text content). By default `encoding` is ``UTF-8``. When set to ``None``, the implementation (based on Segno) tries to use the standard conform ISO/IEC 8859-1 encoding and if it does not fit, it will use UTF-8. Note that no ECI mode indicator is inserted by default (see `eci` option). The `encoding` parameter is case-insensitive.

The `boost_error` indicates whether the QR code encoding engine (Segno) tries to increase the error correction level if it does not affect the version. Error correction level is not increased when it impacts the version of the code.

The `eci` option indicates if binary data which does not use the default encoding (ISO/IEC 8859-1) should enforce the ECI mode. Since a lot of QR code readers do not support the ECI mode, this feature is disabled by default and the data is encoded in the provided encoding using the usual “byte” mode. Set eci to `True` if an ECI header should be inserted into the QR Code. Note that the implementation may not know the ECI designator for the provided encoding and may raise an exception if the ECI designator cannot be found. The ECI mode is not supported by Micro QR Codes.

Alternatively, you may use the `options` keyword argument with an instance of `QRCodeOptions` as value instead of listing every requested options. Here is an example of view: 
```python
from django.shortcuts import render
from qr_code.qrcode.utils import QRCodeOptions

def my_view(request):
    # Build context for rendering QR codes.
    context = dict(
        my_options=QRCodeOptions(size='t', border=6, error_correction='L'),
    )

    # Render the view.
    return render(request, 'my_app/my_view.html', context=context)
```

and an example of template for the view above:
```djangotemplate
{% qr_from_text "Hello World!" options=my_options %}
```

### Generating URLs to QR Code Images (qr_url_from_text)
The **`qr_url_from_text`** tag generates an url to an image representing the QR code. It comes with the same options as `qr_from_text` to customize the image format (SVG or PNG), the size, the border, and the matrix size. It also has an additional option **`cache_enabled`** to disable caching of served image.

Here is a medium "hello world" QR code that uses an URL to serve the image in SVG format:

```djangotemplate
<img src="{% qr_url_from_text "Hello World!" %}" alt="Hello World!">
```

Here is a "hello world" QR code in version 10 that uses an URL to serve the image in PNG format:

```djangotemplate
<img src="{% qr_url_from_text "Hello World!" size=8 version=10 image_format='png' %}" alt="Hello World!">
```

The image targeted by the generated URL is served by a view provided in `qr_code.urls`. Therefore, you need to include the URLs provided by `qr_code.urls` in your app in order to make this tag work. This can be achieved with something like this:

```python
from django.conf.urls import include
from django.urls import path

urlpatterns = [
    path('qr_code/', include('qr_code.urls', namespace="qr_code")),
]
```

The QR code images are served via a URL named **`qr_code:serve_qr_code_image`**. You can customize the path under which the images are served (i.e. the path bound to the URL named `qr_code:serve_qr_code_image`) with the optional setting **`SERVE_QR_CODE_IMAGE_PATH`** which defaults to `images/serve-qr-code-image/`. Note that the trailing slash is mandatory and that defining this setting to an empty string leads to using the default value. The example below will serve any QR code image from `<base URL or your application>/qr-code-image/`:

```python
# In urls.py
from django.conf.urls import include
from django.urls import path

urlpatterns = [
    path('', include('qr_code.urls', namespace='qr_code')),
]

# In your settings
SERVE_QR_CODE_IMAGE_PATH = 'qr-code-image/'
```

### Generating Image Object Representing a QR Code

If you do not want to use Django tags for rendering QR code in a template, you can simply use the API in your code. For instance, `qr_code.qrcode.maker.make_qr_code_image` will return bytes representing an image according to the image_format passed in the `qr_code_options` parameter.

### Special encoding modes with qr_from_data and qr_url_from_data
The tags **`qr_from_data`** and  **`qr_url_from_data`** produce results similar to those of `qr_from_text` and `qr_url_from_text`, but they avoid converting everything to text (UTF-8 encoded by default, or any supported charset depending on `encoding` option).

The ISO/IEC 18004 standard defines four modes in order to encode the data as efficiently as possible.

#### Numeric mode
The numeric mode is the most efficient way to encode digits. This mode does not cover negative numbers because it does not support the minus sign (or plus sign).

The numeric mode is supported by QR Codes and Micro QR Codes. The encoding engine detects (Segno) the numeric mode if the data is provided as string (e.g. '54') or integer (e.g. 54) to `qr_from_data` or `qr_url_from_data`.

#### Alphanumeric mode
The alphanumeric mode extends the numeric mode by various characters. Namely, about the upper case letters ABCDEFGHIJKLMNOPQRSTUVWXYZ, a space character " " and other letters $%*+-./:.

#### Kanji mode
Kanji can be encoded compactly and efficiently and requires significantly less space than encoding the characters in UTF-8.

#### Byte mode
The byte mode covers all data which cannot be represented by the other modes. When the `encoding` option is set to `None`, the encoding engine (Segno) detects, according to ISO/IEC 18004, to encode the data with ISO 8859-1. In case the data cannot be represented by ISO 8859-1, UTF-8 is used as fallback.

NOTE: When using `qr_from_text` or `qr_url_from_text`, the byte mode with UTF-8 encoding is forced by default . You may use the `encoding` option to change this behavior. It appears to be one of the most portable way of encoding text for proper decoding among the readers.

#### Examples
The following renders a tiny numeric QR code containing the value `2021` with a `svg` tag:
```djangotemplate
{% qr_from_data 2021 size="T" %}
```

Here is a micro QR code with an `img` tag containing the value `2021`:
```djangotemplate
{% qr_from_data 2021 micro=True image_format="png" %}
```

### Caching Served Images

A large QR code (version 40) requires 0.2 second to be generated on a powerful machine (in 2018), and probably more than half a second on a really cheap hosting.

The image served by the *qr_code* app can be cached to improve performances and reduce CPU usage required to generate the QR codes. In order to activate caching, you simply need to declare a cache alias with the setting **`QR_CODE_CACHE_ALIAS`** to indicate in which cache to store the generated QR codes.

For instance, you may declare an additional cache for your QR codes like this in your Django settings:
```python
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
    },
    'qr-code': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'qr-code-cache',
        'TIMEOUT': 3600
    }
}

QR_CODE_CACHE_ALIAS = 'qr-code'
```

The `QR_CODE_CACHE_ALIAS = 'qr-code'` tells the *qr_code* app to use that cache for storing the generated QR codes. All QR codes will be cached with the specified *TIMEOUT* when a non-empty value is set to `QR_CODE_CACHE_ALIAS`.

If you want to activate the cache for QR codes, but skip the caching for some specific codes, you can use the keyword argument `cache_enabled=False` when using `qr_url_from_text`.

Here is a "hello world" QR code in version 20 with an error correction level Q (25% of redundant data) that uses a URL to serve the image in SVG format, and disable caching for served image:
```djangotemplate
<img src="{% qr_url_from_text "Hello World!" size=8 version=20 error_correction="Q" cache_enabled=False %}" alt="Hello World!">
```

### Protecting Access to QR Code Images

The default settings protect the URLs that serve QR code images against external requests, and thus against possibly easy (D)DoS attacks.

Here are the available settings to manage the protection for served images:
```python
from qr_code.qrcode import constants

QR_CODE_URL_PROTECTION = {
    constants.TOKEN_LENGTH: 30,                         # Optional random token length for URL protection. Defaults to 20.
    constants.SIGNING_KEY: 'my-secret-signing-key',     # Optional signing key for URL token. Uses SECRET_KEY if not defined.
    constants.SIGNING_SALT: 'my-signing-salt',          # Optional signing salt for URL token.
    constants.ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER: True  # Tells whether a registered user can request the QR code URLs from outside a site that uses this app. It can be a boolean value used for any user or a callable that takes a user as parameter. Defaults to False (nobody can access the URL without the signature token).
}
```

#### Signing Request URLs

By default, the application only serves QR code images for authenticated URLs (requests generated from your application and addressed to your application). The authentication uses a HMAC to sign the request query arguments. The authentication code is passed as a query argument named **`token`** which is automatically generated by `qr_url_from_text`  or `qr_url_from_data`. Whenever the signature is invalid, the application returns a *HTTP 403 Permission denied* response when processing the request for serving a QR code image.

This mechanism ensures that, by default, nobody can send external requests to your application to obtain custom QR codes for free. This is especially useful if you display QR code URLs on public pages (no user authentication).

The `token` query argument is not mandatory and, when a request reaches the `qr_code:serve_qr_code_image` URL without that token, the protection mechanism falls back to the user authentication mechanism (see chapter below).

It is possible to explicitly remove the  signature token that protects a specific URL with the parameter **`url_signature_enabled=False`**. Here is a "hello world" QR code that uses a URL to serve the image in SVG format without the `token` query argument :

```djangotemplate
<img src="{% qr_url_from_text "Hello World!" url_signature_enabled=False %}" alt="Hello World!">
```

The `token` parameter will not be part of the query string of the generated URL, making possible to build a simpler, predictable URL. However, this will trigger the user authentication mechanism (see chapter below).

#### Handling User Authentication when Serving QR Code Images

If you are interested in providing the QR code images as a service, there is a setting named **`ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER`** to grant access to some controlled users. This setting tells who can bypass the url signature token (see chapter above). It can be a boolean value used for any authenticated user, or a callable that takes a user as only parameter.

Setting the `ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER` option to `True` tells the application to serve QR code images to authenticated users only. Hence, to grant access to any authenticated user to generated images, you can use this in your settings:

```python
from qr_code.qrcode import constants

QR_CODE_URL_PROTECTION = {
    constants.ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER: True
}
```

Setting the option `ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER` to a callable that always returns `True` (even for anonymous users) will allow anyone to access QR code image generation from outside your Django app. The following settings will grant access to anonymous users to generated images:

```python
from qr_code.qrcode import constants

QR_CODE_URL_PROTECTION = {
    constants.ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER: lambda u: True
}
```

Please note that, if your service is available on the Internet, allowing anyone to generate any kind of QR code via your Django application - as shown above - might generate a very heavy load on your server.

### QR Codes for Apps

Aside from generating a QR code from a given text, you can also generate codes for specific application purposes, that a reader can interpret as an action to take: open a mail client to send an e-mail to a given address, add a contact to your phone book, connect to a Wi-Fi, start a SMS, etc.  See [this documentation](https://github.com/zxing/zxing/wiki/Barcode-Contents) about what a QR code can encode.

Django QR Code proposes several utility tags to ease the generation of such codes, without having to build the appropriate text representation for each action you need. This remove the hassle of reading the specifications and handling all the required escaping for reserved chars.

Please note that some commands are common patterns, rather than formal specifications. Therefore, there is no guarantee that all QR code readers will handle them properly.

The following tags targeting apps are available:
* `qr_for_email` and `qr_url_for_email`
* `qr_for_tel` and `qr_url_for_tel`
* `qr_for_sms` and `qr_url_for_sms`
* `qr_for_geolocation` and `qr_url_for_geolocation`
* `qr_for_google_maps` and `qr_url_for_google_maps`
* `qr_for_youtube` and `qr_url_for_youtube`
* `qr_for_google_play` and `qr_url_for_google_play`
* `qr_for_mecard` and `qr_url_for_mecard`
* `qr_for_vcard` and `qr_url_for_vcard`
* `qr_for_wifi` and `qr_url_for_wifi`
* `qr_for_epc` and `qr_url_for_epc`
* `qr_for_event` and `qr_url_for_event`
* `qr_for_contact` and `qr_url_for_contact` (legacy, do not use in new projects)

You could write a view like this:

```python
import datetime
from datetime import date
from django.shortcuts import render
from qr_code.qrcode.utils import MeCard, VCard, EpcData, VEvent, EventClass, EventTransparency, EventStatus, WifiConfig, Coordinates, QRCodeOptions


def application_qr_code_demo(request):
    # Use a MeCard instance to encapsulate the detail of the contact.
    mecard_contact = MeCard(
        name='Doe, John',
        phone='+41769998877',
        email='j.doe@company.com',
        url='http://www.company.com',
        birthday=date(year=1985, month=10, day=2),
        memo='Development Manager',
        org='Company Ltd'
    )

    # Use a VCard instance to encapsulate the detail of the contact.
    vcard_contact = VCard(
        name='Doe; John',
        phone='+41769998877',
        email='j.doe@company.com',
        url='http://www.company.com',
        birthday=date(year=1985, month=10, day=2),
        street='Cras des Fourches 987',
        city='Delémont',
        zipcode=2800,
        region='Jura',
        country='Switzerland',
        memo='Development Manager',
        org='Company Ltd'
    )

    # Use a WifiConfig instance to encapsulate the configuration of the connexion.
    wifi_config = WifiConfig(
        ssid='my-wifi',
        authentication=WifiConfig.AUTHENTICATION.WPA,
        password='wifi-password'
    )

    # Use a EpcData instance to encapsulate the data of the European Payments Council Quick Response Code.
    epc_data = EpcData(
        name='Wikimedia Foerdergesellschaft',
        iban='DE33100205000001194700',
        amount=50.0,
        text='To Wikipedia'
    )

    # Build coordinates instances.
    google_maps_coordinates = Coordinates(latitude=586000.32, longitude=250954.19)
    geolocation_coordinates = Coordinates(latitude=586000.32, longitude=250954.19, altitude=500)

    # Build event data (VEVENT properties)
    # NB for start and end of event:
    #   - Naive date and time is rendered as floating time.
    #   - Aware date and time is rendered as UTC converted time.
    event = VEvent(
        uid="some-event-id",
        summary="Vacations",
        start=datetime.datetime(2022, 8, 6, hour=8, minute=30),
        end=datetime.datetime(2022, 8, 17, hour=12),
        location="New-York, Statue de la Liberté",
        geo=(40.69216097988203, -74.04460073403436),
        categories=["PERSO", "holidays"],
        status=EventStatus.CONFIRMED,
        event_class=EventClass.PRIVATE,
        transparency=EventTransparency.OPAQUE,
        organizer="foo@bar.com",
        url="https://bar.com",
        description="""Fake description. Meeting to provide technical review for "Phoenix" design. Happy Face Conference Room.

Phoenix design team MUST attend this meeting.

RSVP to team leader."""
    )
    
    # Build context for rendering QR codes.
    context = dict(
        mecard_contact=mecard_contact,
        vcard_contact=vcard_contact,
        wifi_config=wifi_config,
        epc_data=epc_data,
        event=event,
        video_id='J9go2nj6b3M',
        google_maps_coordinates=google_maps_coordinates,
        geolocation_coordinates=geolocation_coordinates,
        options_example=QRCodeOptions(size='t', border=6, error_correction='L'),
    )

    # Render the index page.
    return render(request, 'my_app/application_qr_code_demo.html', context=context)
```

Then, in your template, you can render the appropriate QR codes for the given context:
```djangotemplate
<h3>Add contact '{{ mecard_contact.name }}' to phone book</h3>
{% qr_for_mecard mecard=mecard_contact size='S' %}
<p>or:</p>
{% qr_for_contact mecard_contact size='S' %}
<p>or:</p>
{% qr_for_contact mecard_contact options=options_example %}

<h3>Add contact '{{ vcard_contact.name }}' to phone book</h3>
{% qr_for_vcard vcard=vcard_contact size='S' %}
<p>or:</p>
{% qr_for_contact vcard_contact size='S' %}
<p>or:</p>
{% qr_for_contact vcard_contact options=options_example %}

<h3>Configure Wi-Fi connexion to '{{ wifi_config.ssid }}'</h3>
<img src="{% qr_url_for_wifi wifi_config=wifi_config size='T' error_correction='Q' %}">
<p>or:</p>
<img src="{% qr_url_for_wifi wifi_config size='T' error_correction='Q' %}">
<p>or:</p>
<img src="{% qr_url_for_wifi wifi_config options=options_example %}">

<h3>EPC QR Code'</h3>
<img src="{% qr_url_for_epc epc_data=epc_data %}">
<p>or:</p>
<img src="{% qr_url_for_epc epc_data size='H' %}">

<h3>Event QR Code'</h3>
<img src="{% qr_url_for_event event=event %}">
<p>or:</p>
{% qr_for_event event=event %}

<h3>Watch YouTube video '{{ video_id }}'</h3>
{% qr_for_youtube video_id image_format='png' size='T' %}
<p>or:</p>
{% qr_for_youtube video_id options=options_example %}

<h3>Open map at location: ({{ geolocation_coordinates }})</h3>
<img src="{% qr_url_for_geolocation coordinates=geolocation_coordinates %}">
<p>or:</p>
<img src="{% qr_url_for_geolocation latitude=geolocation_coordinates.latitude longitude=geolocation_coordinates.longitude altitude=geolocation_coordinates.altitude %}">
<p>or:</p>
<img src="{% qr_url_for_geolocation latitude=geolocation_coordinates.latitude longitude=geolocation_coordinates.longitude altitude=geolocation_coordinates.altitude options=options_example %}">

<h3>Open Google Maps App at location: ({{ google_maps_coordinates }})</h3>
{% qr_for_google_maps coordinates=google_maps_coordinates %}
<p>or:</p>
{% qr_for_google_maps latitude=google_maps_coordinates.latitude longitude=google_maps_coordinates.longitude %}
<p>or:</p>
{% qr_for_google_maps latitude=google_maps_coordinates.latitude longitude=google_maps_coordinates.longitude options=options_example %}
```

Please check out the [demo application](#demo-application) to see more examples.

## Notes

### Image Formats
The SVG is the default image format. It is a vector image format so it can be scaled up and down without quality loss. However, it has two drawbacks. The size is not given in pixel, which can be problematic if the design of your website relies on a fixed width (in pixels). The format is less compact than PNG and results in a larger HTML content. Note that a base64 PNG is less compressible than a SVG tag, so it might not matter that much of you use HTML compression on your web server.

SVG has [broad support](http://caniuse.com/#feat=svg) now, and it will work properly on any modern web browser.

### qr_from_text vs qr_url_from_text
The tag `qr_url_from_text` has several advantages over `qr_from_text`, despite the fact that it requires a bit more of writing:
* the generated HTML code does not contain heavy inline image data (lighter and cleaner content)
* the generated images can be cached (served with a separate HTML request)
* the HTML tag used to render the QR code is always an `<img>` tag, which may simplify CSS handling
* the HTML tag embedding the image is not generated for you, which allows for customization of attributes (*height*, *width*, *alt*)
* the page can be loaded asynchronously, which improves responsiveness
* you can provide links to QR codes instead of displaying them, which is not possible with `qr_from_text`

One disadvantage of `qr_url_from_text` is that it increases the number of requests to the server: one request to serve the page containing the URL and another to request the image.

Be aware that serving image files (which are generated on the fly) from a URL can be abused and lead to (D)DoS attack pretty easily, for instance by requesting very large QR codes from outside your application. This is the reason why the associated setting `ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER` in `QR_CODE_URL_PROTECTION` defaults to completely forbid external access to the API. Be careful when opening external access.

### QR Codes Caching
Caching QR codes reduces CPU usage, but the usage of `qr_url_from_text` (which caching depends on) increases the number of requests to the server (one request to serve the page containing the URL and another to request the image).

Moreover, be aware that the largest QR codes, in version 40 with a border of 4 modules and rendered in SVG format, have a size of ~800 KB.
Be sure that your cache options are reasonable and can be supported by your server(s), especially for in-memory caching.

Note that even without caching the generated QR codes, the app will return a *HTTP 304 Not Modified* status code whenever the same QR code is requested again. The URL named **`qr_code:serve_qr_code_image`** adds the `ETag` and `Last-Modified` headers to the response if the headers aren't already set, enabling  *HTTP 304 Not Modified* response upon following requests.

## Demo Application
If you want to try this app, you may want to use the demo application shipped alongside the source code.

Get the source code from [GitHub](https://github.com/dprog-philippe-docourt/django-qr-code), follow the [installation instructions](#from-the-source-code) above, and run the `runserver` command of Django:
```bash
python manage.py runserver
```
The demo application should be running at <http://127.0.0.1:8000/qr-code-demo/>.

If you have [Docker Compose](https://docs.docker.com/compose/) installed, you can simply run the following from a terminal (this will save you the burden of setting up a proper python environment):
```bash
cd scripts
./run-demo-app.sh
```
The demo application should be running at <http://127.0.0.1:8910/qr-code-demo/>.

## Testing
Get the source code from [GitHub](https://github.com/dprog-philippe-docourt/django-qr-code), follow the [installation instructions](#from-the-source-code) above, and run the `test` command of Django:
```bash
python manage.py test
```
This will run the test suite with the locally installed version of Python and Django.

If you have [Docker Compose](https://docs.docker.com/compose/) installed, you can simply run the following from a terminal (this will save you the burden of setting up a proper python environment):
```bash
cd scripts
./run-tests.sh
```
This will run the test suite with all supported versions of Python and Django. The test results are stored within `tests_result` folder.

## Projects Using this App

This app is used in the following projects:
* [MyGym Web](https://mygym-web.ch/): a web platform for managing sports clubs. The QR codes are used for importing members' contact information in a phone book.
* [Gymna-Score](https://gymna-score.acjg.ch/): a web platform for entering scores during gymnastics competitions organized by the Association Cantonale Jurassienne de Gymnastique (ACJG). The QR codes are used to provide an easy way for the public to follow an ongoing competition. They are also used to authenticate judges that need to enter scores.
* [AC-Ju](https://www.ac-ju.ch/): a website that generates digital vouchers that can be redeemed at affiliate merchants.


%package -n python3-django-qr-code
Summary:	An application that provides tools for displaying QR codes on your Django site.
Provides:	python-django-qr-code
BuildRequires:	python3-devel
BuildRequires:	python3-setuptools
BuildRequires:	python3-pip
%description -n python3-django-qr-code
# Django QR Code
[![Latest PyPI version](https://badge.fury.io/py/django-qr-code.svg)](https://badge.fury.io/py/django-qr-code)
[![Downloads](https://img.shields.io/pypi/dm/django-qr-code.svg)](https://pypi.python.org/pypi/django-qr-code)
[![Documentation Status](https://readthedocs.org/projects/django-qr-code/badge/?version=latest)](http://django-qr-code.readthedocs.io/en/latest/)
[![Build Status](https://travis-ci.com/dprog-philippe-docourt/django-qr-code.svg?branch=master)](https://app.travis-ci.com/github/dprog-philippe-docourt/django-qr-code)
[![Maintainability](https://api.codeclimate.com/v1/badges/c47e79bf51f6a2bb8264/maintainability)](https://codeclimate.com/github/dprog-philippe-docourt/django-qr-code/maintainability)
[![Coverage Status](https://coveralls.io/repos/github/dprog-philippe-docourt/django-qr-code/badge.svg?branch=master)](https://coveralls.io/github/dprog-philippe-docourt/django-qr-code?branch=master)

This is an application that provides tools for displaying QR codes on your [Django](https://www.djangoproject.com/) site.

This application depends on the [Segno QR Code generator](https://pypi.org/project/segno/) library.

This app makes no usage of the Django models and therefore do not use any database.

Only Python >= 3.7 is supported.

## Installation

### Binary Package from PyPi
In order to use this app in a Django project, the simplest way is to install it from [PyPi](https://pypi.python.org/pypi/django-qr-code):
```bash
pip install django-qr-code
```

### From the Source Code
In order to modify or test this app you may want to install it from the source code.

Clone the [GitHub repository](https://github.com/dprog-philippe-docourt/django-qr-code) and then run:
```bash
pip install -r requirements.txt -r requirements-dev.txt
python manage.py collectstatic --no-input
```

## Usage
Start by adding `qr_code` to your `INSTALLED_APPS` setting like this:
```python
INSTALLED_APPS = (
    # ...,
    'qr_code',
)
```

You need to load the tags provided by this app in your template with:
```djangotemplate
{% load qr_code %}
```

The source code on [GitHub](https://github.com/dprog-philippe-docourt/django-qr-code) contains a simple demo app. Please check out the [templates folder](https://github.com/dprog-philippe-docourt/django-qr-code/tree/master/qr_code_demo/templates/qr_code_demo) for an example of template, and the [setting](https://github.com/dprog-philippe-docourt/django-qr-code/tree/master/demo_site/settings.py) and [urls](https://github.com/dprog-philippe-docourt/django-qr-code/tree/master/demo_site/urls.py) files for an example of configuration and integration.

### Generating Inline QR Code in your HTML (qr_from_text)
The tag **`qr_from_text`** generates an embedded `svg` or `img` tag within the HTML code produced by your template.

The following renders a tiny "hello world" QR code with a `svg` tag:
```djangotemplate
{% qr_from_text "Hello World!" size="T" %}
```
Here is a medium "hello world" QR code with an `img` tag:
```djangotemplate
{% qr_from_text "Hello World!" size="m" image_format="png" error_correction="L" %}
```

### QR Code Rendering Options

The `size` parameter gives the size of each module of the QR code matrix. It can be either a positive integer or one of the following letters:

* t or T: tiny (value: 6)
* s or S: small (value: 12)
* m or M: medium (value: 18)
* l or L: large (value: 30)
* h or H: huge (value: 48)

For PNG image format the size unit is in pixels, while the unit is 1 mm for SVG format.

Here is a "hello world" QR code using the version 12:
```djangotemplate
{% qr_from_text "Hello World!" size=8 version=12 %}
```
The `version` parameter is an integer from 1 to 40 that controls the size of the QR code matrix. Set to None to determine this automatically. The smallest, version 1, is a 21 x 21 matrix. The biggest, version 40, is 177 x 177 matrix. The size grows by 4 modules/side.

Here is a "hello world" QR code using a border of 6 modules:
```djangotemplate
{% qr_from_text "Hello World!" size=10 border=6 %}
```
The `border` parameter controls how many modules thick the border should be (the default is 4, which is the minimum according to the specs).

There are 4 error correction levels used for QR codes, with each one adding different amounts of "backup" data
depending on how much damage the QR code is expected to suffer in its intended environment, and hence how much
error correction may be required. The correction level can be configured with the `error_correction` parameter as follows:
* l or L: error correction level L – up to 7% damage
* m or M: error correction level M – up to 15% damage
* q or Q: error correction level Q – up to 25% damage
* h or H: error correction level H – up to 30% damage

You may enforce the creation of a Micro QR Code with `micro=True`. The `micro` option defaults to `False`.

The `encoding` option controls the text encoding used in mode "byte" (used for any general text content). By default `encoding` is ``UTF-8``. When set to ``None``, the implementation (based on Segno) tries to use the standard conform ISO/IEC 8859-1 encoding and if it does not fit, it will use UTF-8. Note that no ECI mode indicator is inserted by default (see `eci` option). The `encoding` parameter is case-insensitive.

The `boost_error` indicates whether the QR code encoding engine (Segno) tries to increase the error correction level if it does not affect the version. Error correction level is not increased when it impacts the version of the code.

The `eci` option indicates if binary data which does not use the default encoding (ISO/IEC 8859-1) should enforce the ECI mode. Since a lot of QR code readers do not support the ECI mode, this feature is disabled by default and the data is encoded in the provided encoding using the usual “byte” mode. Set eci to `True` if an ECI header should be inserted into the QR Code. Note that the implementation may not know the ECI designator for the provided encoding and may raise an exception if the ECI designator cannot be found. The ECI mode is not supported by Micro QR Codes.

Alternatively, you may use the `options` keyword argument with an instance of `QRCodeOptions` as value instead of listing every requested options. Here is an example of view: 
```python
from django.shortcuts import render
from qr_code.qrcode.utils import QRCodeOptions

def my_view(request):
    # Build context for rendering QR codes.
    context = dict(
        my_options=QRCodeOptions(size='t', border=6, error_correction='L'),
    )

    # Render the view.
    return render(request, 'my_app/my_view.html', context=context)
```

and an example of template for the view above:
```djangotemplate
{% qr_from_text "Hello World!" options=my_options %}
```

### Generating URLs to QR Code Images (qr_url_from_text)
The **`qr_url_from_text`** tag generates an url to an image representing the QR code. It comes with the same options as `qr_from_text` to customize the image format (SVG or PNG), the size, the border, and the matrix size. It also has an additional option **`cache_enabled`** to disable caching of served image.

Here is a medium "hello world" QR code that uses an URL to serve the image in SVG format:

```djangotemplate
<img src="{% qr_url_from_text "Hello World!" %}" alt="Hello World!">
```

Here is a "hello world" QR code in version 10 that uses an URL to serve the image in PNG format:

```djangotemplate
<img src="{% qr_url_from_text "Hello World!" size=8 version=10 image_format='png' %}" alt="Hello World!">
```

The image targeted by the generated URL is served by a view provided in `qr_code.urls`. Therefore, you need to include the URLs provided by `qr_code.urls` in your app in order to make this tag work. This can be achieved with something like this:

```python
from django.conf.urls import include
from django.urls import path

urlpatterns = [
    path('qr_code/', include('qr_code.urls', namespace="qr_code")),
]
```

The QR code images are served via a URL named **`qr_code:serve_qr_code_image`**. You can customize the path under which the images are served (i.e. the path bound to the URL named `qr_code:serve_qr_code_image`) with the optional setting **`SERVE_QR_CODE_IMAGE_PATH`** which defaults to `images/serve-qr-code-image/`. Note that the trailing slash is mandatory and that defining this setting to an empty string leads to using the default value. The example below will serve any QR code image from `<base URL or your application>/qr-code-image/`:

```python
# In urls.py
from django.conf.urls import include
from django.urls import path

urlpatterns = [
    path('', include('qr_code.urls', namespace='qr_code')),
]

# In your settings
SERVE_QR_CODE_IMAGE_PATH = 'qr-code-image/'
```

### Generating Image Object Representing a QR Code

If you do not want to use Django tags for rendering QR code in a template, you can simply use the API in your code. For instance, `qr_code.qrcode.maker.make_qr_code_image` will return bytes representing an image according to the image_format passed in the `qr_code_options` parameter.

### Special encoding modes with qr_from_data and qr_url_from_data
The tags **`qr_from_data`** and  **`qr_url_from_data`** produce results similar to those of `qr_from_text` and `qr_url_from_text`, but they avoid converting everything to text (UTF-8 encoded by default, or any supported charset depending on `encoding` option).

The ISO/IEC 18004 standard defines four modes in order to encode the data as efficiently as possible.

#### Numeric mode
The numeric mode is the most efficient way to encode digits. This mode does not cover negative numbers because it does not support the minus sign (or plus sign).

The numeric mode is supported by QR Codes and Micro QR Codes. The encoding engine detects (Segno) the numeric mode if the data is provided as string (e.g. '54') or integer (e.g. 54) to `qr_from_data` or `qr_url_from_data`.

#### Alphanumeric mode
The alphanumeric mode extends the numeric mode by various characters. Namely, about the upper case letters ABCDEFGHIJKLMNOPQRSTUVWXYZ, a space character " " and other letters $%*+-./:.

#### Kanji mode
Kanji can be encoded compactly and efficiently and requires significantly less space than encoding the characters in UTF-8.

#### Byte mode
The byte mode covers all data which cannot be represented by the other modes. When the `encoding` option is set to `None`, the encoding engine (Segno) detects, according to ISO/IEC 18004, to encode the data with ISO 8859-1. In case the data cannot be represented by ISO 8859-1, UTF-8 is used as fallback.

NOTE: When using `qr_from_text` or `qr_url_from_text`, the byte mode with UTF-8 encoding is forced by default . You may use the `encoding` option to change this behavior. It appears to be one of the most portable way of encoding text for proper decoding among the readers.

#### Examples
The following renders a tiny numeric QR code containing the value `2021` with a `svg` tag:
```djangotemplate
{% qr_from_data 2021 size="T" %}
```

Here is a micro QR code with an `img` tag containing the value `2021`:
```djangotemplate
{% qr_from_data 2021 micro=True image_format="png" %}
```

### Caching Served Images

A large QR code (version 40) requires 0.2 second to be generated on a powerful machine (in 2018), and probably more than half a second on a really cheap hosting.

The image served by the *qr_code* app can be cached to improve performances and reduce CPU usage required to generate the QR codes. In order to activate caching, you simply need to declare a cache alias with the setting **`QR_CODE_CACHE_ALIAS`** to indicate in which cache to store the generated QR codes.

For instance, you may declare an additional cache for your QR codes like this in your Django settings:
```python
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
    },
    'qr-code': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'qr-code-cache',
        'TIMEOUT': 3600
    }
}

QR_CODE_CACHE_ALIAS = 'qr-code'
```

The `QR_CODE_CACHE_ALIAS = 'qr-code'` tells the *qr_code* app to use that cache for storing the generated QR codes. All QR codes will be cached with the specified *TIMEOUT* when a non-empty value is set to `QR_CODE_CACHE_ALIAS`.

If you want to activate the cache for QR codes, but skip the caching for some specific codes, you can use the keyword argument `cache_enabled=False` when using `qr_url_from_text`.

Here is a "hello world" QR code in version 20 with an error correction level Q (25% of redundant data) that uses a URL to serve the image in SVG format, and disable caching for served image:
```djangotemplate
<img src="{% qr_url_from_text "Hello World!" size=8 version=20 error_correction="Q" cache_enabled=False %}" alt="Hello World!">
```

### Protecting Access to QR Code Images

The default settings protect the URLs that serve QR code images against external requests, and thus against possibly easy (D)DoS attacks.

Here are the available settings to manage the protection for served images:
```python
from qr_code.qrcode import constants

QR_CODE_URL_PROTECTION = {
    constants.TOKEN_LENGTH: 30,                         # Optional random token length for URL protection. Defaults to 20.
    constants.SIGNING_KEY: 'my-secret-signing-key',     # Optional signing key for URL token. Uses SECRET_KEY if not defined.
    constants.SIGNING_SALT: 'my-signing-salt',          # Optional signing salt for URL token.
    constants.ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER: True  # Tells whether a registered user can request the QR code URLs from outside a site that uses this app. It can be a boolean value used for any user or a callable that takes a user as parameter. Defaults to False (nobody can access the URL without the signature token).
}
```

#### Signing Request URLs

By default, the application only serves QR code images for authenticated URLs (requests generated from your application and addressed to your application). The authentication uses a HMAC to sign the request query arguments. The authentication code is passed as a query argument named **`token`** which is automatically generated by `qr_url_from_text`  or `qr_url_from_data`. Whenever the signature is invalid, the application returns a *HTTP 403 Permission denied* response when processing the request for serving a QR code image.

This mechanism ensures that, by default, nobody can send external requests to your application to obtain custom QR codes for free. This is especially useful if you display QR code URLs on public pages (no user authentication).

The `token` query argument is not mandatory and, when a request reaches the `qr_code:serve_qr_code_image` URL without that token, the protection mechanism falls back to the user authentication mechanism (see chapter below).

It is possible to explicitly remove the  signature token that protects a specific URL with the parameter **`url_signature_enabled=False`**. Here is a "hello world" QR code that uses a URL to serve the image in SVG format without the `token` query argument :

```djangotemplate
<img src="{% qr_url_from_text "Hello World!" url_signature_enabled=False %}" alt="Hello World!">
```

The `token` parameter will not be part of the query string of the generated URL, making possible to build a simpler, predictable URL. However, this will trigger the user authentication mechanism (see chapter below).

#### Handling User Authentication when Serving QR Code Images

If you are interested in providing the QR code images as a service, there is a setting named **`ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER`** to grant access to some controlled users. This setting tells who can bypass the url signature token (see chapter above). It can be a boolean value used for any authenticated user, or a callable that takes a user as only parameter.

Setting the `ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER` option to `True` tells the application to serve QR code images to authenticated users only. Hence, to grant access to any authenticated user to generated images, you can use this in your settings:

```python
from qr_code.qrcode import constants

QR_CODE_URL_PROTECTION = {
    constants.ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER: True
}
```

Setting the option `ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER` to a callable that always returns `True` (even for anonymous users) will allow anyone to access QR code image generation from outside your Django app. The following settings will grant access to anonymous users to generated images:

```python
from qr_code.qrcode import constants

QR_CODE_URL_PROTECTION = {
    constants.ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER: lambda u: True
}
```

Please note that, if your service is available on the Internet, allowing anyone to generate any kind of QR code via your Django application - as shown above - might generate a very heavy load on your server.

### QR Codes for Apps

Aside from generating a QR code from a given text, you can also generate codes for specific application purposes, that a reader can interpret as an action to take: open a mail client to send an e-mail to a given address, add a contact to your phone book, connect to a Wi-Fi, start a SMS, etc.  See [this documentation](https://github.com/zxing/zxing/wiki/Barcode-Contents) about what a QR code can encode.

Django QR Code proposes several utility tags to ease the generation of such codes, without having to build the appropriate text representation for each action you need. This remove the hassle of reading the specifications and handling all the required escaping for reserved chars.

Please note that some commands are common patterns, rather than formal specifications. Therefore, there is no guarantee that all QR code readers will handle them properly.

The following tags targeting apps are available:
* `qr_for_email` and `qr_url_for_email`
* `qr_for_tel` and `qr_url_for_tel`
* `qr_for_sms` and `qr_url_for_sms`
* `qr_for_geolocation` and `qr_url_for_geolocation`
* `qr_for_google_maps` and `qr_url_for_google_maps`
* `qr_for_youtube` and `qr_url_for_youtube`
* `qr_for_google_play` and `qr_url_for_google_play`
* `qr_for_mecard` and `qr_url_for_mecard`
* `qr_for_vcard` and `qr_url_for_vcard`
* `qr_for_wifi` and `qr_url_for_wifi`
* `qr_for_epc` and `qr_url_for_epc`
* `qr_for_event` and `qr_url_for_event`
* `qr_for_contact` and `qr_url_for_contact` (legacy, do not use in new projects)

You could write a view like this:

```python
import datetime
from datetime import date
from django.shortcuts import render
from qr_code.qrcode.utils import MeCard, VCard, EpcData, VEvent, EventClass, EventTransparency, EventStatus, WifiConfig, Coordinates, QRCodeOptions


def application_qr_code_demo(request):
    # Use a MeCard instance to encapsulate the detail of the contact.
    mecard_contact = MeCard(
        name='Doe, John',
        phone='+41769998877',
        email='j.doe@company.com',
        url='http://www.company.com',
        birthday=date(year=1985, month=10, day=2),
        memo='Development Manager',
        org='Company Ltd'
    )

    # Use a VCard instance to encapsulate the detail of the contact.
    vcard_contact = VCard(
        name='Doe; John',
        phone='+41769998877',
        email='j.doe@company.com',
        url='http://www.company.com',
        birthday=date(year=1985, month=10, day=2),
        street='Cras des Fourches 987',
        city='Delémont',
        zipcode=2800,
        region='Jura',
        country='Switzerland',
        memo='Development Manager',
        org='Company Ltd'
    )

    # Use a WifiConfig instance to encapsulate the configuration of the connexion.
    wifi_config = WifiConfig(
        ssid='my-wifi',
        authentication=WifiConfig.AUTHENTICATION.WPA,
        password='wifi-password'
    )

    # Use a EpcData instance to encapsulate the data of the European Payments Council Quick Response Code.
    epc_data = EpcData(
        name='Wikimedia Foerdergesellschaft',
        iban='DE33100205000001194700',
        amount=50.0,
        text='To Wikipedia'
    )

    # Build coordinates instances.
    google_maps_coordinates = Coordinates(latitude=586000.32, longitude=250954.19)
    geolocation_coordinates = Coordinates(latitude=586000.32, longitude=250954.19, altitude=500)

    # Build event data (VEVENT properties)
    # NB for start and end of event:
    #   - Naive date and time is rendered as floating time.
    #   - Aware date and time is rendered as UTC converted time.
    event = VEvent(
        uid="some-event-id",
        summary="Vacations",
        start=datetime.datetime(2022, 8, 6, hour=8, minute=30),
        end=datetime.datetime(2022, 8, 17, hour=12),
        location="New-York, Statue de la Liberté",
        geo=(40.69216097988203, -74.04460073403436),
        categories=["PERSO", "holidays"],
        status=EventStatus.CONFIRMED,
        event_class=EventClass.PRIVATE,
        transparency=EventTransparency.OPAQUE,
        organizer="foo@bar.com",
        url="https://bar.com",
        description="""Fake description. Meeting to provide technical review for "Phoenix" design. Happy Face Conference Room.

Phoenix design team MUST attend this meeting.

RSVP to team leader."""
    )
    
    # Build context for rendering QR codes.
    context = dict(
        mecard_contact=mecard_contact,
        vcard_contact=vcard_contact,
        wifi_config=wifi_config,
        epc_data=epc_data,
        event=event,
        video_id='J9go2nj6b3M',
        google_maps_coordinates=google_maps_coordinates,
        geolocation_coordinates=geolocation_coordinates,
        options_example=QRCodeOptions(size='t', border=6, error_correction='L'),
    )

    # Render the index page.
    return render(request, 'my_app/application_qr_code_demo.html', context=context)
```

Then, in your template, you can render the appropriate QR codes for the given context:
```djangotemplate
<h3>Add contact '{{ mecard_contact.name }}' to phone book</h3>
{% qr_for_mecard mecard=mecard_contact size='S' %}
<p>or:</p>
{% qr_for_contact mecard_contact size='S' %}
<p>or:</p>
{% qr_for_contact mecard_contact options=options_example %}

<h3>Add contact '{{ vcard_contact.name }}' to phone book</h3>
{% qr_for_vcard vcard=vcard_contact size='S' %}
<p>or:</p>
{% qr_for_contact vcard_contact size='S' %}
<p>or:</p>
{% qr_for_contact vcard_contact options=options_example %}

<h3>Configure Wi-Fi connexion to '{{ wifi_config.ssid }}'</h3>
<img src="{% qr_url_for_wifi wifi_config=wifi_config size='T' error_correction='Q' %}">
<p>or:</p>
<img src="{% qr_url_for_wifi wifi_config size='T' error_correction='Q' %}">
<p>or:</p>
<img src="{% qr_url_for_wifi wifi_config options=options_example %}">

<h3>EPC QR Code'</h3>
<img src="{% qr_url_for_epc epc_data=epc_data %}">
<p>or:</p>
<img src="{% qr_url_for_epc epc_data size='H' %}">

<h3>Event QR Code'</h3>
<img src="{% qr_url_for_event event=event %}">
<p>or:</p>
{% qr_for_event event=event %}

<h3>Watch YouTube video '{{ video_id }}'</h3>
{% qr_for_youtube video_id image_format='png' size='T' %}
<p>or:</p>
{% qr_for_youtube video_id options=options_example %}

<h3>Open map at location: ({{ geolocation_coordinates }})</h3>
<img src="{% qr_url_for_geolocation coordinates=geolocation_coordinates %}">
<p>or:</p>
<img src="{% qr_url_for_geolocation latitude=geolocation_coordinates.latitude longitude=geolocation_coordinates.longitude altitude=geolocation_coordinates.altitude %}">
<p>or:</p>
<img src="{% qr_url_for_geolocation latitude=geolocation_coordinates.latitude longitude=geolocation_coordinates.longitude altitude=geolocation_coordinates.altitude options=options_example %}">

<h3>Open Google Maps App at location: ({{ google_maps_coordinates }})</h3>
{% qr_for_google_maps coordinates=google_maps_coordinates %}
<p>or:</p>
{% qr_for_google_maps latitude=google_maps_coordinates.latitude longitude=google_maps_coordinates.longitude %}
<p>or:</p>
{% qr_for_google_maps latitude=google_maps_coordinates.latitude longitude=google_maps_coordinates.longitude options=options_example %}
```

Please check out the [demo application](#demo-application) to see more examples.

## Notes

### Image Formats
The SVG is the default image format. It is a vector image format so it can be scaled up and down without quality loss. However, it has two drawbacks. The size is not given in pixel, which can be problematic if the design of your website relies on a fixed width (in pixels). The format is less compact than PNG and results in a larger HTML content. Note that a base64 PNG is less compressible than a SVG tag, so it might not matter that much of you use HTML compression on your web server.

SVG has [broad support](http://caniuse.com/#feat=svg) now, and it will work properly on any modern web browser.

### qr_from_text vs qr_url_from_text
The tag `qr_url_from_text` has several advantages over `qr_from_text`, despite the fact that it requires a bit more of writing:
* the generated HTML code does not contain heavy inline image data (lighter and cleaner content)
* the generated images can be cached (served with a separate HTML request)
* the HTML tag used to render the QR code is always an `<img>` tag, which may simplify CSS handling
* the HTML tag embedding the image is not generated for you, which allows for customization of attributes (*height*, *width*, *alt*)
* the page can be loaded asynchronously, which improves responsiveness
* you can provide links to QR codes instead of displaying them, which is not possible with `qr_from_text`

One disadvantage of `qr_url_from_text` is that it increases the number of requests to the server: one request to serve the page containing the URL and another to request the image.

Be aware that serving image files (which are generated on the fly) from a URL can be abused and lead to (D)DoS attack pretty easily, for instance by requesting very large QR codes from outside your application. This is the reason why the associated setting `ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER` in `QR_CODE_URL_PROTECTION` defaults to completely forbid external access to the API. Be careful when opening external access.

### QR Codes Caching
Caching QR codes reduces CPU usage, but the usage of `qr_url_from_text` (which caching depends on) increases the number of requests to the server (one request to serve the page containing the URL and another to request the image).

Moreover, be aware that the largest QR codes, in version 40 with a border of 4 modules and rendered in SVG format, have a size of ~800 KB.
Be sure that your cache options are reasonable and can be supported by your server(s), especially for in-memory caching.

Note that even without caching the generated QR codes, the app will return a *HTTP 304 Not Modified* status code whenever the same QR code is requested again. The URL named **`qr_code:serve_qr_code_image`** adds the `ETag` and `Last-Modified` headers to the response if the headers aren't already set, enabling  *HTTP 304 Not Modified* response upon following requests.

## Demo Application
If you want to try this app, you may want to use the demo application shipped alongside the source code.

Get the source code from [GitHub](https://github.com/dprog-philippe-docourt/django-qr-code), follow the [installation instructions](#from-the-source-code) above, and run the `runserver` command of Django:
```bash
python manage.py runserver
```
The demo application should be running at <http://127.0.0.1:8000/qr-code-demo/>.

If you have [Docker Compose](https://docs.docker.com/compose/) installed, you can simply run the following from a terminal (this will save you the burden of setting up a proper python environment):
```bash
cd scripts
./run-demo-app.sh
```
The demo application should be running at <http://127.0.0.1:8910/qr-code-demo/>.

## Testing
Get the source code from [GitHub](https://github.com/dprog-philippe-docourt/django-qr-code), follow the [installation instructions](#from-the-source-code) above, and run the `test` command of Django:
```bash
python manage.py test
```
This will run the test suite with the locally installed version of Python and Django.

If you have [Docker Compose](https://docs.docker.com/compose/) installed, you can simply run the following from a terminal (this will save you the burden of setting up a proper python environment):
```bash
cd scripts
./run-tests.sh
```
This will run the test suite with all supported versions of Python and Django. The test results are stored within `tests_result` folder.

## Projects Using this App

This app is used in the following projects:
* [MyGym Web](https://mygym-web.ch/): a web platform for managing sports clubs. The QR codes are used for importing members' contact information in a phone book.
* [Gymna-Score](https://gymna-score.acjg.ch/): a web platform for entering scores during gymnastics competitions organized by the Association Cantonale Jurassienne de Gymnastique (ACJG). The QR codes are used to provide an easy way for the public to follow an ongoing competition. They are also used to authenticate judges that need to enter scores.
* [AC-Ju](https://www.ac-ju.ch/): a website that generates digital vouchers that can be redeemed at affiliate merchants.


%package help
Summary:	Development documents and examples for django-qr-code
Provides:	python3-django-qr-code-doc
%description help
# Django QR Code
[![Latest PyPI version](https://badge.fury.io/py/django-qr-code.svg)](https://badge.fury.io/py/django-qr-code)
[![Downloads](https://img.shields.io/pypi/dm/django-qr-code.svg)](https://pypi.python.org/pypi/django-qr-code)
[![Documentation Status](https://readthedocs.org/projects/django-qr-code/badge/?version=latest)](http://django-qr-code.readthedocs.io/en/latest/)
[![Build Status](https://travis-ci.com/dprog-philippe-docourt/django-qr-code.svg?branch=master)](https://app.travis-ci.com/github/dprog-philippe-docourt/django-qr-code)
[![Maintainability](https://api.codeclimate.com/v1/badges/c47e79bf51f6a2bb8264/maintainability)](https://codeclimate.com/github/dprog-philippe-docourt/django-qr-code/maintainability)
[![Coverage Status](https://coveralls.io/repos/github/dprog-philippe-docourt/django-qr-code/badge.svg?branch=master)](https://coveralls.io/github/dprog-philippe-docourt/django-qr-code?branch=master)

This is an application that provides tools for displaying QR codes on your [Django](https://www.djangoproject.com/) site.

This application depends on the [Segno QR Code generator](https://pypi.org/project/segno/) library.

This app makes no usage of the Django models and therefore do not use any database.

Only Python >= 3.7 is supported.

## Installation

### Binary Package from PyPi
In order to use this app in a Django project, the simplest way is to install it from [PyPi](https://pypi.python.org/pypi/django-qr-code):
```bash
pip install django-qr-code
```

### From the Source Code
In order to modify or test this app you may want to install it from the source code.

Clone the [GitHub repository](https://github.com/dprog-philippe-docourt/django-qr-code) and then run:
```bash
pip install -r requirements.txt -r requirements-dev.txt
python manage.py collectstatic --no-input
```

## Usage
Start by adding `qr_code` to your `INSTALLED_APPS` setting like this:
```python
INSTALLED_APPS = (
    # ...,
    'qr_code',
)
```

You need to load the tags provided by this app in your template with:
```djangotemplate
{% load qr_code %}
```

The source code on [GitHub](https://github.com/dprog-philippe-docourt/django-qr-code) contains a simple demo app. Please check out the [templates folder](https://github.com/dprog-philippe-docourt/django-qr-code/tree/master/qr_code_demo/templates/qr_code_demo) for an example of template, and the [setting](https://github.com/dprog-philippe-docourt/django-qr-code/tree/master/demo_site/settings.py) and [urls](https://github.com/dprog-philippe-docourt/django-qr-code/tree/master/demo_site/urls.py) files for an example of configuration and integration.

### Generating Inline QR Code in your HTML (qr_from_text)
The tag **`qr_from_text`** generates an embedded `svg` or `img` tag within the HTML code produced by your template.

The following renders a tiny "hello world" QR code with a `svg` tag:
```djangotemplate
{% qr_from_text "Hello World!" size="T" %}
```
Here is a medium "hello world" QR code with an `img` tag:
```djangotemplate
{% qr_from_text "Hello World!" size="m" image_format="png" error_correction="L" %}
```

### QR Code Rendering Options

The `size` parameter gives the size of each module of the QR code matrix. It can be either a positive integer or one of the following letters:

* t or T: tiny (value: 6)
* s or S: small (value: 12)
* m or M: medium (value: 18)
* l or L: large (value: 30)
* h or H: huge (value: 48)

For PNG image format the size unit is in pixels, while the unit is 1 mm for SVG format.

Here is a "hello world" QR code using the version 12:
```djangotemplate
{% qr_from_text "Hello World!" size=8 version=12 %}
```
The `version` parameter is an integer from 1 to 40 that controls the size of the QR code matrix. Set to None to determine this automatically. The smallest, version 1, is a 21 x 21 matrix. The biggest, version 40, is 177 x 177 matrix. The size grows by 4 modules/side.

Here is a "hello world" QR code using a border of 6 modules:
```djangotemplate
{% qr_from_text "Hello World!" size=10 border=6 %}
```
The `border` parameter controls how many modules thick the border should be (the default is 4, which is the minimum according to the specs).

There are 4 error correction levels used for QR codes, with each one adding different amounts of "backup" data
depending on how much damage the QR code is expected to suffer in its intended environment, and hence how much
error correction may be required. The correction level can be configured with the `error_correction` parameter as follows:
* l or L: error correction level L – up to 7% damage
* m or M: error correction level M – up to 15% damage
* q or Q: error correction level Q – up to 25% damage
* h or H: error correction level H – up to 30% damage

You may enforce the creation of a Micro QR Code with `micro=True`. The `micro` option defaults to `False`.

The `encoding` option controls the text encoding used in mode "byte" (used for any general text content). By default `encoding` is ``UTF-8``. When set to ``None``, the implementation (based on Segno) tries to use the standard conform ISO/IEC 8859-1 encoding and if it does not fit, it will use UTF-8. Note that no ECI mode indicator is inserted by default (see `eci` option). The `encoding` parameter is case-insensitive.

The `boost_error` indicates whether the QR code encoding engine (Segno) tries to increase the error correction level if it does not affect the version. Error correction level is not increased when it impacts the version of the code.

The `eci` option indicates if binary data which does not use the default encoding (ISO/IEC 8859-1) should enforce the ECI mode. Since a lot of QR code readers do not support the ECI mode, this feature is disabled by default and the data is encoded in the provided encoding using the usual “byte” mode. Set eci to `True` if an ECI header should be inserted into the QR Code. Note that the implementation may not know the ECI designator for the provided encoding and may raise an exception if the ECI designator cannot be found. The ECI mode is not supported by Micro QR Codes.

Alternatively, you may use the `options` keyword argument with an instance of `QRCodeOptions` as value instead of listing every requested options. Here is an example of view: 
```python
from django.shortcuts import render
from qr_code.qrcode.utils import QRCodeOptions

def my_view(request):
    # Build context for rendering QR codes.
    context = dict(
        my_options=QRCodeOptions(size='t', border=6, error_correction='L'),
    )

    # Render the view.
    return render(request, 'my_app/my_view.html', context=context)
```

and an example of template for the view above:
```djangotemplate
{% qr_from_text "Hello World!" options=my_options %}
```

### Generating URLs to QR Code Images (qr_url_from_text)
The **`qr_url_from_text`** tag generates an url to an image representing the QR code. It comes with the same options as `qr_from_text` to customize the image format (SVG or PNG), the size, the border, and the matrix size. It also has an additional option **`cache_enabled`** to disable caching of served image.

Here is a medium "hello world" QR code that uses an URL to serve the image in SVG format:

```djangotemplate
<img src="{% qr_url_from_text "Hello World!" %}" alt="Hello World!">
```

Here is a "hello world" QR code in version 10 that uses an URL to serve the image in PNG format:

```djangotemplate
<img src="{% qr_url_from_text "Hello World!" size=8 version=10 image_format='png' %}" alt="Hello World!">
```

The image targeted by the generated URL is served by a view provided in `qr_code.urls`. Therefore, you need to include the URLs provided by `qr_code.urls` in your app in order to make this tag work. This can be achieved with something like this:

```python
from django.conf.urls import include
from django.urls import path

urlpatterns = [
    path('qr_code/', include('qr_code.urls', namespace="qr_code")),
]
```

The QR code images are served via a URL named **`qr_code:serve_qr_code_image`**. You can customize the path under which the images are served (i.e. the path bound to the URL named `qr_code:serve_qr_code_image`) with the optional setting **`SERVE_QR_CODE_IMAGE_PATH`** which defaults to `images/serve-qr-code-image/`. Note that the trailing slash is mandatory and that defining this setting to an empty string leads to using the default value. The example below will serve any QR code image from `<base URL or your application>/qr-code-image/`:

```python
# In urls.py
from django.conf.urls import include
from django.urls import path

urlpatterns = [
    path('', include('qr_code.urls', namespace='qr_code')),
]

# In your settings
SERVE_QR_CODE_IMAGE_PATH = 'qr-code-image/'
```

### Generating Image Object Representing a QR Code

If you do not want to use Django tags for rendering QR code in a template, you can simply use the API in your code. For instance, `qr_code.qrcode.maker.make_qr_code_image` will return bytes representing an image according to the image_format passed in the `qr_code_options` parameter.

### Special encoding modes with qr_from_data and qr_url_from_data
The tags **`qr_from_data`** and  **`qr_url_from_data`** produce results similar to those of `qr_from_text` and `qr_url_from_text`, but they avoid converting everything to text (UTF-8 encoded by default, or any supported charset depending on `encoding` option).

The ISO/IEC 18004 standard defines four modes in order to encode the data as efficiently as possible.

#### Numeric mode
The numeric mode is the most efficient way to encode digits. This mode does not cover negative numbers because it does not support the minus sign (or plus sign).

The numeric mode is supported by QR Codes and Micro QR Codes. The encoding engine detects (Segno) the numeric mode if the data is provided as string (e.g. '54') or integer (e.g. 54) to `qr_from_data` or `qr_url_from_data`.

#### Alphanumeric mode
The alphanumeric mode extends the numeric mode by various characters. Namely, about the upper case letters ABCDEFGHIJKLMNOPQRSTUVWXYZ, a space character " " and other letters $%*+-./:.

#### Kanji mode
Kanji can be encoded compactly and efficiently and requires significantly less space than encoding the characters in UTF-8.

#### Byte mode
The byte mode covers all data which cannot be represented by the other modes. When the `encoding` option is set to `None`, the encoding engine (Segno) detects, according to ISO/IEC 18004, to encode the data with ISO 8859-1. In case the data cannot be represented by ISO 8859-1, UTF-8 is used as fallback.

NOTE: When using `qr_from_text` or `qr_url_from_text`, the byte mode with UTF-8 encoding is forced by default . You may use the `encoding` option to change this behavior. It appears to be one of the most portable way of encoding text for proper decoding among the readers.

#### Examples
The following renders a tiny numeric QR code containing the value `2021` with a `svg` tag:
```djangotemplate
{% qr_from_data 2021 size="T" %}
```

Here is a micro QR code with an `img` tag containing the value `2021`:
```djangotemplate
{% qr_from_data 2021 micro=True image_format="png" %}
```

### Caching Served Images

A large QR code (version 40) requires 0.2 second to be generated on a powerful machine (in 2018), and probably more than half a second on a really cheap hosting.

The image served by the *qr_code* app can be cached to improve performances and reduce CPU usage required to generate the QR codes. In order to activate caching, you simply need to declare a cache alias with the setting **`QR_CODE_CACHE_ALIAS`** to indicate in which cache to store the generated QR codes.

For instance, you may declare an additional cache for your QR codes like this in your Django settings:
```python
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
    },
    'qr-code': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'qr-code-cache',
        'TIMEOUT': 3600
    }
}

QR_CODE_CACHE_ALIAS = 'qr-code'
```

The `QR_CODE_CACHE_ALIAS = 'qr-code'` tells the *qr_code* app to use that cache for storing the generated QR codes. All QR codes will be cached with the specified *TIMEOUT* when a non-empty value is set to `QR_CODE_CACHE_ALIAS`.

If you want to activate the cache for QR codes, but skip the caching for some specific codes, you can use the keyword argument `cache_enabled=False` when using `qr_url_from_text`.

Here is a "hello world" QR code in version 20 with an error correction level Q (25% of redundant data) that uses a URL to serve the image in SVG format, and disable caching for served image:
```djangotemplate
<img src="{% qr_url_from_text "Hello World!" size=8 version=20 error_correction="Q" cache_enabled=False %}" alt="Hello World!">
```

### Protecting Access to QR Code Images

The default settings protect the URLs that serve QR code images against external requests, and thus against possibly easy (D)DoS attacks.

Here are the available settings to manage the protection for served images:
```python
from qr_code.qrcode import constants

QR_CODE_URL_PROTECTION = {
    constants.TOKEN_LENGTH: 30,                         # Optional random token length for URL protection. Defaults to 20.
    constants.SIGNING_KEY: 'my-secret-signing-key',     # Optional signing key for URL token. Uses SECRET_KEY if not defined.
    constants.SIGNING_SALT: 'my-signing-salt',          # Optional signing salt for URL token.
    constants.ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER: True  # Tells whether a registered user can request the QR code URLs from outside a site that uses this app. It can be a boolean value used for any user or a callable that takes a user as parameter. Defaults to False (nobody can access the URL without the signature token).
}
```

#### Signing Request URLs

By default, the application only serves QR code images for authenticated URLs (requests generated from your application and addressed to your application). The authentication uses a HMAC to sign the request query arguments. The authentication code is passed as a query argument named **`token`** which is automatically generated by `qr_url_from_text`  or `qr_url_from_data`. Whenever the signature is invalid, the application returns a *HTTP 403 Permission denied* response when processing the request for serving a QR code image.

This mechanism ensures that, by default, nobody can send external requests to your application to obtain custom QR codes for free. This is especially useful if you display QR code URLs on public pages (no user authentication).

The `token` query argument is not mandatory and, when a request reaches the `qr_code:serve_qr_code_image` URL without that token, the protection mechanism falls back to the user authentication mechanism (see chapter below).

It is possible to explicitly remove the  signature token that protects a specific URL with the parameter **`url_signature_enabled=False`**. Here is a "hello world" QR code that uses a URL to serve the image in SVG format without the `token` query argument :

```djangotemplate
<img src="{% qr_url_from_text "Hello World!" url_signature_enabled=False %}" alt="Hello World!">
```

The `token` parameter will not be part of the query string of the generated URL, making possible to build a simpler, predictable URL. However, this will trigger the user authentication mechanism (see chapter below).

#### Handling User Authentication when Serving QR Code Images

If you are interested in providing the QR code images as a service, there is a setting named **`ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER`** to grant access to some controlled users. This setting tells who can bypass the url signature token (see chapter above). It can be a boolean value used for any authenticated user, or a callable that takes a user as only parameter.

Setting the `ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER` option to `True` tells the application to serve QR code images to authenticated users only. Hence, to grant access to any authenticated user to generated images, you can use this in your settings:

```python
from qr_code.qrcode import constants

QR_CODE_URL_PROTECTION = {
    constants.ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER: True
}
```

Setting the option `ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER` to a callable that always returns `True` (even for anonymous users) will allow anyone to access QR code image generation from outside your Django app. The following settings will grant access to anonymous users to generated images:

```python
from qr_code.qrcode import constants

QR_CODE_URL_PROTECTION = {
    constants.ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER: lambda u: True
}
```

Please note that, if your service is available on the Internet, allowing anyone to generate any kind of QR code via your Django application - as shown above - might generate a very heavy load on your server.

### QR Codes for Apps

Aside from generating a QR code from a given text, you can also generate codes for specific application purposes, that a reader can interpret as an action to take: open a mail client to send an e-mail to a given address, add a contact to your phone book, connect to a Wi-Fi, start a SMS, etc.  See [this documentation](https://github.com/zxing/zxing/wiki/Barcode-Contents) about what a QR code can encode.

Django QR Code proposes several utility tags to ease the generation of such codes, without having to build the appropriate text representation for each action you need. This remove the hassle of reading the specifications and handling all the required escaping for reserved chars.

Please note that some commands are common patterns, rather than formal specifications. Therefore, there is no guarantee that all QR code readers will handle them properly.

The following tags targeting apps are available:
* `qr_for_email` and `qr_url_for_email`
* `qr_for_tel` and `qr_url_for_tel`
* `qr_for_sms` and `qr_url_for_sms`
* `qr_for_geolocation` and `qr_url_for_geolocation`
* `qr_for_google_maps` and `qr_url_for_google_maps`
* `qr_for_youtube` and `qr_url_for_youtube`
* `qr_for_google_play` and `qr_url_for_google_play`
* `qr_for_mecard` and `qr_url_for_mecard`
* `qr_for_vcard` and `qr_url_for_vcard`
* `qr_for_wifi` and `qr_url_for_wifi`
* `qr_for_epc` and `qr_url_for_epc`
* `qr_for_event` and `qr_url_for_event`
* `qr_for_contact` and `qr_url_for_contact` (legacy, do not use in new projects)

You could write a view like this:

```python
import datetime
from datetime import date
from django.shortcuts import render
from qr_code.qrcode.utils import MeCard, VCard, EpcData, VEvent, EventClass, EventTransparency, EventStatus, WifiConfig, Coordinates, QRCodeOptions


def application_qr_code_demo(request):
    # Use a MeCard instance to encapsulate the detail of the contact.
    mecard_contact = MeCard(
        name='Doe, John',
        phone='+41769998877',
        email='j.doe@company.com',
        url='http://www.company.com',
        birthday=date(year=1985, month=10, day=2),
        memo='Development Manager',
        org='Company Ltd'
    )

    # Use a VCard instance to encapsulate the detail of the contact.
    vcard_contact = VCard(
        name='Doe; John',
        phone='+41769998877',
        email='j.doe@company.com',
        url='http://www.company.com',
        birthday=date(year=1985, month=10, day=2),
        street='Cras des Fourches 987',
        city='Delémont',
        zipcode=2800,
        region='Jura',
        country='Switzerland',
        memo='Development Manager',
        org='Company Ltd'
    )

    # Use a WifiConfig instance to encapsulate the configuration of the connexion.
    wifi_config = WifiConfig(
        ssid='my-wifi',
        authentication=WifiConfig.AUTHENTICATION.WPA,
        password='wifi-password'
    )

    # Use a EpcData instance to encapsulate the data of the European Payments Council Quick Response Code.
    epc_data = EpcData(
        name='Wikimedia Foerdergesellschaft',
        iban='DE33100205000001194700',
        amount=50.0,
        text='To Wikipedia'
    )

    # Build coordinates instances.
    google_maps_coordinates = Coordinates(latitude=586000.32, longitude=250954.19)
    geolocation_coordinates = Coordinates(latitude=586000.32, longitude=250954.19, altitude=500)

    # Build event data (VEVENT properties)
    # NB for start and end of event:
    #   - Naive date and time is rendered as floating time.
    #   - Aware date and time is rendered as UTC converted time.
    event = VEvent(
        uid="some-event-id",
        summary="Vacations",
        start=datetime.datetime(2022, 8, 6, hour=8, minute=30),
        end=datetime.datetime(2022, 8, 17, hour=12),
        location="New-York, Statue de la Liberté",
        geo=(40.69216097988203, -74.04460073403436),
        categories=["PERSO", "holidays"],
        status=EventStatus.CONFIRMED,
        event_class=EventClass.PRIVATE,
        transparency=EventTransparency.OPAQUE,
        organizer="foo@bar.com",
        url="https://bar.com",
        description="""Fake description. Meeting to provide technical review for "Phoenix" design. Happy Face Conference Room.

Phoenix design team MUST attend this meeting.

RSVP to team leader."""
    )
    
    # Build context for rendering QR codes.
    context = dict(
        mecard_contact=mecard_contact,
        vcard_contact=vcard_contact,
        wifi_config=wifi_config,
        epc_data=epc_data,
        event=event,
        video_id='J9go2nj6b3M',
        google_maps_coordinates=google_maps_coordinates,
        geolocation_coordinates=geolocation_coordinates,
        options_example=QRCodeOptions(size='t', border=6, error_correction='L'),
    )

    # Render the index page.
    return render(request, 'my_app/application_qr_code_demo.html', context=context)
```

Then, in your template, you can render the appropriate QR codes for the given context:
```djangotemplate
<h3>Add contact '{{ mecard_contact.name }}' to phone book</h3>
{% qr_for_mecard mecard=mecard_contact size='S' %}
<p>or:</p>
{% qr_for_contact mecard_contact size='S' %}
<p>or:</p>
{% qr_for_contact mecard_contact options=options_example %}

<h3>Add contact '{{ vcard_contact.name }}' to phone book</h3>
{% qr_for_vcard vcard=vcard_contact size='S' %}
<p>or:</p>
{% qr_for_contact vcard_contact size='S' %}
<p>or:</p>
{% qr_for_contact vcard_contact options=options_example %}

<h3>Configure Wi-Fi connexion to '{{ wifi_config.ssid }}'</h3>
<img src="{% qr_url_for_wifi wifi_config=wifi_config size='T' error_correction='Q' %}">
<p>or:</p>
<img src="{% qr_url_for_wifi wifi_config size='T' error_correction='Q' %}">
<p>or:</p>
<img src="{% qr_url_for_wifi wifi_config options=options_example %}">

<h3>EPC QR Code'</h3>
<img src="{% qr_url_for_epc epc_data=epc_data %}">
<p>or:</p>
<img src="{% qr_url_for_epc epc_data size='H' %}">

<h3>Event QR Code'</h3>
<img src="{% qr_url_for_event event=event %}">
<p>or:</p>
{% qr_for_event event=event %}

<h3>Watch YouTube video '{{ video_id }}'</h3>
{% qr_for_youtube video_id image_format='png' size='T' %}
<p>or:</p>
{% qr_for_youtube video_id options=options_example %}

<h3>Open map at location: ({{ geolocation_coordinates }})</h3>
<img src="{% qr_url_for_geolocation coordinates=geolocation_coordinates %}">
<p>or:</p>
<img src="{% qr_url_for_geolocation latitude=geolocation_coordinates.latitude longitude=geolocation_coordinates.longitude altitude=geolocation_coordinates.altitude %}">
<p>or:</p>
<img src="{% qr_url_for_geolocation latitude=geolocation_coordinates.latitude longitude=geolocation_coordinates.longitude altitude=geolocation_coordinates.altitude options=options_example %}">

<h3>Open Google Maps App at location: ({{ google_maps_coordinates }})</h3>
{% qr_for_google_maps coordinates=google_maps_coordinates %}
<p>or:</p>
{% qr_for_google_maps latitude=google_maps_coordinates.latitude longitude=google_maps_coordinates.longitude %}
<p>or:</p>
{% qr_for_google_maps latitude=google_maps_coordinates.latitude longitude=google_maps_coordinates.longitude options=options_example %}
```

Please check out the [demo application](#demo-application) to see more examples.

## Notes

### Image Formats
The SVG is the default image format. It is a vector image format so it can be scaled up and down without quality loss. However, it has two drawbacks. The size is not given in pixel, which can be problematic if the design of your website relies on a fixed width (in pixels). The format is less compact than PNG and results in a larger HTML content. Note that a base64 PNG is less compressible than a SVG tag, so it might not matter that much of you use HTML compression on your web server.

SVG has [broad support](http://caniuse.com/#feat=svg) now, and it will work properly on any modern web browser.

### qr_from_text vs qr_url_from_text
The tag `qr_url_from_text` has several advantages over `qr_from_text`, despite the fact that it requires a bit more of writing:
* the generated HTML code does not contain heavy inline image data (lighter and cleaner content)
* the generated images can be cached (served with a separate HTML request)
* the HTML tag used to render the QR code is always an `<img>` tag, which may simplify CSS handling
* the HTML tag embedding the image is not generated for you, which allows for customization of attributes (*height*, *width*, *alt*)
* the page can be loaded asynchronously, which improves responsiveness
* you can provide links to QR codes instead of displaying them, which is not possible with `qr_from_text`

One disadvantage of `qr_url_from_text` is that it increases the number of requests to the server: one request to serve the page containing the URL and another to request the image.

Be aware that serving image files (which are generated on the fly) from a URL can be abused and lead to (D)DoS attack pretty easily, for instance by requesting very large QR codes from outside your application. This is the reason why the associated setting `ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER` in `QR_CODE_URL_PROTECTION` defaults to completely forbid external access to the API. Be careful when opening external access.

### QR Codes Caching
Caching QR codes reduces CPU usage, but the usage of `qr_url_from_text` (which caching depends on) increases the number of requests to the server (one request to serve the page containing the URL and another to request the image).

Moreover, be aware that the largest QR codes, in version 40 with a border of 4 modules and rendered in SVG format, have a size of ~800 KB.
Be sure that your cache options are reasonable and can be supported by your server(s), especially for in-memory caching.

Note that even without caching the generated QR codes, the app will return a *HTTP 304 Not Modified* status code whenever the same QR code is requested again. The URL named **`qr_code:serve_qr_code_image`** adds the `ETag` and `Last-Modified` headers to the response if the headers aren't already set, enabling  *HTTP 304 Not Modified* response upon following requests.

## Demo Application
If you want to try this app, you may want to use the demo application shipped alongside the source code.

Get the source code from [GitHub](https://github.com/dprog-philippe-docourt/django-qr-code), follow the [installation instructions](#from-the-source-code) above, and run the `runserver` command of Django:
```bash
python manage.py runserver
```
The demo application should be running at <http://127.0.0.1:8000/qr-code-demo/>.

If you have [Docker Compose](https://docs.docker.com/compose/) installed, you can simply run the following from a terminal (this will save you the burden of setting up a proper python environment):
```bash
cd scripts
./run-demo-app.sh
```
The demo application should be running at <http://127.0.0.1:8910/qr-code-demo/>.

## Testing
Get the source code from [GitHub](https://github.com/dprog-philippe-docourt/django-qr-code), follow the [installation instructions](#from-the-source-code) above, and run the `test` command of Django:
```bash
python manage.py test
```
This will run the test suite with the locally installed version of Python and Django.

If you have [Docker Compose](https://docs.docker.com/compose/) installed, you can simply run the following from a terminal (this will save you the burden of setting up a proper python environment):
```bash
cd scripts
./run-tests.sh
```
This will run the test suite with all supported versions of Python and Django. The test results are stored within `tests_result` folder.

## Projects Using this App

This app is used in the following projects:
* [MyGym Web](https://mygym-web.ch/): a web platform for managing sports clubs. The QR codes are used for importing members' contact information in a phone book.
* [Gymna-Score](https://gymna-score.acjg.ch/): a web platform for entering scores during gymnastics competitions organized by the Association Cantonale Jurassienne de Gymnastique (ACJG). The QR codes are used to provide an easy way for the public to follow an ongoing competition. They are also used to authenticate judges that need to enter scores.
* [AC-Ju](https://www.ac-ju.ch/): a website that generates digital vouchers that can be redeemed at affiliate merchants.


%prep
%autosetup -n django-qr-code-3.1.1

%build
%py3_build

%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
	find usr/lib -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
	find usr/lib64 -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
	find usr/bin -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
	find usr/sbin -type f -printf "/%h/%f\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
	find usr/share/man -type f -printf "/%h/%f.gz\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .

%files -n python3-django-qr-code -f filelist.lst
%dir %{python3_sitelib}/*

%files help -f doclist.lst
%{_docdir}/*

%changelog
* Tue Apr 11 2023 Python_Bot <Python_Bot@openeuler.org> - 3.1.1-1
- Package Spec generated