pax_global_header00006660000000000000000000000064140566420360014520gustar00rootroot0000000000000052 comment=9a51dba4a35e1b50a7db9fa59416d79b246e5607 django-qr-code-2.2.0/000077500000000000000000000000001405664203600143135ustar00rootroot00000000000000django-qr-code-2.2.0/.editorconfig000066400000000000000000000001741405664203600167720ustar00rootroot00000000000000root = true [*] indent_style = space indent_size = 4 insert_final_newline = true charset = utf-8 [*.html] indent_size = 2 django-qr-code-2.2.0/.gitignore000066400000000000000000000025711405664203600163100ustar00rootroot00000000000000# Generated data and logs during tests. tests_result/ tests_result.back/ # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover .hypothesis/ .pytest_cache/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv .python-version # celery beat schedule file celerybeat-schedule # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ django-qr-code-2.2.0/.travis.yml000066400000000000000000000006501405664203600164250ustar00rootroot00000000000000dist: bionic language: python python: - "3.6" - "3.7" - "3.8" - "3.9" env: - DJANGO_VERSION=2.2 - DJANGO_VERSION=3.1 - DJANGO_VERSION=3.2 # command to install dependencies install: - pip install django~=$DJANGO_VERSION - pip install -r requirements.txt - pip install python-coveralls coverage # command to run tests script: - coverage run --source='qr_code' manage.py test after_success: - coveralls django-qr-code-2.2.0/CHANGELOG.md000066400000000000000000000145431405664203600161330ustar00rootroot00000000000000# Change Log ## 2.2.0 (2021-06-03) * Change encoding from URL-safe Base64 to standard Base64 for `text` query argument (used for serving QR code images). * Fix #31 by passing the border parameter for segno.QRCode.save. * Ensure compatibility with Django 3.2. * Drop support for Django 3.0. ## 2.1.0 (2021-01-23) * Change encoding from URL-safe Base64 to standard Base64 for `text` query argument (used for serving QR code images). * Introduce setting `SERVE_QR_CODE_IMAGE_PATH` to configure the path under which QR Code images are served. * Reorganize and improve documentation. * Fix #23 * Introduce usage of type hints. ## 2.0.1 (2020-11-24) * Update the install_requires after the move from qrcode to Segno. ## 2.0.0 (2020-11-22) * Remove dependency on Pillow / qrcode * Switch to [Segno](https://pypi.org/project/segno/) for generating QR Codes * Add support for QR Codes with multiple colors * Add support for Micro QR Codes * Stable SVG format for QR code between 32-bit and 64-bit architecture (#19) * Use hyphens in URLs (#16) * Add support for Python 3.9 ## 1.3.1 (2020-09-07) * Fix local testing script. * Fix date of release 1.3.0 in readme. * Code cleanup. ## 1.3.0 (2020-09-05) * Drop support for Django 2.1. * Ensure compatibility with Django 3.1. ## 1.2.0 (2020-04-26) * Ensure compatibility with Django 3.0. * Upgrade Pillow requirement to 7.1. * Drop support for Python 3.5. * Drop support for Django <2.2. * More modern build environment and configuration for ReadTheDocs. ## 1.1.0 (2019-11-16) * Ensure compatibility with Django 2.1. * Ensure compatibility with Django 2.2. * Upgrade qr_code library from 5.3 to 6.1 (several fixes). * Drop support for Python 3.4. * Fixed error when generating qr code from lazy text. (#1) * Add support for customizing usage of URL signature token via template tags (allows to generate URLs for serving QR code images that do not include a signature token). (#4) * The caching of QR codes images could allow to bypass checking the user when external access is active. * Upgrade Pillow requirement to 6.2.0 (CVE-2019-16865). * Adopt a dedicated logger, and move message "Pillow is not installed. No support available for PNG format." from info to debug. (#6) ## 1.0.0 (2018-03-23) * BREAKING CHANGES: * QR code options have been factorized and now use the `QRCodeOptions` class. * The context for rendering a QR code encoding a Wi-Fi configuration uses the dedicated `WifiConfig` class. * The context for rendering a QR code encoding a contact detail uses the dedicated `ContactDetail` class. * `qr_for_contact` and `qr_url_for_contact` keyword arg has been renamed from `contact_dict` to `contact_detail`. * `qr_for_wifi` and `qr_url_for_wifi` keyword arg has been renamed from `wifi_dict` to `wifi_config`. * Reorganize code and split qr_code.py into several modules. The changes mentioned above might break the compatibility with code using qr_code.py's API directly, but template tags are not impacted, except for `qr_for_contact`, `qr_url_for_contact`, `qr_for_wifi`, and `qr_url_for_wifi` if they were using a keyword argument. * Other changes: * Added support for `error_correction` parameter when generating a QR code. * Added support for `coordinates` keyword argument to `qr_for_geolocation`, `qr_for_google_maps`, `qr_url_for_geolocation`, and `qr_url_for_google_maps`. * Additions to documentation. * Added ability to use a `QRCodeOptions` instance with `options` keyword argument in all tags. * Bug fixes: * Fixed non-closed tag when generating embedded PNG image. * Escape colon char (':') if it appears within a contact detail or a wifi configuration. * Add a second terminal semi-colon at the end of the text representing a wifi configuration, as recommended in some sources. ## 0.4.1 (2018-03-10) * Fixed unescaped chars when generating QR code for a contact. * Simplify handling of default values for QR code options. * Add documentation about what a QR code can encode. ## 0.4.0 (2018-03-09) * Added support for multiple new tags: * `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_contact` and `qr_url_for_contact` * `qr_for_wifi` and `qr_url_for_wifi` * Reformat documentation on the demo site for better readability. * Drop support for Django <1.11. ## 0.3.3 (2017-08-16) * Added `app_name` namespace to `qr_code.urls` (better compatibility with `include()` function provided with Django >= 1.9). * Update documentation regarding the inclusion of `qr_code.urls` for distinct versions of Django. * Minor improvements to the documentation. ## 0.3.2 (2017-08-13) * Allows optional installation of Pillow (PNG format unavailable, fallback to SVG). * Fixed caching of images (not working due protection against external queries). * Fixed conditional view processing (HTTP 304) for rendered QR codes (not working due protection against external queries). ## 0.3.1 (2017-08-12) * Added a mention about Pillow library requirement in documentation. * Minor improvements to the documentation and the demo application. ## 0.3.0 (2017-08-12) * Added new tag qr_url_from_text: * Separate image from the page displaying the image * Handle caching of images * Conditional view processing (HTTP 304) for rendered QR codes * Protection against external requests * Settings to configure URLs accesses as a service for generating QR code images * Add documentation for new features * Add tests for new features * Add examples to demo site * More robust testing of make_embedded_qr_code's arguments. * Improved documentation. * Demo site is compatible with Django 1.8. * Added support for Docker Compose for running the demo application and running the tests. ## 0.2.1 (2017-08-05) * Added support for Django 1.8. * Fixed version specifiers for Django requirement so that it wont force the installation of Django 1.11. * Added badges for PyPi, Read the Docs and Travis CI to readme file. * Several additions to the documentation. ## 0.2.0 (2017-08-04) * Add support for PNG image format via an `img` tag. * Add documentation for users and developers. * Improve examples in demo app. ## 0.1.1 (2017-08-02) First public release. django-qr-code-2.2.0/Dockerfile000066400000000000000000000020501405664203600163020ustar00rootroot00000000000000ARG PYTHON_VERSION FROM python:${PYTHON_VERSION} LABEL vendor="dProg - Philippe Docourt" maintainer="Philippe Docourt" description="Demo Site for Django QR code" ENV PYTHONUNBUFFERED 1 # Avoid possible occurrences of UnicodeEncodeError when running on x86 architecture. ENV PYTHONIOENCODING utf-8 # Set env variables used in this Dockerfile (add a unique prefix, such as ) # Directory in container for project source files. ARG APP_BASE_DIR=/usr/src/app # Declare a proper Django settings file. ENV DJANGO_SETTINGS_MODULE=demo_site.settings # Make app dir. RUN mkdir -p "$APP_BASE_DIR" WORKDIR "$APP_BASE_DIR" # Install requirements (separate step for caching intermediate image). COPY requirements.txt "$APP_BASE_DIR/" RUN pip install -r requirements.txt COPY requirements-web-deployment.txt "$APP_BASE_DIR/" RUN pip install -r requirements-web-deployment.txt # Copy entrypoint script into the image. COPY ./docker-entrypoint.sh / # Invoke app's entrypoint via dumb-init so that sub-processes are handled properly. CMD ["/docker-entrypoint.sh"] django-qr-code-2.2.0/LICENSE000066400000000000000000000027711405664203600153270ustar00rootroot00000000000000BSD 3-Clause License Copyright (c) 2017-2018, dProg - Philippe Docourt All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. django-qr-code-2.2.0/MANIFEST.in000066400000000000000000000000671405664203600160540ustar00rootroot00000000000000include README.md include LICENSE include CHANGELOG.md django-qr-code-2.2.0/README.md000066400000000000000000000551341405664203600156020ustar00rootroot00000000000000# 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://travis-ci.com/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.6 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 follow: * 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 Alternatively, you may use the `options` keyword argument with an instance of `QRCodeOptions` as value instead of listing every requested options. Here is a 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 Hello World! ``` Here is a "hello world" QR code in version 10 that uses an URL to serve the image in PNG format: ```djangotemplate 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 optionnal 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 `/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/' ``` ### 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 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 adressed 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`. 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 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_contact` and `qr_url_for_contact` * `qr_for_wifi` and `qr_url_for_wifi` You could write a view like this: ```python from datetime import date from django.shortcuts import render from qr_code.qrcode.utils import ContactDetail, WifiConfig, Coordinates, QRCodeOptions def application_qr_code_demo(request): # Use a ContactDetail instance to encapsulate the detail of the contact. contact_detail = ContactDetail( first_name='John', last_name='Doe', first_name_reading='jAAn', last_name_reading='dOH', tel='+41769998877', email='j.doe@company.com', url='http://www.company.com', birthday=date(year=1985, month=10, day=2), address='Cras des Fourches 987, 2800 Delémont, Jura, 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' ) # 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 context for rendering QR codes. context = dict( contact_detail=contact_detail, wifi_config=wifi_config, 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

Add contact '{{ contact_detail.first_name }} {{ contact_detail.last_name }}' to phone book

{% qr_for_contact contact_detail=contact_detail size='S' %}

or:

{% qr_for_contact contact_detail size='S' %}

or:

{% qr_for_contact contact_detail options=options_example %}

Configure Wi-Fi connexion to '{{ wifi_config.ssid }}'

or:

or:

Watch YouTube video '{{ video_id }}'

{% qr_for_youtube video_id image_format='png' size='T' %}

or:

{% qr_for_youtube video_id options=options_example %}

Open map at location: ({{ geolocation_coordinates }})

or:

or:

Open Google Maps App at location: ({{ google_maps_coordinates }})

{% qr_for_google_maps coordinates=google_maps_coordinates %}

or:

{% qr_for_google_maps latitude=google_maps_coordinates.latitude longitude=google_maps_coordinates.longitude %}

or:

{% 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 `` 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 . 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 . ## 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. django-qr-code-2.2.0/demo_site/000077500000000000000000000000001405664203600162635ustar00rootroot00000000000000django-qr-code-2.2.0/demo_site/__init__.py000066400000000000000000000000001405664203600203620ustar00rootroot00000000000000django-qr-code-2.2.0/demo_site/settings.py000066400000000000000000000100331405664203600204720ustar00rootroot00000000000000""" Django settings for qr_code_demo project. Generated by 'django-admin startproject' using Django 2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os from distutils.version import StrictVersion import django # Build paths inside the project like this: os.path.join(BASE_DIR, ...) from qr_code.qrcode import constants BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '8l4)()f1&tg*dtxh6whlew#k-d5&79npe#j_dg9l0b)m8^g#8u' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.staticfiles', 'qr_code', 'qr_code_demo' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'demo_site.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'demo_site.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # Caches. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', }, 'qr-code': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'qr-code-cache', 'TIMEOUT': 3600 } } # Django QR Code specific options. QR_CODE_CACHE_ALIAS = 'qr-code' 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: lambda u: 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 security token). } SERVE_QR_CODE_IMAGE_PATH = 'qr-code-image/' django-qr-code-2.2.0/demo_site/urls.py000066400000000000000000000005431405664203600176240ustar00rootroot00000000000000from django.conf.urls import include from django.urls import path from django.views.generic import RedirectView urlpatterns = [ path('', RedirectView.as_view(url='qr-code-demo/', permanent=True)), path('qr-code-demo/', include('qr_code_demo.urls', namespace='qr_code_demo')), path('qr-code/', include('qr_code.urls', namespace='qr_code')), ] django-qr-code-2.2.0/demo_site/wsgi.py000066400000000000000000000006221405664203600176060ustar00rootroot00000000000000""" WSGI config for qr_code_demo project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "qr_code_demo.settings") application = get_wsgi_application() django-qr-code-2.2.0/docker-compose.yml000066400000000000000000000004171405664203600177520ustar00rootroot00000000000000version: '3.7' services: django-qr-code: build: context: . dockerfile: Dockerfile args: - PYTHON_VERSION volumes: - ./:/usr/src/app environment: - APP_PORT=8910 expose: - "8910" ports: - "8910:8910" django-qr-code-2.2.0/docker-entrypoint.sh000077500000000000000000000010611405664203600203300ustar00rootroot00000000000000#!/bin/bash echo APP_PORT=$APP_PORT echo DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE # Collect static files first. python3 manage.py collectstatic --noinput echo --- Start Gunicorn processes and replace the shell [i.e. invoke gunicorn with exec] echo Starting Gunicorn. exec gunicorn demo_site.wsgi:application \ --name django-qr-code \ --bind 0.0.0.0:$APP_PORT \ --workers 2 \ --worker-class=gthread \ --log-level=info \ --log-file=- \ --access-logfile=- \ --env DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE \ "$@" django-qr-code-2.2.0/docs/000077500000000000000000000000001405664203600152435ustar00rootroot00000000000000django-qr-code-2.2.0/docs/Makefile000066400000000000000000000011441405664203600167030ustar00rootroot00000000000000# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = python -msphinx SPHINXPROJ = DjangoQRcode SOURCEDIR = . BUILDDIR = _build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)django-qr-code-2.2.0/docs/_static/000077500000000000000000000000001405664203600166715ustar00rootroot00000000000000django-qr-code-2.2.0/docs/_static/colors/000077500000000000000000000000001405664203600201725ustar00rootroot00000000000000django-qr-code-2.2.0/docs/_static/colors/alignment_dark.png000066400000000000000000000012251405664203600236570ustar00rootroot00000000000000PNG  IHDR PLTE ,?GIDATxZY@ sG]ҧy)[?C34R#/qYs~33>sYǮ7ahfc:xe3OUʺMC<\] C "nT] "\g݋ˇZ!.C6Re^q0Ʌ][^5hMA5K9=m-@!2a "]Bud0*6k0 tD "Qr4+Q.ie'ծe ?x\{?dˇՎ8[*Ү>:-5z.֫0xË|Rqt#fcCLʇaj(*a!\@}({ս^U8xz|2sձ_gXڸΣ7m`8]yvnަݡvnh!7pj?|?焛dW~:~«X!.%s CU/Ce5UihAӽTT^&9L2Ay Qx -!a~( yPm(_a7A%iWU6dWZa$zOfA~qB-KP\~#-zKI?-xpb4WjV(~CR^ yz\ WI˅0 Y<Ŋ|2xF欇ć*€PaH!P*I%yxIP@\Vy@Z?b;aZFQI@TL6e~ G:N}VxGg>:Oة Юx۔e4|iŗ Q=<>\;^K=uwWo)MIENDB`django-qr-code-2.2.0/docs/_static/colors/dark.png000066400000000000000000000011121405664203600216140ustar00rootroot00000000000000PNG  IHDR[PLTEIDATxAj@ CM/R7p䡋B7- M~>d1%Y' {3,>x5\%/UoBXR^ƓRVmCf.[ţߎ(>96J*ȧBgTN(߆@g[ Adh~0 E$ {+.L7=7ȿqJDY^çK N.g`S|ZdP0Cn5B2vN?6[M L~U.z27I}ճG{O%:XKt>!}.;=]ũ7׺>h2-4Lu3o&Z;!ǹvҟ՗ jfIj퓂)(v+od[o{لz)$s`?xK@*~t_#}Z5 |1G} EMIENDB`django-qr-code-2.2.0/docs/_static/colors/dark_module.png000066400000000000000000000011701405664203600231650ustar00rootroot00000000000000PNG  IHDR PLTE ,?*IDATxZj1 +Grƒ|1.ʵےW^uWvfL|驏xe窧]HF+[g0g0a@UTBrdS[Fnš/ǬQaP rr^kNu)+ɘoKJw+'!>ϕj]9}R2^Ŋ;^jmz#է@QC *x .7| IKݗ2^CuRE1'ѡRuu#sClCaj(0L`=q,D>iKP/I KvKPðJ+Dz F`x p#$~X*_D쩨e_$zUѾ)ۯ#T}Xy Lq>aSA]xD00E`N+ ܆>ӇkNj\i} ^uU'IE4IENDB`django-qr-code-2.2.0/docs/_static/colors/data_dark.png000066400000000000000000000012631405664203600226140ustar00rootroot00000000000000PNG  IHDR PLTE ,?eIDATxZJ@ dڦ ""B`'{,MnlxWU?]r//mûsU=s= ^w f ,/wkõ^;2ݮ2;*.wj=N{+2븂"6FI_ӓЊfזFXtU+ (|kg$6k ᎨB[Ce|+;0`׽[E&dM: HUFwHIt k13i9bv79ٱkcǔnppK7''ʡ WZJW&R_PC~aLI:X uֿ|nG"GHN<,Q˱`]`֗KIqYzO̓kȝXެ/_^(ą4v#^9GAvQz~TX!f|hKvhH}0_.즛_ t*W]1!㞆0cGL;Vz#+z  LfK4R33_k?E+!fsŠW-i~ejP3?|@zٱe|rp:3}~RQC7δW6롇#v;fچy YU)'zIENDB`django-qr-code-2.2.0/docs/_static/colors/finder_dark.png000066400000000000000000000012111405664203600231430ustar00rootroot00000000000000PNG  IHDR PLTE ,?;IDATxZJP {|֦;wn̵MnYzvt׹ԻOZבz|%/\o\߸|1>+8ƨp]B-N ^ qAi8:rXy[`}5~C/X8]iA@c|LWxUiiqb ʹ2TUBū3a 6D pY&BwH%N!4gS_h򘢂9{F$bEZ1󾪹AnPv> nw%,(!>qZ/qpa.bN@IX~#ZY. K3}5(lk I y~|eby:b9ʈ 7;7S(>& G3jbQF3ŋ&=ΚG(41b#og3 5+L 0V1ڔS(ޘCמ['w=pzL=aKA .x3d }~cd{tW_mpp+̴y ]q(}xEIENDB`django-qr-code-2.2.0/docs/_static/colors/finder_light.png000066400000000000000000000012011405664203600233300ustar00rootroot00000000000000PNG  IHDR PLTE ,?3IDATxZj@ >WMlKna2d%%ٗǽ^u*\u񼚧.\p~^TǫA1,T3BVE;;9!WE o T_4f/ppE ;Z]g%)68UQ:xQG,ZPJ oGU_䡢9{fID`eI%AnPv? 8J^,(!^J-q0]n#aIw|V. k飬Aa_XHe$q1p%j\>LN-tL8ްz{rD0` E<7"J5T/HKH;kDsi| Fߠx5 5 x,UL6ek _$M<m|_ip=pE-4d ~C2fs=:ͫ/k};<>\;^tL;PU?] b)J" IENDB`django-qr-code-2.2.0/docs/_static/colors/format_dark.png000066400000000000000000000012051405664203600231670ustar00rootroot00000000000000PNG  IHDR PLTE ,?7IDATxZ0 +G}ү%ǁIvr'zf=~; |zx:>s֊kp@3&׏N?ו!4+@*8f.0^_qVbfW8lKkCL\Ň7jzvOHZ_ \h1j+Ž\XLiD|QeD El)ChC;\kaU0I5L`{KIWƓN.fA80\B-, } tubi~c磬@vV| Ia>F7Õpa\CqbEl`8ްfcCLCah(0$`98"PJE*WHKfK;Ds0\cvXP~ǫVW*7bj5)cûTHR'QTe훰J;P@EP0 0>CoHƬ0[y ߆y'ǎWr_)g3Og}CKIENDB`django-qr-code-2.2.0/docs/_static/colors/format_light.png000066400000000000000000000011761405664203600233640ustar00rootroot00000000000000PNG  IHDR PLTE ,?0IDATxZj@ ^ymw,[8rK@mI'yV=U {Lw}Oꅋ?ϰ~zlb8p>\N7] J(\!.CuEOu|(VŋQi-u(u> gU_x}V_P>±h5y8Gh>sWR]T_reKJ"Zn!Uu:e~C(H\&i{98ݥPq t%DbVXo?RC'wh.,] ( k[/roDxM|T4(D}C.#| %Fõq2]&֣#b.^#d:*7oZM& XO"xeŋ!=G(141O;"```x=  x#,Ul6es _=]A!oVP\ORP{sH7,c1أӾ?!õT.ϴ y Y~9A:>+IENDB`django-qr-code-2.2.0/docs/_static/colors/light.png000066400000000000000000000011071405664203600220060ustar00rootroot00000000000000PNG  IHDR[PLTEIDATxKj#@ D\K@+5"jHvgfڏ۳*U ?Ir[juo"xoW7t*;?DE?ᙟR-Q:Bh=>oh`?}+d;;ַp-xԫtAKeu"O mNA?7ۓ _cĐӯ\?ui诓~=>Ny;&ZI$~Ѥ\$h~Fltʩ.sz{Es͇#?& #P0d.D݁.S/ss@sd)c5s"Cr)g7CϫR1ǵvr?&goTL,A0XlA!(ܜt]F k׋KѸC0zu3s\|į,^{KH* ni˨e>Cn⪐J'IENDB`django-qr-code-2.2.0/docs/_static/colors/mqr_alignment_dark.png000066400000000000000000000003301405664203600245320ustar00rootroot00000000000000PNG  IHDRTTaR PLTE ,?IDATxՕ1 x+Bqf =)"Ystri?کޜvѫcBqP,UL|'CPs馬,f07׫3o6Nz"|E*JЯi #/tIENDB`django-qr-code-2.2.0/docs/_static/colors/mqr_alignment_light.png000066400000000000000000000003301405664203600247200ustar00rootroot00000000000000PNG  IHDRTTaR PLTE ,?IDATxՕ1 x+Bqf =)"Ystri?کޜvѫcBqP,UL|'CPs馬,f07׫3o6Nz"|E*JЯi #/tIENDB`django-qr-code-2.2.0/docs/_static/colors/mqr_dark.png000066400000000000000000000003071405664203600225000ustar00rootroot00000000000000PNG  IHDRTT&PLTE|IDATxڵ 1 /dR䫗H ϶ f|C#V{Hoqcl''\xͨGIUofv{e? Oy[89}F˚*IENDB`django-qr-code-2.2.0/docs/_static/colors/mqr_dark_module.png000066400000000000000000000003301405664203600240410ustar00rootroot00000000000000PNG  IHDRTTaR PLTE ,?IDATxՕ1 x+Bqf =)"Ystri?کޜvѫcBqP,UL|'CPs馬,f07׫3o6Nz"|E*JЯi #/tIENDB`django-qr-code-2.2.0/docs/_static/colors/mqr_data_dark.png000066400000000000000000000003331405664203600234700ustar00rootroot00000000000000PNG  IHDRTTaR PLTE ,?IDATxՕ10QO&ȒUjR.USٗCez2]ܸ`Ժ J0˕^+·ڇx!ܪH k0z-+ jE E;l)W7բz]J_n^czf,IENDB`django-qr-code-2.2.0/docs/_static/colors/mqr_data_light.png000066400000000000000000000003361405664203600236610ustar00rootroot00000000000000PNG  IHDRTTaR PLTE ,?IDATxՕA 0 +mi"lA#Ba\D—TsŅ]&0xMظv`q */~FsÝŔ Xq啫c[R,$ؖWfcf{W V֚o9\îIENDB`django-qr-code-2.2.0/docs/_static/colors/mqr_finder_dark.png000066400000000000000000000003311405664203600240240ustar00rootroot00000000000000PNG  IHDRTTaR PLTE ,?IDATxՕ90 -+I|ѤA)Űۊ˷㗝ͭwX?;oeA顸[8=7ۥ sTͪw58:7<<<{1 oBEVZ4'޷_C7V:wIENDB`django-qr-code-2.2.0/docs/_static/colors/mqr_finder_light.png000066400000000000000000000003311405664203600242120ustar00rootroot00000000000000PNG  IHDRTTaR PLTE ,?IDATxՕA O9h5p6CQO_^MUx7s#m,EL҃ʋCCv za9/ݧsS~ugvS~Kt.n6ЯArQ՟J0oF/C7琏dQIENDB`django-qr-code-2.2.0/docs/_static/colors/mqr_format_dark.png000066400000000000000000000003331405664203600240470ustar00rootroot00000000000000PNG  IHDRTTaR PLTE ,?IDATxՕA '-pb2]" [iT˳rչjOfvTMc ڭT! C6Fi9š?;~1ݽ[)̯|}  & [W -ky9t\% IENDB`django-qr-code-2.2.0/docs/_static/colors/mqr_format_light.png000066400000000000000000000003321405664203600242340ustar00rootroot00000000000000PNG  IHDRTTaR PLTE ,?IDATxՕ1 oc>W $3[h@f |*}y5NNIENDB`django-qr-code-2.2.0/docs/_static/colors/mqr_light.png000066400000000000000000000003021405664203600226610ustar00rootroot00000000000000PNG  IHDRTT&PLTEwIDATxڵ 0Q`-v&.raY#i݁DؓGz= 5Oj7zu8X[4V}% Uw^U|TU!zsyպ#?!.r(Cs+/p{;6ceՅ)֠Ps̬auA!(J/0ɄiD l)C _B D$}Vt(X|'azC(I\"Je{GsݥPR# n;+Yu͖ASf.3l.ŪE'`o^lb0lxmt-̱n0Hȸ2ߓ;l.sqHH˗՜D2x|#sK0>$| in/Q0,?I[́5@q~Q@>jD49jRg+L abڔ[*$'lTȂb-aƊ12_ ,1ppx'촃p=oQcIENDB`django-qr-code-2.2.0/docs/_static/colors/rain.png000066400000000000000000000003321405664203600216270ustar00rootroot00000000000000PNG  IHDRTTaR PLTEFIDATxՕ10 #OiCWbpXN_ K;=॔VEak wp9>܆ ^ )4cŸkZS߬`E[U K+|wEnݷ_C'@IENDB`django-qr-code-2.2.0/docs/_static/colors/separator.png000066400000000000000000000012061405664203600226770ustar00rootroot00000000000000PNG  IHDR PLTE ,?8IDATxZJP ;|MEM{ m;yV=U]{;_;o7|w\ub=tCIG?BvU +B|S ^ qaP8W+!l%&"?aWh}C[U_ D P8LWxUiƔr (J%@^Z&LF]CEsa~c"Gb}|o;' %ip-){!z<尼ԢK 򊝈.3L[wrp'HXRExıVi~c#י>I 4.71D݇2i5ܘi7^ovOS(>TG3Ąͣ4l ŋ&5G(kF1B73^B~iapNd#>̳9OKĶoW'x{0{z–@\4d ~C2fs=:ͫ/k5w8y|xѕK30|zVOH+LjIENDB`django-qr-code-2.2.0/docs/_static/colors/timing_dark.png000066400000000000000000000012101405664203600231620ustar00rootroot00000000000000PNG  IHDR PLTE ,?:IDATxZj0 Grk8@WJ@YVXϬg3뷳_ύLOYϛ_gq1xdÂSO":݄7 JC[r@\ZN'Np6+q|(VFuUX_Qe^+-(^?¡Y]PDnd/o덗X *^ E#aybڀ~+8Jv uX5Z1ӾZsQ5J'ẵ0މދYPbC\K-K‡O갹0.W*aI;Q. 0ݨ<e X8H0b7~yTe= }Ps\Ò!:*#7o|= eoD>T-QI^hE\2-,?ʭDSiԌ&@Ax 5 +fפqwEZ7q OF~`Pz=a@\xX2~!L4o}Yo"v/S`-xII$֯+g3Og})AMIENDB`django-qr-code-2.2.0/docs/_static/colors/timing_light.png000066400000000000000000000012071405664203600233560ustar00rootroot00000000000000PNG  IHDR PLTE ,?9IDATxZj@ ;IYӗR@tAmYe7ǺWݫU>J|.,bp/2a ";ZPuҎ\﹘r'KE$I& *^;0\/P!OEU_^V+_0Lo4%4+fڗ5{ IK,|.*v%Wfx`)Z2[V_a^X2r] JyGhcc̠p ` I}yC% ZΏ!oj5}X_~P iEGl9GA8z ˅.LL4*w3k`9ymT& v<Ƅ6Qz5]0ƆL^Bg+&CR1M)4IԾ+5U&l^(=PՓ X!V$=2P9ˌoC|'ǎWyL;oݫU 9.AIENDB`django-qr-code-2.2.0/docs/_static/colors/version_dark.png000066400000000000000000000012001405664203600233570ustar00rootroot00000000000000PNG  IHDR PLTE ,?2IDATxZ@ G}Rf,]8eY$M2Pa[=zV=U An\7'Os +J<8&׹d f\PF}|\TN'alTkWx1ޓXP|\ÐC}#+鑊V/NΆ3[p%mP%J Mk(h9BIH\BD$r]E!ٗ %\b{98ݥPq /DbVXo'Wu^!;4.V5_t[7? L>}T4(D}C.#| %Fõq2]&_GPs]GtUFoDdŵ!60` M)W1dQe~ApE +ZUgE)6(ȋY@&5D pY:BnJ~u Ed3<`>o(wUR(IKNwKѻ!?(, ?}rͅa\3%aI;xF. G> c!Ia>Pb~#mQpaLC5qRGl9'ӡVqa}#fzŇ݄c؄F=jŋ&&ͣ|hn= SpbAHOvф7ֹe:_#\XmňmSI;|J$yUۯGxz0y)8znc"l0GyeoCp>LJcNj\=ԯ)gճOW}/hZ,蟶//l *Gxv_Ut>X.DP5_]Rϟ{&3bO(טGU z<"cM8fWY( Z|ebLZSy+ ZsW[T՟agP쏋\y3J;|;C78g.Wza?;^vHB~OU?/ dIENDB`django-qr-code-2.2.0/docs/conf.py000066400000000000000000000154031405664203600165450ustar00rootroot00000000000000#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Django QR Code documentation build configuration file, created by # sphinx-quickstart on Wed Aug 2 22:36:45 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import re import sys sys.path.insert(0, os.path.abspath('../')) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'demo_site.settings') # Symlink CHANGELOG.md from repo root to the pages dir. basedir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) filenames = ['CHANGELOG.md', 'README.md'] for filename in filenames: target = os.path.join(basedir, 'docs', 'pages', filename) if not os.path.islink(target): os.symlink(os.path.join(basedir, filename), target) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.mathjax', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode', 'sphinx.ext.githubpages'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] # Allow markdown to be able to include the README.md, CHANGELOG.md, etc. from recommonmark.parser import CommonMarkParser source_parsers = { '.md': CommonMarkParser, } source_suffix = ['.rst', '.md'] # The master toctree document. master_doc = 'index' # General information about the project. project = 'Django QR Code' copyright = '2017-2020, Philippe Docourt' author = 'Philippe Docourt' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # Get version without importing with open('../qr_code/__init__.py', 'rb') as f: VERSION = str(re.search('__version__ = \'(.+?)\'', f.read().decode('utf-8')).group(1)) # The short X.Y version. version = VERSION # The full version, including alpha/beta/rc tags. release = VERSION # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # This is required for the alabaster theme # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars html_sidebars = { '**': [ 'about.html', 'navigation.html', 'relations.html', # needs 'show_related': True theme option to display 'searchbox.html', 'donate.html', ] } # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = 'DjangoQRCodedoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'DjangoQRCode.tex', 'Django QR Code Documentation', 'Philippe Docourt', 'manual'), ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'djangoqrcode', 'Django QR Code Documentation', [author], 1) ] # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'DjangoQRCode', 'Django QR Code Documentation', author, 'DjangoQRCode', 'An application that provides tools for displaying QR codes on your Django site.', 'Miscellaneous'), ] # -- Options for Epub output ---------------------------------------------- # Bibliographic Dublin Core info. epub_title = project epub_author = author epub_publisher = author epub_copyright = copyright # The unique identifier of the text. This can be a ISBN number # or the project homepage. # # epub_identifier = '' # A unique identification for the text. # # epub_uid = '' # A list of files that should not be packed into the epub file. epub_exclude_files = ['search.html'] # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'https://docs.python.org/': None} django-qr-code-2.2.0/docs/index.rst000066400000000000000000000010311405664203600170770ustar00rootroot00000000000000.. Django QR code documentation master file, created by sphinx-quickstart on Wed Aug 2 22:36:45 2017. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Welcome to Django QR Code's documentation! ========================================== .. toctree:: :maxdepth: 2 :caption: Contents: pages/README.md pages/module-colors pages/api pages/CHANGELOG.md Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` django-qr-code-2.2.0/docs/make.bat000066400000000000000000000014521405664203600166520ustar00rootroot00000000000000@ECHO OFF pushd %~dp0 REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=python -msphinx ) set SOURCEDIR=. set BUILDDIR=_build set SPHINXPROJ=DjangoQRcode if "%1" == "" goto help %SPHINXBUILD% >NUL 2>NUL if errorlevel 9009 ( echo. echo.The Sphinx module was not found. Make sure you have Sphinx installed, echo.then set the SPHINXBUILD environment variable to point to the full echo.path of the 'sphinx-build' executable. Alternatively you may add the echo.Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% goto end :help %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% :end popd django-qr-code-2.2.0/docs/pages/000077500000000000000000000000001405664203600163425ustar00rootroot00000000000000django-qr-code-2.2.0/docs/pages/api.rst000066400000000000000000000006331405664203600176470ustar00rootroot00000000000000API Reference ============= qrcode.maker ------- .. automodule:: qr_code.qrcode.maker :members: qrcode.serve ------- .. automodule:: qr_code.qrcode.serve :members: qrcode.utils ------- .. automodule:: qr_code.qrcode.utils :members: templatetags.qr_code -------------------- .. automodule:: qr_code.templatetags.qr_code :members: tests ----- .. automodule:: qr_code.tests :members: django-qr-code-2.2.0/docs/pages/module-colors.rst000066400000000000000000000150431405664203600216630ustar00rootroot00000000000000Module Colors ============= By default the QR codes are rendered in black and white but this project supports individual colors for each QR Code module type, i.e. the alignment and finder patterns may use another color than the data modules. The color values can be provided as tuple ``(R, G, B)``, as web color name (like 'red') or as hexadecimal ``#RRGGBB`` value (i.e. '#085A75'). The value ``None`` is used to indicate transparency, i.e. ``light_color=None`` indicates that all light modules should be transparent. .. code-block:: {% qr_from_text "Yellow Submarine" dark_color="darkred" data_dark="darkorange" data_light="yellow" %} .. image:: ../_static/colors/yellow-submarine.png :alt: Colorful 7-H QR code encoding "Yellow Submarine" .. code-block:: {% qr_from_text "Rain" dark_color="darkblue" data_dark="steelblue" micro=True %} .. image:: ../_static/colors/rain.png :alt: Colorful M4-Q QR code encoding "RAIN" Module names ------------ The following examples show the results of all supported module types. The unaffected modules are rendered as grey or white modules, the red modules show the result of the keyword. dark_color ~~~~~~~~~~ Sets the (default) color of dark modules. .. image:: ../_static/colors/dark.png :alt: Picture showing the dark modules .. image:: ../_static/colors/mqr_dark.png :alt: Picture showing the dark modules of a Micro QR code light_color ~~~~~~~~~~~ Sets the (default) color of light modules. .. image:: ../_static/colors/light.png :alt: Picture showing the light modules .. image:: ../_static/colors/mqr_light.png :alt: Picture showing the light modules of a Micro QR code alignment_dark_color ~~~~~~~~~~~~~~~~~~~~ Sets the color of the dark alignment pattern modules. Micro QR Codes don't have alignment patterns. .. image:: ../_static/colors/alignment_dark.png :alt: Picture showing the dark alignment modules .. image:: ../_static/colors/mqr_alignment_dark.png :alt: Picture showing the dark alignment modules of a Micro QR code (none) alignment_light_color ~~~~~~~~~~~~~~~~~~~~~ Sets the color of the light alignment pattern modules. Micro QR Codes don't have alignment patterns. .. image:: ../_static/colors/alignment_light.png :alt: Picture showing the light alignment modules .. image:: ../_static/colors/mqr_alignment_light.png :alt: Picture showing the light alignment modules of a Micro QR code (none) dark_module_color ~~~~~~~~~~~~~~~~~ Sets the color of the dark module. Micro QR Codes don't have a dark module. .. image:: ../_static/colors/dark_module.png :alt: Picture showing the dark modules .. image:: ../_static/colors/mqr_dark_module.png :alt: Picture showing the dark modules of a Micro QR code (none) data_dark_color ~~~~~~~~~~~~~~~ Sets the color of the dark data modules. .. image:: ../_static/colors/data_dark.png :alt: Picture showing the dark data modules .. image:: ../_static/colors/mqr_data_dark.png :alt: Picture showing the dark data modules of a Micro QR code data_light_color ~~~~~~~~~~~~~~~~ Sets the color of the light data modules. .. image:: ../_static/colors/data_light.png :alt: Picture showing the light modules .. image:: ../_static/colors/mqr_data_light.png :alt: Picture showing the light modules of a Micro QR code finder_dark_color ~~~~~~~~~~~~~~~~~ Sets the color of the dark modules of the finder pattern. .. image:: ../_static/colors/finder_dark.png :alt: Picture showing the dark finder modules .. image:: ../_static/colors/mqr_finder_dark.png :alt: Picture showing the dark finder modules of a Micro QR code finder_light_color ~~~~~~~~~~~~~~~~~~ Sets the color of the light modules of the finder pattern. .. image:: ../_static/colors/finder_light.png :alt: Picture showing the light finder modules .. image:: ../_static/colors/mqr_finder_light.png :alt: Picture showing the light finder modules of a Micro QR code format_dark_color ~~~~~~~~~~~~~~~~~ Sets the color of the dark modules of the format information. .. image:: ../_static/colors/format_dark.png :alt: Picture showing the dark format information modules .. image:: ../_static/colors/mqr_format_dark.png :alt: Picture showing the dark format information modules of a Micro QR code (none) format_light_color ~~~~~~~~~~~~~~~~~~ Sets the color of the light modules of the format information. .. image:: ../_static/colors/format_light.png :alt: Picture showing the light format information modules .. image:: ../_static/colors/mqr_format_light.png :alt: Picture showing the light format information modules of a Micro QR code (none) quiet_zone_color ~~~~~~~~~~~~~~~~ Sets the color of the quiet zone. .. image:: ../_static/colors/quiet_zone.png :alt: Picture showing the quiet zone .. image:: ../_static/colors/mqr_quiet_zone.png :alt: Picture showing the quiet zone of a Micro QR code separator_color ~~~~~~~~~~~~~~~ Sets the color of the separator. .. image:: ../_static/colors/separator.png :alt: Picture showing the separator .. image:: ../_static/colors/mqr_separator.png :alt: Picture showing the separator of a Micro QR code timing_dark_color ~~~~~~~~~~~~~~~~~ Sets the color of the dark modules of the timing pattern. .. image:: ../_static/colors/timing_dark.png :alt: Picture showing the dark timing pattern modules .. image:: ../_static/colors/mqr_timing_dark.png :alt: Picture showing the dark timing pattern modules of a Micro QR code timing_light_color ~~~~~~~~~~~~~~~~~~ Sets the color of the light modules of the timing pattern. .. image:: ../_static/colors/timing_light.png :alt: Picture showing the light timing pattern modules .. image:: ../_static/colors/mqr_timing_light.png :alt: Picture showing the light timing pattern modules of a Micro QR code version_dark_color ~~~~~~~~~~~~~~~~~~ Sets the color of the dark modules of the version information. Micro QR Codes and QR Codes lesser than version 7 don't carry any version information. .. image:: ../_static/colors/version_dark.png :alt: Picture showing the dark version modules .. image:: ../_static/colors/mqr_version_dark.png :alt: Picture showing the dark version modules of a Micro QR code (none) version_light_color ~~~~~~~~~~~~~~~~~~~ Sets the color of the light modules of the version information. Micro QR Codes and QR Codes lesser than version 7 don't carry any version information. .. image:: ../_static/colors/version_light.png :alt: Picture showing the light version modules .. image:: ../_static/colors/mqr_version_light.png :alt: Picture showing the light version modules of a Micro QR code (none) django-qr-code-2.2.0/docs/requirements.txt000066400000000000000000000000731405664203600205270ustar00rootroot00000000000000recommonmark sphinx sphinx-autobuild -r ../requirements.txtdjango-qr-code-2.2.0/manage.py000077500000000000000000000014471405664203600161260ustar00rootroot00000000000000#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo_site.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv) django-qr-code-2.2.0/qr_code/000077500000000000000000000000001405664203600157275ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code/__init__.py000066400000000000000000000000261405664203600200360ustar00rootroot00000000000000__version__ = '2.2.0' django-qr-code-2.2.0/qr_code/apps.py000066400000000000000000000001741405664203600172460ustar00rootroot00000000000000from django.apps import AppConfig class QrCodeConfig(AppConfig): name = 'qr_code' verbose_name = 'Django QR Code' django-qr-code-2.2.0/qr_code/qrcode/000077500000000000000000000000001405664203600172045ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code/qrcode/__init__.py000066400000000000000000000000001405664203600213030ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code/qrcode/constants.py000066400000000000000000000013561405664203600215770ustar00rootroot00000000000000from datetime import datetime from typing import Optional, Union QR_CODE_GENERATION_VERSION_DATE: datetime = datetime(year=2020, month=9, day=8, hour=12) SIZE_DICT: dict = {'t': 6, 's': 12, 'm': 18, 'l': 30, 'h': 48} ERROR_CORRECTION_DICT: dict = {'L': 'l', 'M': 'm', 'Q': 'q', 'H': 'h'} DEFAULT_MODULE_SIZE: Union[str, int] = 'm' DEFAULT_BORDER_SIZE: int = 4 DEFAULT_VERSION: Optional[int] = None DEFAULT_IMAGE_FORMAT: str = 'svg' DEFAULT_ERROR_CORRECTION: str = 'm' DEFAULT_CACHE_ENABLED: bool = True DEFAULT_URL_SIGNATURE_ENABLED: bool = True ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER: str = 'ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER' SIGNING_KEY: str = 'SIGNING_KEY' TOKEN_LENGTH: str = 'TOKEN_LENGTH' SIGNING_SALT: str = 'SIGNING_SALT' django-qr-code-2.2.0/qr_code/qrcode/maker.py000066400000000000000000000056721405664203600206670ustar00rootroot00000000000000"""Tools for generating QR codes. This module depends on the Segno library.""" import io from typing import Mapping, Any from django.utils.html import escape from django.utils.safestring import mark_safe import segno from qr_code.qrcode.constants import DEFAULT_CACHE_ENABLED, \ DEFAULT_URL_SIGNATURE_ENABLED from qr_code.qrcode.serve import make_qr_code_url from qr_code.qrcode.utils import QRCodeOptions def make_qr(text: Any, qr_code_options: QRCodeOptions): """Creates a QR code :rtype: segno.QRCode """ # WARNING: For compatibility reasons, we still allow to pass __proxy__ class (lazy string). Moreover, it would be OK to pass anything that has __str__ # attribute (e. g. class instance that handles phone numbers). return segno.make(str(text), **qr_code_options.kw_make()) def make_qr_code_image(text: Any, qr_code_options: QRCodeOptions) -> bytes: """ Returns a bytes object representing a QR code image for the provided text. :param str text: The text to encode :param qr_code_options: Options to create and serialize the QR code. :rtype: bytes """ qr = make_qr(text, qr_code_options) out = io.BytesIO() qr.save(out, **qr_code_options.kw_save()) return out.getvalue() def make_embedded_qr_code(text: Any, qr_code_options: QRCodeOptions) -> str: """ Generates a or tag representing the QR code for the given text. This tag can be embedded into an HTML document. """ qr = make_qr(text, qr_code_options) kw = qr_code_options.kw_save() # Pop the image format from the keywords since qr.png_data_uri / qr.svg_inline # set it automatically kw.pop('kind') if qr_code_options.image_format == 'png': return mark_safe('{1}' .format(qr.png_data_uri(**kw), escape(text))) return mark_safe(qr.svg_inline(**kw)) def make_qr_code_with_args(text: Any, qr_code_args: dict) -> str: options = _options_from_args(qr_code_args) return make_embedded_qr_code(text, options) def make_qr_code_url_with_args(text: Any, qr_code_args: dict) -> str: cache_enabled = qr_code_args.pop('cache_enabled', DEFAULT_CACHE_ENABLED) url_signature_enabled = qr_code_args.pop('url_signature_enabled', DEFAULT_URL_SIGNATURE_ENABLED) options = _options_from_args(qr_code_args) return make_qr_code_url(text, options, cache_enabled=cache_enabled, url_signature_enabled=url_signature_enabled) def _options_from_args(args: Mapping) -> QRCodeOptions: """Returns a QRCodeOptions instance from the provided arguments. """ options = args.get('options') if options: if not isinstance(options, QRCodeOptions): raise TypeError('The options argument must be of type QRCodeOptions.') else: # Convert the string "None" into None kw = {k: v if v != 'None' else None for k, v in args.items()} options = QRCodeOptions(**kw) return options django-qr-code-2.2.0/qr_code/qrcode/serve.py000066400000000000000000000144331405664203600207070ustar00rootroot00000000000000import base64 import urllib.parse from collections.abc import Mapping from datetime import datetime from typing import Optional, Union from django.conf import settings from django.contrib.auth.models import AnonymousUser, User from django.core.signing import Signer from django.urls import reverse from django.utils.crypto import get_random_string from django.utils.encoding import force_str from django.utils.safestring import mark_safe from qr_code.qrcode import constants from qr_code.qrcode.utils import QRCodeOptions def _get_default_url_protection_options() -> dict: return { constants.TOKEN_LENGTH: 20, constants.SIGNING_KEY: settings.SECRET_KEY, constants.SIGNING_SALT: 'qr_code_url_protection_salt', constants.ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER: False } def _get_url_protection_settings() -> Optional[Mapping]: if hasattr(settings, 'QR_CODE_URL_PROTECTION') and isinstance(settings.QR_CODE_URL_PROTECTION, Mapping): return settings.QR_CODE_URL_PROTECTION return None def _options_allow_external_request(url_protection_options: Mapping, user: Union[User, AnonymousUser, None]) -> bool: # Evaluate the callable if required. if callable(url_protection_options[constants.ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER]): allows_external_request = url_protection_options[constants.ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER](user or AnonymousUser()) elif url_protection_options[constants.ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER] is True: allows_external_request = user and user.pk and user.is_authenticated else: allows_external_request = False return allows_external_request def requires_url_protection_token(user: Union[User, AnonymousUser, None] = None) -> bool: return not _options_allow_external_request(get_url_protection_options(), user) def allows_external_request_from_user(user: Union[User, AnonymousUser, None] = None) -> bool: return _options_allow_external_request(get_url_protection_options(), user) def get_url_protection_options() -> dict: options = _get_default_url_protection_options() settings_options = _get_url_protection_settings() if settings_options is not None: options.update(settings.QR_CODE_URL_PROTECTION) return options def _make_random_token() -> str: url_protection_options = get_url_protection_options() return get_random_string(url_protection_options[constants.TOKEN_LENGTH]) _RANDOM_TOKEN = _make_random_token() def get_qr_url_protection_signed_token(qr_code_options: QRCodeOptions): """Generate a signed token to handle view protection.""" url_protection_options = get_url_protection_options() signer = Signer(key=url_protection_options[constants.SIGNING_KEY], salt=url_protection_options[constants.SIGNING_SALT]) token = signer.sign(get_qr_url_protection_token(qr_code_options, _RANDOM_TOKEN)) return token def get_qr_url_protection_token(qr_code_options, random_token): """ Generate a random token for the QR code image. The token contains image attributes so that a user cannot use a token provided somewhere on a website to generate bigger QR codes. The random_token part ensures that the signed token is not predictable. """ return '.'.join(list(map(str, (qr_code_options.size, qr_code_options.border, qr_code_options.version or '', qr_code_options.image_format, qr_code_options.error_correction, random_token)))) def qr_code_etag(request) -> str: return '"%s:%s:version_%s"' % (request.path, request.GET.urlencode(), constants.QR_CODE_GENERATION_VERSION_DATE.isoformat()) def qr_code_last_modified(_request) -> datetime: return constants.QR_CODE_GENERATION_VERSION_DATE def make_qr_code_url(text: str, qr_code_options: Optional[QRCodeOptions] = None, cache_enabled: Optional[bool] = None, url_signature_enabled: Optional[bool] = None) -> str: """Build an URL to a view that handle serving QR code image from the given parameters. Any invalid argument related to the size or the format of the image is silently converted into the default value for that argument. :param str text: Text to encode into a QR code :param QRCodeOptions qr_code_options: The rendering options for the QR code. :param bool cache_enabled: Allows to skip caching the QR code (when set to *False*) when caching has been enabled. :param bool url_signature_enabled: Tells whether the random token for protecting the URL against external requests is added to the returned URL. It defaults to *True*. """ qr_code_options = QRCodeOptions() if qr_code_options is None else qr_code_options if url_signature_enabled is None: url_signature_enabled = constants.DEFAULT_URL_SIGNATURE_ENABLED if cache_enabled is None: cache_enabled = constants.DEFAULT_CACHE_ENABLED encoded_text = str(base64.b64encode(bytes(force_str(text), encoding='utf-8')), encoding='utf-8') params = dict(text=encoded_text, cache_enabled=cache_enabled) # Only add non-default values to the params dict if qr_code_options.size != constants.DEFAULT_MODULE_SIZE: params['size'] = qr_code_options.size if qr_code_options.border != constants.DEFAULT_BORDER_SIZE: params['border'] = qr_code_options.border if qr_code_options.version != constants.DEFAULT_VERSION: params['version'] = qr_code_options.version if qr_code_options.image_format != constants.DEFAULT_IMAGE_FORMAT: params['image_format'] = qr_code_options.image_format if qr_code_options.error_correction != constants.DEFAULT_ERROR_CORRECTION: params['error_correction'] = qr_code_options.error_correction if qr_code_options.micro: params['micro'] = qr_code_options.micro params.update(qr_code_options.color_mapping()) path = reverse('qr_code:serve_qr_code_image') if url_signature_enabled: # Generate token to handle view protection. The token is added to the query arguments. It does not replace # existing plain text query arguments in order to allow usage of the URL as an API (without token since external # users cannot generate the signed token!). token = get_qr_url_protection_signed_token(qr_code_options) params['token'] = token url = '%s?%s' % (path, urllib.parse.urlencode(params)) return mark_safe(url) django-qr-code-2.2.0/qr_code/qrcode/utils.py000066400000000000000000000437001405664203600207220ustar00rootroot00000000000000"""Utility classes and functions for configuring and setting up the content and the look of a QR code.""" import decimal from collections import namedtuple from datetime import date from typing import Optional, Any, Union, Tuple from django.utils.html import escape from qr_code.qrcode.constants import DEFAULT_MODULE_SIZE, SIZE_DICT, \ DEFAULT_ERROR_CORRECTION, DEFAULT_IMAGE_FORMAT class QRCodeOptions: """ Represents the options used to create and draw a QR code. """ def __init__(self, *, size: Union[int, str] = DEFAULT_MODULE_SIZE, border: int = 4, version: Union[int, str, None] = None, image_format: str = 'svg', error_correction: str = DEFAULT_ERROR_CORRECTION, micro: bool = False, dark_color: Union[Tuple, str] = '#000', light_color: Union[Tuple, str] = '#fff', finder_dark_color: bool = False, finder_light_color: bool = False, data_dark_color: bool = False, data_light_color: bool = False, version_dark_color: bool = False, version_light_color: bool = False, format_dark_color: bool = False, format_light_color: bool = False, alignment_dark_color: bool = False, alignment_light_color: bool = False, timing_dark_color: bool = False, timing_light_color: bool = False, separator_color: bool = False, dark_module_color: bool = False, quiet_zone_color: bool = False) -> None: """ :param size: The size of the QR code as an integer or a string. Default is *'m'*. :type: str or int :param int border: The size of the border (blank space around the code). :param int version: The version of the QR code gives the size of the matrix. Default is *None* which mean automatic in order to avoid data overflow. :param str image_format: The graphics format used to render the QR code. It can be either *'svg'* or *'png'*. Default is *'svg'*. :param str error_correction: How much error correction that might be required to read the code. It can be either *'L'*, *'M'*, *'Q'*, or *'H'*. Default is *'M'*. :param bool micro: Indicates if a Micro QR Code should be created. Default: False :param dark_color: Color of the dark modules (default: black). The color can be provided as ``(R, G, B)`` tuple, as hexadecimal format (``#RGB``, ``#RRGGBB`` ``RRGGBBAA``), or web color name (i.e. ``red``). :param light_color: Color of the light modules (default: white). See `color` for valid values. If light is set to ``None`` the light modules will be transparent. :param finder_dark_color: Color of the dark finder modules (default: same as ``dark_color``) :param finder_light_color: Color of the light finder modules (default: same as ``light_color``) :param data_dark_color: Color of the dark data modules (default: same as ``dark_color``) :param data_light_color: Color of the light data modules (default: same as ``light_color``) :param version_dark_color: Color of the dark version modules (default: same as ``dark_color``) :param version_light_color: Color of the light version modules (default: same as ``light_color``) :param format_dark_color: Color of the dark format modules (default: same as ``dark_color``) :param format_light_color: Color of the light format modules (default: same as ``light_color``) :param alignment_dark_color: Color of the dark alignment modules (default: same as ``dark_color``) :param alignment_light_color: Color of the light alignment modules (default: same as ``light_color``) :param timing_dark_color: Color of the dark timing pattern modules (default: same as ``dark_color``) :param timing_light_color: Color of the light timing pattern modules (default: same as ``light_color``) :param separator_color: Color of the separator (default: same as ``light_color``) :param dark_module_color: Color of the dark module (default: same as ``dark_color``) :param quiet_zone_color: Color of the quiet zone modules (default: same as ``light_color``) 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 0.1 mm for SVG format. The *border* parameter controls how many modules thick the border should be (blank space around the code). The default is 4, which is the minimum according to the specs. 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. 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 follow: * 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 :raises: TypeError in case an unknown argument is given. """ self._size = size self._border = int(border) if _can_be_cast_to_int(version): version = int(version) # type: ignore if not 1 <= version <= 40: version = None elif version in ('m1', 'm2', 'm3', 'm4', 'M1', 'M2', 'M3', 'M4'): version = version.lower() # type: ignore # Set / change the micro setting otherwise Segno complains about # conflicting parameters micro = True else: version = None self._version = version if not isinstance(micro, bool): micro = micro == 'True' self._micro = micro try: error = error_correction.lower() self._error_correction = error if error in ('l', 'm', 'q', 'h') else DEFAULT_ERROR_CORRECTION except AttributeError: self._error_correction = DEFAULT_ERROR_CORRECTION try: image_format = image_format.lower() self._image_format = image_format if image_format in ('svg', 'png') else DEFAULT_IMAGE_FORMAT except AttributeError: self._image_format = DEFAULT_IMAGE_FORMAT self._colors = dict(dark_color=dark_color, light_color=light_color, finder_dark_color=finder_dark_color, finder_light_color=finder_light_color, data_dark_color=data_dark_color, data_light_color=data_light_color, version_dark_color=version_dark_color, version_light_color=version_light_color, format_dark_color=format_dark_color, format_light_color=format_light_color, alignment_dark_color=alignment_dark_color, alignment_light_color=alignment_light_color, timing_dark_color=timing_dark_color, timing_light_color=timing_light_color, separator_color=separator_color, dark_module_color=dark_module_color, quiet_zone_color=quiet_zone_color) def kw_make(self): """Internal method which returns a dict of parameters to create a QR code. :rtype: dict """ return dict(version=self._version, error=self._error_correction, micro=self._micro) def kw_save(self): """Internal method which returns a dict of parameters to save a QR code. :rtype: dict """ image_format = self._image_format kw = dict(border=self.border, kind=image_format, scale=self._size_as_int()) # Change the color mapping into the keywords Segno expects # (remove the "_color" suffix from the module names) kw.update({k[:-6]: v for k, v in self.color_mapping().items()}) if image_format == 'svg': kw['unit'] = 'mm' scale = decimal.Decimal(kw['scale']) / 10 kw['scale'] = scale return kw def color_mapping(self): """Internal method which returns the color mapping. Only non-default values are returned. :rtype: dict """ colors = {k: v for k, v in self._colors.items() if v is not False} # Remove common default "dark" and "light" values if colors.get('dark_color') in ('#000', '#000000', 'black'): del colors['dark_color'] if colors.get('light_color') in ('#fff', '#FFF', '#ffffff', '#FFFFFF', 'white'): del colors['light_color'] return colors def _size_as_int(self): """Returns the size as integer value. :rtype: int """ size = self._size if _can_be_cast_to_int(size): actual_size = int(size) if actual_size < 1: actual_size = SIZE_DICT[DEFAULT_MODULE_SIZE] elif isinstance(size, str): actual_size = SIZE_DICT.get(size.lower(), DEFAULT_MODULE_SIZE) else: actual_size = SIZE_DICT[DEFAULT_MODULE_SIZE] return actual_size @property def size(self): return self._size @property def border(self): return self._border @property def version(self): return self._version @property def image_format(self): return self._image_format @property def error_correction(self): return self._error_correction @property def micro(self): return self._micro def _can_be_cast_to_int(value: Any) -> bool: return isinstance(value, int) or (isinstance(value, str) and value.isdigit()) class ContactDetail: """ Represents the detail of a contact. The following fields are provided: * first_name * last_name * first_name_reading: the sound of the first name. * last_name_reading: the sound of the last name. * tel: the phone number, it can appear multiple times. * tel_av: the video-phone number, it can appear multiple times. * email: the email address, it can appear multiple times. * memo: notes. * birthday: the birth date (Python date). * address: the fields divided by commas (,) denote PO box, room number, house number, city, prefecture, zip code and country, in order. * url: homepage URL. * nickname: display name. * org: organization or company name (non-standard,but often recognized, ORG field). """ def __init__(self, first_name: Optional[str] = None, last_name: Optional[str] = None, first_name_reading: Optional[str] = None, last_name_reading: Optional[str] = None, tel: Optional[str] = None, tel_av: Optional[str] = None, email: Optional[str] = None, memo: Optional[str] = None, birthday: Optional[date] = None, address: Optional[str] = None, url: Optional[str] = None, nickname: Optional[str] = None, org: Optional[str] = None): self.first_name = first_name self.last_name = last_name self.first_name_reading = first_name_reading self.last_name_reading = last_name_reading self.tel = tel self.tel_av = tel_av self.email = email self.memo = memo self.birthday = birthday self.address = address self.url = url self.nickname = nickname self.org = org def make_qr_code_text(self) -> str: """ Make a text for configuring a contact in a phone book. The MeCARD format is used, with an optional, non-standard (but often recognized) ORG field. See this archive of the format specifications: https://web.archive.org/web/20160304025131/https://www.nttdocomo.co.jp/english/service/developer/make/content/barcode/function/application/addressbook/index.html :return: the MeCARD contact description. """ # See this for an archive of the format specifications: # https://web.archive.org/web/20160304025131/https://www.nttdocomo.co.jp/english/service/developer/make/content/barcode/function/application/addressbook/index.html contact_text = 'MECARD:' for name_components_pair in ( ('N:%s;', (_escape_mecard_special_chars(self.last_name), _escape_mecard_special_chars(self.first_name))), ('SOUND:%s;', (_escape_mecard_special_chars(self.last_name_reading), _escape_mecard_special_chars(self.first_name_reading))) ): if name_components_pair[1][0] and name_components_pair[1][1]: name = '%s,%s' % name_components_pair[1] else: name = name_components_pair[1][0] or name_components_pair[1][1] or '' if name: contact_text += name_components_pair[0] % name if self.tel: contact_text += 'TEL:%s;' % _escape_mecard_special_chars(self.tel) if self.tel_av: contact_text += 'TEL-AV:%s;' % _escape_mecard_special_chars(self.tel_av) if self.email: contact_text += 'EMAIL:%s;' % _escape_mecard_special_chars(self.email) if self.memo: contact_text += 'NOTE:%s;' % _escape_mecard_special_chars(self.memo) if self.birthday: # Format date to YYMMDD. contact_text += 'BDAY:%s;' % self.birthday.strftime('%Y%m%d') if self.address: contact_text += 'ADR:%s;' % self.address if self.url: contact_text += 'URL:%s;' % _escape_mecard_special_chars(self.url) if self.nickname: contact_text += 'NICKNAME:%s;' % _escape_mecard_special_chars(self.nickname) # Not standard, but recognized by several readers. if self.org: contact_text += 'ORG:%s;' % _escape_mecard_special_chars(self.org) contact_text += ';' return contact_text def escaped_value(self, field_name: str): return _escape_mecard_special_chars(getattr(self, field_name)) class WifiConfig: """ Represents the configuration of a Wi-Fi connexion. The following fields are provided: * ssid: the name of the SSID * authentication: the authentication type for the SSID; can be AUTHENTICATION.wep or AUTHENTICATION.wpa, or AUTHENTICATION.nopass for no password. Or, omit for no password. * password: the password, ignored if "authentication" is 'nopass' (in which case it may be omitted). * hidden: tells whether the SSID is hidden or not; can be True or False. """ AUTHENTICATION = namedtuple('AUTHENTICATION', 'nopass WEP WPA')._make(range(3)) # type: ignore AUTHENTICATION_CHOICES = ((AUTHENTICATION.nopass, 'nopass'), (AUTHENTICATION.WEP, 'WEP'), (AUTHENTICATION.WPA, 'WPA')) def __init__(self, ssid: str = '', authentication: int = AUTHENTICATION.nopass, password: str = '', hidden: bool = False) -> None: self.ssid = ssid self.authentication = authentication self.password = password self.hidden = hidden def make_qr_code_text(self) -> str: """ Make a text for configuring a Wi-Fi connexion. The syntax is inspired by the MeCARD format used for contacts. :return: the WIFI configuration text that can be translated to a QR code. """ wifi_config = 'WIFI:' if self.ssid: wifi_config += 'S:%s;' % _escape_mecard_special_chars(self.ssid) if self.authentication: wifi_config += 'T:%s;' % WifiConfig.AUTHENTICATION_CHOICES[self.authentication][1] if self.password: wifi_config += 'P:%s;' % _escape_mecard_special_chars(self.password) if self.hidden: wifi_config += 'H:%s;' % str(self.hidden).lower() wifi_config += ';' return wifi_config class Coordinates: def __init__(self, latitude, longitude, altitude=None) -> None: self.latitude = latitude self.longitude = longitude self.altitude = altitude def __str__(self) -> str: if self.altitude: return 'latitude: %s, longitude: %s, altitude: %s' % (self.latitude, self.longitude, self.altitude) return 'latitude: %s, longitude: %s' % (self.latitude, self.longitude) def make_geolocation_text(self) -> str: return 'geo:%s,%s,%s' % ( escape(self.latitude), escape(self.longitude), escape(self.altitude)) def make_google_maps_text(self) -> str: return 'https://maps.google.com/local?q=%s,%s' % ( escape(self.latitude), escape(self.longitude)) def make_email_text(email: str) -> str: return 'mailto:%s' % email def make_tel_text(phone_number: Any) -> str: return 'tel:%s' % phone_number def make_sms_text(phone_number: Any) -> str: return 'sms:%s' % phone_number def make_youtube_text(video_id: str) -> str: return 'https://www.youtube.com/watch/?v=%s' % escape(video_id) def make_google_play_text(package_id: str) -> str: return 'https://play.google.com/store/apps/details?id=%s' % escape(package_id) def _escape_mecard_special_chars(string_to_escape: Optional[str]) -> Optional[str]: if not string_to_escape: return string_to_escape special_chars = ['\\', '"', ';', ',', ':'] for sc in special_chars: string_to_escape = string_to_escape.replace(sc, '\\%s' % sc) return string_to_escape django-qr-code-2.2.0/qr_code/templatetags/000077500000000000000000000000001405664203600204215ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code/templatetags/__init__.py000066400000000000000000000000001405664203600225200ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code/templatetags/qr_code.py000066400000000000000000000125721405664203600224160ustar00rootroot00000000000000"""Tags for Django template system that help generating QR codes.""" from typing import Union, Any from django import template from qr_code.qrcode.maker import make_qr_code_with_args, make_qr_code_url_with_args from qr_code.qrcode.utils import make_email_text, make_google_play_text, make_tel_text, make_sms_text, \ make_youtube_text, WifiConfig, ContactDetail, Coordinates register = template.Library() def _make_contact_or_wifi_qr_code(contact_or_wifi, expected_cls, embedded: bool, qr_code_args: dict) -> str: if not isinstance(contact_or_wifi, expected_cls): # For compatibility with existing views and templates, try to build from dict. contact_or_wifi = expected_cls(**contact_or_wifi) if embedded: return make_qr_code_with_args(contact_or_wifi.make_qr_code_text(), qr_code_args=qr_code_args) else: return make_qr_code_url_with_args(contact_or_wifi.make_qr_code_text(), qr_code_args=qr_code_args) def _make_google_maps_qr_code(embedded: bool, **kwargs) -> str: if 'coordinates' in kwargs: coordinates = kwargs.pop('coordinates') else: coordinates = Coordinates(kwargs.pop('latitude'), kwargs.pop('longitude')) if embedded: return make_qr_code_with_args(coordinates.make_google_maps_text(), qr_code_args=kwargs) else: return make_qr_code_url_with_args(coordinates.make_google_maps_text(), qr_code_args=kwargs) def _make_geolocation_qr_code(embedded: bool, **kwargs) -> str: if 'coordinates' in kwargs: coordinates = kwargs.pop('coordinates') else: coordinates = Coordinates(kwargs.pop('latitude'), kwargs.pop('longitude'), kwargs.pop('altitude')) if embedded: return make_qr_code_with_args(coordinates.make_geolocation_text(), qr_code_args=kwargs) else: return make_qr_code_url_with_args(coordinates.make_geolocation_text(), qr_code_args=kwargs) @register.simple_tag() def qr_from_text(text: Any, **kwargs) -> str: return make_qr_code_with_args(text, qr_code_args=kwargs) @register.simple_tag() def qr_for_email(email: Any, **kwargs) -> str: return make_qr_code_with_args(make_email_text(email), qr_code_args=kwargs) @register.simple_tag() def qr_for_tel(phone_number: Any, **kwargs) -> str: return make_qr_code_with_args(make_tel_text(phone_number), qr_code_args=kwargs) @register.simple_tag() def qr_for_sms(phone_number: Any, **kwargs) -> str: return make_qr_code_with_args(make_sms_text(phone_number), qr_code_args=kwargs) @register.simple_tag() def qr_for_geolocation(**kwargs) -> str: """Accepts a *'coordinates'* keyword argument or a triplet *'latitude'*, *'longitude'*, and *'altitude'*.""" return _make_geolocation_qr_code(embedded=True, **kwargs) @register.simple_tag() def qr_for_google_maps(**kwargs) -> str: """Accepts a *'coordinates'* keyword argument or a pair *'latitude'* and *'longitude'*.""" return _make_google_maps_qr_code(embedded=True, **kwargs) @register.simple_tag() def qr_for_youtube(video_id: str, **kwargs) -> str: return make_qr_code_with_args(make_youtube_text(video_id), qr_code_args=kwargs) @register.simple_tag() def qr_for_google_play(package_id: str, **kwargs) -> str: return make_qr_code_with_args(make_google_play_text(package_id), qr_code_args=kwargs) @register.simple_tag() def qr_for_contact(contact_detail, **kwargs) -> str: return _make_contact_or_wifi_qr_code(contact_detail, ContactDetail, embedded=True, qr_code_args=kwargs) @register.simple_tag() def qr_for_wifi(wifi_config, **kwargs) -> str: return _make_contact_or_wifi_qr_code(wifi_config, WifiConfig, embedded=True, qr_code_args=kwargs) @register.simple_tag() def qr_url_from_text(text: Any, **kwargs) -> str: return make_qr_code_url_with_args(text, qr_code_args=kwargs) @register.simple_tag() def qr_url_for_email(email: str, **kwargs) -> str: return make_qr_code_url_with_args(make_email_text(email), qr_code_args=kwargs) @register.simple_tag() def qr_url_for_tel(phone_number: Any, **kwargs) -> str: return make_qr_code_url_with_args(make_tel_text(phone_number), qr_code_args=kwargs) @register.simple_tag() def qr_url_for_sms(phone_number: Any, **kwargs) -> str: return make_qr_code_url_with_args(make_sms_text(phone_number), qr_code_args=kwargs) @register.simple_tag() def qr_url_for_geolocation(**kwargs) -> str: """Accepts a *'coordinates'* keyword argument or a triplet *'latitude'*, *'longitude'*, and *'altitude'*.""" return _make_geolocation_qr_code(embedded=False, **kwargs) @register.simple_tag() def qr_url_for_google_maps(**kwargs) -> str: """Accepts a *'coordinates'* keyword argument or a pair *'latitude'* and *'longitude'*.""" return _make_google_maps_qr_code(embedded=False, **kwargs) @register.simple_tag() def qr_url_for_youtube(video_id: str, **kwargs) -> str: return make_qr_code_url_with_args(make_youtube_text(video_id), qr_code_args=kwargs) @register.simple_tag() def qr_url_for_google_play(package_id: str, **kwargs) -> str: return make_qr_code_url_with_args(make_google_play_text(package_id), qr_code_args=kwargs) @register.simple_tag() def qr_url_for_contact(contact_detail, **kwargs) -> str: return _make_contact_or_wifi_qr_code(contact_detail, ContactDetail, embedded=False, qr_code_args=kwargs) @register.simple_tag() def qr_url_for_wifi(wifi_config, **kwargs) -> str: return _make_contact_or_wifi_qr_code(wifi_config, WifiConfig, embedded=False, qr_code_args=kwargs) django-qr-code-2.2.0/qr_code/tests/000077500000000000000000000000001405664203600170715ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code/tests/__init__.py000066400000000000000000000000001405664203600211700ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code/tests/resources/000077500000000000000000000000001405664203600211035ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code/tests/resources/qr_for_contact.ref.png000066400000000000000000000023651405664203600253750ustar00rootroot00000000000000PNG  IHDRZIDATx\QH v#}$`%Rc'h2?D_Cz~v^ؼyel#{xz' ~zaN+ ;p7 f!OHOl8=]-K AyF]~vlled+ޙ'teg"wW[mOzx$ns2 CPϺZ%2|1#b;mBuYHj9b2K2Q.ɪh.r(6z$E[y!-ƥXX'zd EmF1>,\td,b(>Eͮ6-Cg󡺷Rpn`؁A!Q}![j3P -68-!ZR9 k#t=.{^C\Y쌺I+.> B]ԽdCBCv КpŶY+qp2GHRT<抺fD8M,xdVUc+ %G(8ʖZD9ΎfM-c/3<޳ͩY"DT2l7jw2XSZםm*e@ff X6սohO+0 F80.P>;5hli`zax,;@bZh w62L{u hc Ae*3ױ81\ Ɣ-ϑPzmZzk{b'kl~YRWY#69NeЮ4{Y@0/ly)Zf& `T~+ok {C.%lI3$Nƒi~`7҆ױ{~ɰ^!"K-*].Bm,7b;iIܥ׎yjntq'mw#BsaAμ؜yIeS~e㘳]{>yx3DK樁¡django-qr-code-2.2.0/qr_code/tests/resources/qr_for_email.ref.png000066400000000000000000000004731405664203600250270ustar00rootroot00000000000000PNG  IHDRIDATxX 0 #|_I>*RM)8ăQG !Px+o xffl GU>;[!51Տm 醭 VarڧjgsHrEo}A6ևuHoCV͐ uo-Z %')XөohXx[߶Lڃ72K i 떧̬n{H,--{ iuÆ۹x5Cڧ !p{/ {Z IENDB`django-qr-code-2.2.0/qr_code/tests/resources/qr_for_email.ref.svg000066400000000000000000000021741405664203600250420ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code/tests/resources/qr_for_geolocation.ref.png000066400000000000000000000005751405664203600262460ustar00rootroot00000000000000PNG  IHDRzDIDATxXA0C|'Hष:OjUl\,$ṉ,׌p/r~,#}]gOy~zBѶnr=p_iO౫dP&6ٶ-ȢݬzPVBÃwA-(=}vUPTf0x߆ZVr/#SwN"@݂[-LL̾½;B~gqjgfTg`\yi%w})+eN n]|-tչA(WVV)!=u֚r}>]>K IENDB`django-qr-code-2.2.0/qr_code/tests/resources/qr_for_geolocation.ref.svg000066400000000000000000000030641405664203600262550ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code/tests/resources/qr_for_google_maps.ref.png000066400000000000000000000007131405664203600262310ustar00rootroot00000000000000PNG  IHDRiGeIDATxYm0 2RVH*o6F`\cS8V;{E=K}/z]Wƕ㹵\s'u#^u츋?H!OG/~?8 ?3oPb9gˉ?G0'UR kŜzE ~FZn7 I{6L["cßR".g00oLN6WBEF/ LdDQ"KXXNE`??79iۼ95W*KlsTwԿ; țKIENDB`django-qr-code-2.2.0/qr_code/tests/resources/qr_for_google_maps.ref.svg000066400000000000000000000035341405664203600262500ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code/tests/resources/qr_for_google_play.ref.png000066400000000000000000000010341405664203600262330ustar00rootroot00000000000000PNG  IHDRPIDATxYm0 django-qr-code-2.2.0/qr_code/tests/resources/qr_for_sms.ref.png000066400000000000000000000004771405664203600245460ustar00rootroot00000000000000PNG  IHDRIDATxXA0C|' HۥM>U]Z.6!$cWl> d^ՙ mc/\6w[j̃ VMt[U$7#L l7pZ* ?3o6 a%N'K78P+7Z.y*-,whfvRV1CȦR_1_H/^jucCO*Z!,Vz'V.?\p'磚/kv/קU=p3?ϼmIENDB`django-qr-code-2.2.0/qr_code/tests/resources/qr_for_sms.ref.svg000066400000000000000000000021151405664203600245500ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code/tests/resources/qr_for_tel.ref.png000066400000000000000000000005021405664203600245150ustar00rootroot00000000000000PNG  IHDR IDATx 0ѹ] @/D0:EV0쒳x9W21G[!*l 5u,pX:M,تͼF@8Z<}&Xy=RxQ:@v<ꆊx&aSߠ!PH6ʈ,̒5ciiH'ҵ8}K]FȍY#YΆ/b{S/khג)X9 [ZMK}\ .o,׶T7xK'U͏ T%V IENDB`django-qr-code-2.2.0/qr_code/tests/resources/qr_for_tel.ref.svg000066400000000000000000000023131405664203600245320ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code/tests/resources/qr_for_wifi.ref.png000066400000000000000000000006001405664203600246660ustar00rootroot00000000000000PNG  IHDRzGIDATxэ! C(S bٿHZ8f{{3F^U mZ]s7hJ@(ZUI=#h{ݣ@KlZ2k$]n3k%)*!f %np  8mdIN*ynlz,*l` ɞW[ڶ [4[B(x'ƥ^vk8'dIXÜu޴1'׶d\t{BZ -hYyYw^->22fBW S slht枠Hf|޿.ç% hIENDB`django-qr-code-2.2.0/qr_code/tests/resources/qr_for_wifi.ref.svg000066400000000000000000000030051405664203600247030ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code/tests/resources/qr_for_youtube.ref.png000066400000000000000000000007151405664203600254330ustar00rootroot00000000000000PNG  IHDRiGeIDATxY[! p$#qlb_;UǓPcnb۱5c׷?q^[+2% A||_i3=9֙~R ?^[m8+?g?\ C"}O;R'`2͢*p&I.Y'Ig 9CB(~!={+B~>lUJ W,ddjango-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_default.ref.png000066400000000000000000000002471405664203600263060ustar00rootroot00000000000000PNG  IHDR~ZnIDATxc4⃸C+D^! "H|_A(C/}Q _bwU0ᇰ django-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_error_correction_h.ref.png000066400000000000000000000011271405664203600305470ustar00rootroot00000000000000PNG  IHDRRR IDATxAn0P>@H R*cʦyz.~'I֔X,bX,bX,+T2lo?kܭbX*su<ru*6,WY,Y޶ i+𜷾r*bk_-bXoXNSsUź8_Zd*bE5TD\eXmXCW?obXm{X)D\eXf0nR9b]jUX,EUW1\eXN.Љܹ,ն>قU,qj1 \*bWcVfw8KX,y_-^)KZbXM_k@wVY}b^E7UjϪ_UX,2W ebXoj8X\eXwj:^IMq5`X\]ξt5uN` _eXZ|vuKP_eX~yM,bX,bX,M/?8ET{uIENDB`django-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_error_correction_h.ref.svg000066400000000000000000000023751405664203600305700ustar00rootroot00000000000000 django-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_error_correction_l.ref.png000066400000000000000000000007301405664203600305520ustar00rootroot00000000000000PNG  IHDR  jZIDATx0PkD.X%#y_3fB @ @ G~Gu>>5'}߫JH-Rz^GZK-/潎2jy_SraR @ Zz\zF@ IѾ) @ Z521=xwB åVNϓ:D1r5}O@ HֻLʺRk!R+sFUIv?@ @ C6@Ha EIENDB`django-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_error_correction_l.ref.svg000066400000000000000000000016161405664203600305710ustar00rootroot00000000000000 django-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_error_correction_m.ref.png000066400000000000000000000007301405664203600305530ustar00rootroot00000000000000PNG  IHDR  jZIDATx0PkD.X%#y_3fB @ @ G~Gu>>5'}߫JH-Rz^GZK-/潎2jy_SraR @ Zz\zF@ IѾ) @ Z521=xwB åVNϓ:D1r5}O@ HֻLʺRk!R+sFUIv?@ @ C6@Ha EIENDB`django-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_error_correction_m.ref.svg000066400000000000000000000016161405664203600305720ustar00rootroot00000000000000 django-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_error_correction_q.ref.png000066400000000000000000000007301405664203600305570ustar00rootroot00000000000000PNG  IHDR  jZIDATx0PkD.X%#y_3fB @ @ G~Gu>>5'}߫JH-Rz^GZK-/潎2jy_SraR @ Zz\zF@ IѾ) @ Z521=xwB åVNϓ:D1r5}O@ HֻLʺRk!R+sFUIv?@ @ C6@Ha EIENDB`django-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_error_correction_q.ref.svg000066400000000000000000000016161405664203600305760ustar00rootroot00000000000000 django-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_size_10.ref.png000066400000000000000000000005011405664203600261250ustar00rootroot00000000000000PNG  IHDR""uIDATxA '|_I>ՁHS}*1+Ȃ *T^>*zLT;^d/{^~)"eYezg|_aT+> }Xsb؏1(YqX ao>?G-/ת WZ{d?.g_mdNh7^Kω9e{[ *TT}=P6IENDB`django-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_size_10.ref.svg000066400000000000000000000015231405664203600261450ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_size_6.ref.png000066400000000000000000000004021405664203600260520ustar00rootroot00000000000000PNG  IHDRw CIDATxW 0 32WH唃WQ#$TȒM%K{y}ބI|ڧJϳ4&STM>$ML/>TATnO,/#ձ9LF'$1 5d "rWvB ]AذJbh3ūA|&,O$(nl&/OC8oIENDB`django-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_size_6.ref.svg000066400000000000000000000015621405664203600260750ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_size_8.ref.png000066400000000000000000000003521405664203600260600ustar00rootroot00000000000000PNG  IHDRҕIDATxX0kL;1Fcl*hœ +bG$79S; ̙<_p,To3JspҾNSV=)Ժ 4߱m?Q(㿜A|3.1?3X|U.cM#3%*󘣵۷6%zjF&IENDB`django-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_size_8.ref.svg000066400000000000000000000015621405664203600260770ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_size_huge.ref.png000066400000000000000000000024031405664203600266400ustar00rootroot00000000000000PNG  IHDRppJIDATx1 @t]pJhpc{WkMM `>................................................................................................................................C#Us=*\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\S3!^ּ<.............................nK*իwgmƽ-Pgݭ{ggpwqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqWg]Sr<.............................nA!\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\܃)..............................nnļ>SOgm3$y~WV cuz!y!%πے[&"v_~Xupqqqqqqqqqqqqqqqqqqqqqqqqqqqqqpdjango-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_size_large.ref.png000066400000000000000000000012531405664203600270040ustar00rootroot00000000000000PNG  IHDRffSrIDATxm0@Q+.h$VD؜&yﰧ/Ð לh4Fh4Fh4Fh4Fh4Fh4Fh?şWr}+Fh4FZ8Bq>kϞJh4Fh{g53yPJᦏơh4Fh5NqVh4FhG7&j4Fh4F{N,7n}Fh4STVhFh4FqbN&Uh4Fh4ڵSimbڰ?qh4Fh4ZgjFh4FqjۍxGh4FhS7Rfj&ơh4Fh6NG׊fGh4Fh|ZSS$ơh4Fh>q'Mh4F:kSiŰ'5Ch4FnkzAnUkˣqh4Fh4Z>84Fh4푍4'K>Fh4F8q;5\5Fh4jAǡh4Fh5ίFh4Fh4Fh4Fh4Fh4Fh4F{4f//1(IENDB`django-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_size_large.ref.svg000066400000000000000000000015501405664203600270170ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_size_medium.ref.png000066400000000000000000000007141405664203600271730ustar00rootroot00000000000000PNG  IHDR  jZIDATxKj0@QQ/ Kֵ$/ R>n)d89AIQҴ;JB @ @ L>mJo_5[jhfެZb^su4싮c2LDj]3@ >d]m8;\ @DV33DZk N1mxbѳ!8gT @V{M/7@ &W?C\+r=@ ToLB 1? @ @ >\7%gIENDB`django-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_size_medium.ref.svg000066400000000000000000000015621405664203600272100ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_size_small.ref.png000066400000000000000000000005111405664203600270160ustar00rootroot00000000000000PNG  IHDR\\m;IDATxA0 ->2?0M7v  q@F0000000װ4|.wfO7KܨhC*Z$%=EOz nē|HnqggQmnh/Ė n1C37~W=ݘO3X:,n,=ECQ7oh1&IS<Qfcō}rnFZdjango-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_size_tiny.ref.png000066400000000000000000000004021405664203600266700ustar00rootroot00000000000000PNG  IHDRw CIDATxW 0 32WH唃WQ#$TȒM%K{y}ބI|ڧJϳ4&STM>$ML/>TATnO,/#ձ9LF'$1 5d "rWvB ]AذJbh3ūA|&,O$(nl&/OC8oIENDB`django-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_size_tiny.ref.svg000066400000000000000000000015621405664203600267130ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_version_2.ref.png000066400000000000000000000011051405664203600265620ustar00rootroot00000000000000PNG  IHDRRR  IDATxA0p=F θ|Y`_MbZ^6ΉbX,bX,b>Jq >eLl} zW񞷿)ڊqsIX,~N!bus.5k7zebujӜaX,փ\{*7$WY,Wk箰X,Vϳn ,&t_*bե}zbոj UjjE>*Uj;Y_eXqfX,bX,bXO Me IENDB`django-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_version_2.ref.svg000066400000000000000000000023051405664203600266000ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_version_4.ref.png000066400000000000000000000015611405664203600265720ustar00rootroot00000000000000PNG  IHDR8IDATxA0Pkrs$VW0سy^C.mX Nt:Nt:Nt:K~W?etl q<R!w~Q=:N駳 #T֑_ltlWRX7&:Nt %ĖltlURLȦMt:NMa,a./q&:NɦO^KYNٔg3TRmaR7t:}L6Uq}\JZ&\DuS :LZj[ltlM[[)Mt:NMy;m/w1j;veNOgS鴃HMľFt:}T6mBgHN鳳)#ҝj⩷\DtBk[pC^dNGMy7S{Xc,Ni}ߩޕfS܍ eNfSbpNK:s_ٱNٔ `tKSQN駲] a<ZKIT[N'曞t:>n=tReNOM-K D#8[N05*o+\@&:NΦkp#nMt:NM_@D;w.aN3ݻtzUuzt:NMqa}}!ztl cIgǯ|:)U%t:~2&Nt:Nt:Nt:hQee1IENDB`django-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_version_4.ref.svg000066400000000000000000000037101405664203600266030ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_version_default.ref.png000066400000000000000000000007141405664203600300520ustar00rootroot00000000000000PNG  IHDR  jZIDATxKj0@QQ/ Kֵ$/ R>n)d89AIQҴ;JB @ @ L>mJo_5[jhfެZb^su4싮c2LDj]3@ >d]m8;\ @DV33DZk N1mxbѳ!8gT @V{M/7@ &W?C\+r=@ ToLB 1? @ @ >\7%gIENDB`django-qr-code-2.2.0/qr_code/tests/resources/qrfromtext_version_default.ref.svg000066400000000000000000000015621405664203600300670ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code/tests/tests.py000066400000000000000000001115471405664203600206160ustar00rootroot00000000000000"""Tests for qr_code application.""" import base64 import re import os from datetime import date from itertools import product from django.conf import settings from django.contrib.auth.models import AnonymousUser, User from django.core.cache import caches from django.template import Template, Context from django.test import SimpleTestCase, override_settings from django.utils.safestring import mark_safe from django.utils.html import escape from qr_code.qrcode.maker import make_embedded_qr_code from qr_code.qrcode.constants import ERROR_CORRECTION_DICT, DEFAULT_IMAGE_FORMAT, DEFAULT_MODULE_SIZE, \ DEFAULT_ERROR_CORRECTION, DEFAULT_VERSION from qr_code.qrcode.serve import make_qr_code_url, allows_external_request_from_user from qr_code.qrcode.utils import ContactDetail, WifiConfig, QRCodeOptions, Coordinates from qr_code.templatetags.qr_code import qr_from_text, qr_url_from_text # Set this flag to True for writing the new version of each reference image in tests/resources while running the tests. REFRESH_REFERENCE_IMAGES = False BASE64_PNG_IMAGE_TEMPLATE = 'Hello World!' IMAGE_TAG_BASE64_DATA_RE = re.compile(r'data:image/png;base64,(?P[\w/+=]+)') TEST_TEXT = 'Hello World!' COMPLEX_TEST_TEXT = '/%+¼@#=<>àé' TEST_CONTACT_DETAIL = dict( first_name='John', last_name='Doe', first_name_reading='jAAn', last_name_reading='dOH', tel='+41769998877', email='j.doe@company.com', url='http://www.company.com', birthday=date(year=1985, month=10, day=2), address='Cras des Fourches 987, 2800 Delémont, Jura, Switzerland', memo='Development Manager', org='Company Ltd', ) TEST_WIFI_CONFIG = dict( ssid='my-wifi', authentication=WifiConfig.AUTHENTICATION.WPA, password='wifi-password' ) OVERRIDE_CACHES_SETTING = {'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', }, 'qr-code': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'qr-code-cache', 'TIMEOUT': 3600}} SVG_REF_SUFFIX = '.ref.svg' PNG_REF_SUFFIX = '.ref.png' def get_urls_without_token_for_comparison(*urls): token_regex = re.compile(r"&?token=[^&]+") simplified_urls = list(map(lambda x: token_regex.sub('', x), urls)) simplified_urls = list(map(lambda x: x.replace('?&', '?'), simplified_urls)) return simplified_urls def get_resources_path(): tests_dir = os.path.dirname(os.path.abspath(__file__)) return os.path.join(tests_dir, 'resources') def minimal_svg(s): """Returns the SVG document without the XML declaration and SVG namespace declaration :rtype: str """ return s.replace('\n', '') \ .replace('xmlns="http://www.w3.org/2000/svg" ', '').strip() class TestApps(SimpleTestCase): def test_apps_attributes(self): from qr_code.apps import QrCodeConfig self.assertEqual(QrCodeConfig.name, 'qr_code') self.assertEqual(QrCodeConfig.verbose_name, 'Django QR Code') class TestQRCodeOptions(SimpleTestCase): def test_qr_code_options(self): with self.assertRaises(TypeError): QRCodeOptions(foo='bar') options = QRCodeOptions() self.assertEqual(options.border, 4) self.assertEqual(options.size, DEFAULT_MODULE_SIZE) self.assertEqual(options.image_format, DEFAULT_IMAGE_FORMAT) self.assertEqual(options.version, DEFAULT_VERSION) self.assertEqual(options.error_correction, DEFAULT_ERROR_CORRECTION) options = QRCodeOptions(image_format='invalid-image-format') self.assertEqual(options.image_format, DEFAULT_IMAGE_FORMAT) def test_kw_save(self): options = QRCodeOptions(border=0, image_format="png", size=13) self.assertDictEqual(options.kw_save(), {'border': 0, 'kind': 'png', 'scale': 13}) class TestContactDetail(SimpleTestCase): def test_make_qr_code_text(self): data = dict(**TEST_CONTACT_DETAIL) c1 = ContactDetail(**data) data['nickname'] = 'buddy' c2 = ContactDetail(**data) data['last_name'] = "O'Hara;,:" data['tel_av'] = 'n/a' c3 = ContactDetail(**data) del data['last_name'] c4 = ContactDetail(**data) self.assertEqual(c1.make_qr_code_text(), r'MECARD:N:Doe,John;SOUND:dOH,jAAn;TEL:+41769998877;EMAIL:j.doe@company.com;NOTE:Development Manager;BDAY:19851002;ADR:Cras des Fourches 987, 2800 Delémont, Jura, Switzerland;URL:http\://www.company.com;ORG:Company Ltd;;') self.assertEqual(c2.make_qr_code_text(), r'MECARD:N:Doe,John;SOUND:dOH,jAAn;TEL:+41769998877;EMAIL:j.doe@company.com;NOTE:Development Manager;BDAY:19851002;ADR:Cras des Fourches 987, 2800 Delémont, Jura, Switzerland;URL:http\://www.company.com;NICKNAME:buddy;ORG:Company Ltd;;') self.assertEqual(c3.make_qr_code_text(), r"MECARD:N:O'Hara\;\,\:,John;SOUND:dOH,jAAn;TEL:+41769998877;TEL-AV:n/a;EMAIL:j.doe@company.com;NOTE:Development Manager;BDAY:19851002;ADR:Cras des Fourches 987, 2800 Delémont, Jura, Switzerland;URL:http\://www.company.com;NICKNAME:buddy;ORG:Company Ltd;;") self.assertEqual(c4.make_qr_code_text(), r"MECARD:N:John;SOUND:dOH,jAAn;TEL:+41769998877;TEL-AV:n/a;EMAIL:j.doe@company.com;NOTE:Development Manager;BDAY:19851002;ADR:Cras des Fourches 987, 2800 Delémont, Jura, Switzerland;URL:http\://www.company.com;NICKNAME:buddy;ORG:Company Ltd;;") class TestWifiConfig(SimpleTestCase): def test_make_qr_code_text(self): wifi1 = WifiConfig(**TEST_WIFI_CONFIG) wifi2 = WifiConfig(hidden=True, **TEST_WIFI_CONFIG) self.assertEqual(wifi1.make_qr_code_text(), 'WIFI:S:my-wifi;T:WPA;P:wifi-password;;') self.assertEqual(wifi2.make_qr_code_text(), 'WIFI:S:my-wifi;T:WPA;P:wifi-password;H:true;;') class TestCoordinates(SimpleTestCase): def test_coordinates(self): c1 = Coordinates(latitude=586000.32, longitude=250954.19) c2 = Coordinates(latitude=586000.32, longitude=250954.19, altitude=500) self.assertEqual(c1.__str__(), 'latitude: 586000.32, longitude: 250954.19') self.assertEqual(c2.__str__(), 'latitude: 586000.32, longitude: 250954.19, altitude: 500') class TestQRUrlFromTextResult(SimpleTestCase): """ Ensures that serving images representing QR codes works as expected (with or without caching, and with or without protection against external requests). """ default_ref_base_file_name = 'qrfromtext_default' @staticmethod def _get_reference_result_for_default_svg(): return get_svg_content_from_file_name(TestQRUrlFromTextResult.default_ref_base_file_name) @staticmethod def _get_reference_result_for_default_png(): return get_png_content_from_file_name(TestQRUrlFromTextResult.default_ref_base_file_name) def test_svg_url(self): is_first = True users = [None, AnonymousUser(), User(username='test')] for url_options in product([True, False, None], [True, False, None], users): cache_enabled = url_options[0] url_signature_enabled = url_options[1] user = url_options[2] print("\t - cache_enabled=%s, url_signature_enabled=%s, user=%s" % (cache_enabled, url_signature_enabled, user)) url_options_kwargs = dict() url0 = make_qr_code_url(TEST_TEXT, QRCodeOptions(size=1), **dict(**url_options_kwargs, cache_enabled=cache_enabled, url_signature_enabled=url_signature_enabled)) if cache_enabled is not None: url_options_kwargs['cache_enabled'] = cache_enabled url1 = make_qr_code_url(TEST_TEXT, QRCodeOptions(size=1), **dict(**url_options_kwargs, url_signature_enabled=url_signature_enabled)) if url_signature_enabled is not None: url_options_kwargs['url_signature_enabled'] = url_signature_enabled url2 = qr_url_from_text(TEST_TEXT, size=1, **url_options_kwargs) url3 = qr_url_from_text(TEST_TEXT, image_format='svg', size=1, **url_options_kwargs) url4 = qr_url_from_text(TEST_TEXT, image_format='SVG', size=1, **url_options_kwargs) url5 = qr_url_from_text(TEST_TEXT, options=QRCodeOptions(image_format='SVG', size=1), **url_options_kwargs) # Using an invalid image format should fallback to SVG. url6 = qr_url_from_text(TEST_TEXT, image_format='invalid-format-name', size=1, **url_options_kwargs) url = url1 if url_signature_enabled is not False: urls = get_urls_without_token_for_comparison(url0, url1, url2, url3, url4, url5, url6) else: urls = [url0, url1, url2, url3, url4, url5, url6] self.assertEqual(urls[0], urls[1]) self.assertEqual(urls[0], urls[2]) self.assertEqual(urls[0], urls[3]) self.assertEqual(urls[0], urls[4]) self.assertEqual(urls[0], urls[5]) response = self.client.get(url) expected_status_code = 200 if url_signature_enabled is False and not allows_external_request_from_user(user): expected_status_code = 403 self.assertEqual(response.status_code, expected_status_code) image_data = response.content.decode('utf-8') if expected_status_code == 200: if is_first and REFRESH_REFERENCE_IMAGES: write_svg_content_to_file(TestQRUrlFromTextResult.default_ref_base_file_name, image_data) is_first = False self.assertEqual(image_data, TestQRUrlFromTextResult._get_reference_result_for_default_svg()) def test_png_url(self): is_first = True for url_options in product([True, False, None], [True, False, None]): cache_enabled = url_options[0] url_signature_enabled = url_options[1] url_options_kwargs = dict() if cache_enabled is not None: url_options_kwargs['cache_enabled'] = cache_enabled if url_signature_enabled is not None: url_options_kwargs['url_signature_enabled'] = url_signature_enabled url1 = make_qr_code_url(TEST_TEXT, QRCodeOptions(image_format='png', size=1), **url_options_kwargs) url2 = qr_url_from_text(TEST_TEXT, image_format='png', size=1, **url_options_kwargs) url3 = qr_url_from_text(TEST_TEXT, image_format='PNG', size=1, **url_options_kwargs) url4 = qr_url_from_text(TEST_TEXT, options=QRCodeOptions(image_format='PNG', size=1), **url_options_kwargs) url = url1 if url_signature_enabled is not False: urls = get_urls_without_token_for_comparison(url1, url2, url3, url4) else: urls = [url1, url2, url3, url4] self.assertEqual(urls[0], urls[1]) self.assertEqual(urls[0], urls[2]) self.assertEqual(urls[0], urls[3]) response = self.client.get(url) print("\t - cache_enabled=%s, url_signature_enabled=%s" % (cache_enabled, url_signature_enabled)) expected_status_code = 200 if url_signature_enabled is False and not allows_external_request_from_user(None): expected_status_code = 403 self.assertEqual(response.status_code, expected_status_code) if expected_status_code == 200: if is_first and REFRESH_REFERENCE_IMAGES: write_png_content_to_file(TestQRUrlFromTextResult.default_ref_base_file_name, response.content) is_first = False self.assertEqual(response.content, TestQRUrlFromTextResult._get_reference_result_for_default_png()) @override_settings(CACHES=OVERRIDE_CACHES_SETTING, QR_CODE_CACHE_ALIAS=None) def test_svg_with_cache_but_no_alias(self): self.test_svg_url() @override_settings(CACHES=OVERRIDE_CACHES_SETTING) def test_png_with_cache(self): self.test_png_url() @override_settings(CACHES=OVERRIDE_CACHES_SETTING, QR_CODE_CACHE_ALIAS=None) def test_png_with_cache_but_no_alias(self): self.test_png_url() @override_settings(QR_CODE_URL_PROTECTION=dict(TOKEN_LENGTH=30, SIGNING_KEY='my-secret-signing-key', SIGNING_SALT='my-signing-salt', ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER=True)) def test_url_with_protection_settings_1(self): # We need to clear cache every time we change the QR_CODE_URL_PROTECTION to avoid incidence between tests. caches[settings.QR_CODE_CACHE_ALIAS].clear() self.test_svg_url() self.test_png_url() response = self.client.get(make_qr_code_url(TEST_TEXT, url_signature_enabled=False, cache_enabled=False)) # Registered users can access the URL externally, but since we are not logged in, we must expect an HTTP 403. self.assertEqual(response.status_code, 403) @override_settings(QR_CODE_URL_PROTECTION=dict(ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER=False)) def test_url_with_protection_settings_2(self): # We need to clear cache every time we change the QR_CODE_URL_PROTECTION to avoid incidence between tests. caches[settings.QR_CODE_CACHE_ALIAS].clear() self.test_svg_url() self.test_png_url() response = self.client.get(make_qr_code_url(TEST_TEXT, url_signature_enabled=False, cache_enabled=False)) self.assertEqual(response.status_code, 403) response = self.client.get(make_qr_code_url(TEST_TEXT, url_signature_enabled=True, cache_enabled=False)) self.assertEqual(response.status_code, 200) @override_settings(QR_CODE_URL_PROTECTION=dict(ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER=lambda user: False)) def test_url_with_protection_settings_3(self): # We need to clear cache every time we change the QR_CODE_URL_PROTECTION to avoid incidence between tests. caches[settings.QR_CODE_CACHE_ALIAS].clear() self.test_svg_url() self.test_png_url() response = self.client.get(make_qr_code_url(TEST_TEXT, url_signature_enabled=False, cache_enabled=False)) self.assertEqual(response.status_code, 403) response = self.client.get(make_qr_code_url(TEST_TEXT, url_signature_enabled=True, cache_enabled=False)) self.assertEqual(response.status_code, 200) @override_settings(QR_CODE_URL_PROTECTION=dict(ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER=lambda user: True)) def test_url_with_protection_settings_4(self): # We need to clear cache every time we change the QR_CODE_URL_PROTECTION to avoid incidence between tests. caches[settings.QR_CODE_CACHE_ALIAS].clear() self.test_svg_url() self.test_png_url() # The callable for ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER always return True, even for anonymous user. # Therefore, we must expect an HTTP 200. # We test with different values of url_signature_enabled. response = self.client.get(make_qr_code_url(TEST_TEXT, cache_enabled=False)) self.assertEqual(response.status_code, 200) response = self.client.get(make_qr_code_url(TEST_TEXT, url_signature_enabled=True, cache_enabled=False)) self.assertEqual(response.status_code, 200) response = self.client.get(make_qr_code_url(TEST_TEXT, url_signature_enabled=False, cache_enabled=False)) self.assertEqual(response.status_code, 200) def test_url_with_invalid_signature_token(self): valid_url_with_signature_token = make_qr_code_url(TEST_TEXT) url_with_invalid_signature_token = valid_url_with_signature_token.replace('token=', 'token=some-front-padding') response = self.client.get(url_with_invalid_signature_token) self.assertEqual(response.status_code, 403) def test_url_with_wrong_signature_token(self): valid_url_with_signature_token_for_size_10 = make_qr_code_url(TEST_TEXT, QRCodeOptions(size=10)) valid_url_with_signature_token_for_size_8 = make_qr_code_url(TEST_TEXT, QRCodeOptions(size=8)) token_regex = re.compile(r"token=([^&]+)") match = token_regex.search(valid_url_with_signature_token_for_size_8) size_8_token_value = match.group(1) match = token_regex.search(valid_url_with_signature_token_for_size_10) size_10_token_value = match.group(1) url_with_invalid_signature_token = valid_url_with_signature_token_for_size_10.replace(size_10_token_value, size_8_token_value) response = self.client.get(url_with_invalid_signature_token) self.assertEqual(response.status_code, 403) def test_svg_error_correction(self): base_file_name = 'qrfromtext_error_correction' for correction_level in ERROR_CORRECTION_DICT: print('Testing SVG URL with error correction: %s' % correction_level) url1 = make_qr_code_url(COMPLEX_TEST_TEXT, QRCodeOptions(error_correction=correction_level), cache_enabled=False) url2 = qr_url_from_text(COMPLEX_TEST_TEXT, error_correction=correction_level, cache_enabled=False) url3 = qr_url_from_text(COMPLEX_TEST_TEXT, error_correction=correction_level, image_format='svg', cache_enabled=False) url4 = qr_url_from_text(COMPLEX_TEST_TEXT, error_correction=correction_level, image_format='SVG', cache_enabled=False) url5 = qr_url_from_text(COMPLEX_TEST_TEXT, options=QRCodeOptions(error_correction=correction_level, image_format='SVG'), cache_enabled=False) # Using an invalid image format should fallback to SVG. url6 = qr_url_from_text(COMPLEX_TEST_TEXT, error_correction=correction_level, image_format='invalid-format-name', cache_enabled=False) url = url1 urls = get_urls_without_token_for_comparison(url1, url2, url3, url4, url5, url6) self.assertEqual(urls[0], urls[1]) self.assertEqual(urls[0], urls[2]) self.assertEqual(urls[0], urls[3]) self.assertEqual(urls[0], urls[4]) self.assertEqual(urls[0], urls[5]) response = self.client.get(url) self.assertEqual(response.status_code, 200) source_image_data = response.content.decode('utf-8') ref_file_name = '%s_%s' % (base_file_name, correction_level.lower()) if REFRESH_REFERENCE_IMAGES: write_svg_content_to_file(ref_file_name, source_image_data) ref_image_data = get_svg_content_from_file_name(ref_file_name) self.assertEqual(source_image_data, ref_image_data) def test_png_error_correction(self): base_file_name = 'qrfromtext_error_correction' for correction_level in ERROR_CORRECTION_DICT: print('Testing PNG URL with error correction: %s' % correction_level) url1 = make_qr_code_url(COMPLEX_TEST_TEXT, QRCodeOptions(error_correction=correction_level, image_format='png'), cache_enabled=False) url2 = make_qr_code_url(COMPLEX_TEST_TEXT, QRCodeOptions(error_correction=correction_level, image_format='PNG'), cache_enabled=False) url3 = qr_url_from_text(COMPLEX_TEST_TEXT, error_correction=correction_level, image_format='png', cache_enabled=False) url4 = qr_url_from_text(COMPLEX_TEST_TEXT, error_correction=correction_level, image_format='PNG', cache_enabled=False) url5 = qr_url_from_text(COMPLEX_TEST_TEXT, options=QRCodeOptions(error_correction=correction_level, image_format='PNG'), cache_enabled=False) url = url1 urls = get_urls_without_token_for_comparison(url1, url2, url3, url4, url5) self.assertEqual(urls[0], urls[1]) self.assertEqual(urls[0], urls[2]) self.assertEqual(urls[0], urls[3]) self.assertEqual(urls[0], urls[4]) response = self.client.get(url) self.assertEqual(response.status_code, 200) source_image_data = response.content ref_file_name = '%s_%s' % (base_file_name, correction_level.lower()) if REFRESH_REFERENCE_IMAGES: write_png_content_to_file(ref_file_name, source_image_data) ref_image_data = get_png_content_from_file_name(ref_file_name) self.assertEqual(source_image_data, ref_image_data) class TestQRFromTextSvgResult(SimpleTestCase): """ Ensures that produced QR codes in SVG format coincide with verified references. The tests cover direct call to tag function, rendering of tag, and direct call to qr_code API. """ def test_size(self): base_ref_file_name = 'qrfromtext_size' sizes = ['t', 'T', 's', 'S', None, -1, 0, 'm', 'M', 'l', 'L', 'h', 'H', '6', 6, '8', 8, '10', 10] size_names = ['tiny'] * 2 + ['small'] * 2 + ['medium'] * 5 + ['large'] * 2 + ['huge'] * 2 + ['6'] * 2 + ['8'] * 2 + ['10'] * 2 for i in range(len(sizes)): size = sizes[i] print('Testing SVG with size %s' % size) size_name = size_names[i] qr1 = make_embedded_qr_code(TEST_TEXT, QRCodeOptions(size=size)) qr2 = qr_from_text(TEST_TEXT, size=size) qr3 = qr_from_text(TEST_TEXT, size=size, image_format='svg') qr4 = qr_from_text(TEST_TEXT, options=QRCodeOptions(size=size, image_format='svg')) qr5 = qr_from_text(TEST_TEXT, size=size, image_format='invalid-format-name') result_file_name = '%s_%s' % (base_ref_file_name, size_name) if REFRESH_REFERENCE_IMAGES: write_svg_content_to_file(result_file_name, qr1) result = get_svg_content_from_file_name(result_file_name) self.assertEqual(qr1, qr2) self.assertEqual(qr1, qr3) self.assertEqual(qr1, qr4) self.assertEqual(qr1, qr5) self.assertEqual(qr1, result) def test_version(self): base_file_name = "qrfromtext_version" versions = [None, -1, 0, 41, '-1', '0', '41', 'blabla', 1, '1', 2, '2', 4, '4'] version_names = ['default'] * 10 + [ '2', '2', '4', '4' ] for i in range(len(versions)): version = versions[i] print('Testing SVG with version %s' % version) version_name = version_names[i] qr1 = make_embedded_qr_code(TEST_TEXT, QRCodeOptions(version=version)) qr2 = qr_from_text(TEST_TEXT, version=version) qr3 = qr_from_text(TEST_TEXT, version=version, image_format='svg') qr4 = qr_from_text(TEST_TEXT, version=version, image_format='SVG') qr5 = qr_from_text(TEST_TEXT, options=QRCodeOptions(version=version, image_format='SVG')) qr6 = qr_from_text(TEST_TEXT, version=version, image_format='invalid-format-name') result_file_name = '%s_%s' % (base_file_name, version_name) if REFRESH_REFERENCE_IMAGES: write_svg_content_to_file(result_file_name, qr1) result = get_svg_content_from_file_name(result_file_name) self.assertEqual(qr1, qr2) self.assertEqual(qr1, qr3) self.assertEqual(qr1, qr4) self.assertEqual(qr1, qr5) self.assertEqual(qr1, qr6) self.assertEqual(qr1, result) def test_error_correction(self): file_base_name = 'qrfromtext_error_correction' tests_data = [] for correction_level in ERROR_CORRECTION_DICT.keys(): ref_file_name = '%s_%s' % (file_base_name, correction_level) tests_data.append(dict(source=f'{{% qr_from_text "{COMPLEX_TEST_TEXT}" image_format="svg" error_correction="{correction_level}" %}}', ref_file_name=ref_file_name.lower())) for test_data in tests_data: print('Testing template: %s' % test_data['source']) html_source = mark_safe('{% load qr_code %}' + test_data['source']) template = Template(html_source) context = Context() source_image_data = template.render(context) if REFRESH_REFERENCE_IMAGES: write_svg_content_to_file(test_data['ref_file_name'], source_image_data) ref_image_data = get_svg_content_from_file_name(test_data['ref_file_name']) self.assertEqual(minimal_svg(source_image_data), minimal_svg(ref_image_data)) class TestQRFromTextPngResult(SimpleTestCase): """ Ensures that produced QR codes in PNG format coincide with verified references. The tests cover direct call to tag function, rendering of tag, and direct call to qr_code API. """ def test_size(self): base_ref_file_name = 'qrfromtext_size' sizes = ['t', 'T', 's', 'S', None, -1, 0, 'm', 'M', 'l', 'L', 'h', 'H', '6', 6, '8', 8, '10', 10] size_names = ['tiny'] * 2 + ['small'] * 2 + ['medium'] * 5 + ['large'] * 2 + ['huge'] * 2 + ['6'] * 2 + [ '8'] * 2 + ['10'] * 2 for i in range(len(sizes)): size = sizes[i] print('Testing PNG with size %s' % size) size_name = size_names[i] result_file_name = '%s_%s' % (base_ref_file_name, size_name) qr1 = make_embedded_qr_code(TEST_TEXT, QRCodeOptions(size=size, image_format='png')) qr2 = qr_from_text(TEST_TEXT, size=size, image_format='png') qr3 = qr_from_text(TEST_TEXT, options=QRCodeOptions(size=size, image_format='png')) if REFRESH_REFERENCE_IMAGES: match = IMAGE_TAG_BASE64_DATA_RE.search(qr1) source_image_data = match.group('data') write_png_content_to_file(result_file_name, base64.b64decode(source_image_data)) result = base64.b64encode(get_png_content_from_file_name(result_file_name)).decode('utf-8') self.assertEqual(qr1, qr2) self.assertEqual(qr1, qr3) self.assertEqual(qr1, BASE64_PNG_IMAGE_TEMPLATE % result) def test_version(self): base_file_name = "qrfromtext_version" versions = [None, -1, 0, 41, '-1', '0', '41', 'blabla', 1, '1', 2, '2', 4, '4'] version_names = ['default'] * 10 + [ '2', '2', '4', '4' ] for i in range(len(versions)): version = versions[i] print('Testing PNG with version %s' % version) version_name = version_names[i] qr1 = make_embedded_qr_code(TEST_TEXT, QRCodeOptions(version=version, image_format='png')) qr2 = qr_from_text(TEST_TEXT, version=version, image_format='png') qr3 = qr_from_text(TEST_TEXT, version=version, image_format='PNG') qr4 = qr_from_text(TEST_TEXT, options=QRCodeOptions(version=version, image_format='PNG')) result_file_name = '%s_%s' % (base_file_name, version_name) if REFRESH_REFERENCE_IMAGES: match = IMAGE_TAG_BASE64_DATA_RE.search(qr1) source_image_data = match.group('data') write_png_content_to_file(result_file_name, base64.b64decode(source_image_data)) result = base64.b64encode(get_png_content_from_file_name(result_file_name)).decode('utf-8') self.assertEqual(qr1, qr2) self.assertEqual(qr1, qr3) self.assertEqual(qr1, qr4) self.assertEqual(qr1, BASE64_PNG_IMAGE_TEMPLATE % result) def test_error_correction(self): file_base_name = 'qrfromtext_error_correction' tests_data = [] for correction_level in ERROR_CORRECTION_DICT.keys(): ref_file_name = '%s_%s' % (file_base_name, correction_level) tests_data.append(dict(source=f'{{% qr_from_text "{COMPLEX_TEST_TEXT}" image_format="png" error_correction="{correction_level}" %}}', ref_file_name=ref_file_name.lower())) for test_data in tests_data: print('Testing template: %s' % test_data['source']) html_source = mark_safe('{% load qr_code %}' + test_data['source']) template = Template(html_source) context = Context() source_image = template.render(context).strip() source_image_data = source_image[32:-len('" alt="%s"' % escape(COMPLEX_TEST_TEXT))] source_image_data = base64.b64decode(source_image_data) if REFRESH_REFERENCE_IMAGES: write_png_content_to_file(test_data['ref_file_name'], source_image_data) ref_image_data = get_png_content_from_file_name(test_data['ref_file_name']) self.assertEqual(source_image_data, ref_image_data) class TestQRForApplications(SimpleTestCase): @staticmethod def _make_test_data(tag_pattern, ref_file_name, tag_args, template_context=dict()): tag_content = tag_pattern for key, value in tag_args.items(): if isinstance(value, str): tag_content += ' %s="%s"' % (key, value) else: tag_content += ' %s=%s' % (key, value) return dict(source='{% ' + tag_content + ' %}', ref_file_name=ref_file_name, template_context=template_context) @staticmethod def _make_tests_data(embedded=True, image_format='svg'): contact_detail1 = dict(**TEST_CONTACT_DETAIL) contact_detail2 = ContactDetail( **contact_detail1 ) wifi_config1 = dict(**TEST_WIFI_CONFIG) wifi_config2 = WifiConfig( **wifi_config1 ) google_maps_coordinates = Coordinates(latitude=586000.32, longitude=250954.19) geolocation_coordinates = Coordinates(latitude=586000.32, longitude=250954.19, altitude=500) tag_prefix = 'qr_for_' if embedded else 'qr_url_for_' tag_args = dict(image_format=image_format) if image_format == 'png': tag_args['size'] = 't' if not embedded: # Deactivate cache for URL. tag_args['cache_enabled'] = False raw_data = ( ('email', '"john.doe@domain.com"', None), ('tel', ' "+41769998877"', None), ('sms', ' "+41769998877"', None), ('geolocation', 'latitude=586000.32 longitude=250954.19 altitude=500', None), ('geolocation', 'coordinates=coordinates', {'coordinates': geolocation_coordinates}), ('google_maps', 'latitude=586000.32 longitude=250954.19', None), ('google_maps', 'coordinates=coordinates', {'coordinates': google_maps_coordinates}), ('wifi', 'wifi_config', {'wifi_config': wifi_config1}), ('wifi', 'wifi_config', {'wifi_config': wifi_config2}), ('wifi', 'wifi_config=wifi_config', {'wifi_config': wifi_config2}), ('contact', 'contact_detail', {'contact_detail': contact_detail1}), ('contact', 'contact_detail', {'contact_detail': contact_detail2}), ('contact', 'contact_detail=contact_detail', {'contact_detail': contact_detail2}), ('youtube', '"J9go2nj6b3M"', None), ('youtube', 'video_id', {'video_id': "J9go2nj6b3M"}), ('google_play', '"ch.admin.meteoswiss"', None), ) tests_data = [] for tag_base_name, tag_data, template_context in raw_data: test_data = TestQRForApplications._make_test_data(tag_pattern='%s%s %s' % (tag_prefix, tag_base_name, tag_data), ref_file_name='qr_for_%s' % tag_base_name, tag_args=tag_args, template_context=template_context) tests_data.append(test_data) return tests_data @staticmethod def _get_rendered_template(template_source, template_context): html_source = mark_safe('{% load qr_code %}' + template_source) template = Template(html_source) context = Context() if template_context: context.update(template_context) return template.render(context).strip() def test_demo_samples_embedded_in_svg_format(self): tests_data = self._make_tests_data(embedded=True) for test_data in tests_data: print('Testing template: %s' % test_data['source']) source_image_data = TestQRForApplications._get_rendered_template(test_data['source'], test_data.get('template_context')) if REFRESH_REFERENCE_IMAGES: write_svg_content_to_file(test_data['ref_file_name'], source_image_data) ref_image_data = get_svg_content_from_file_name(test_data['ref_file_name']) self.assertEqual(source_image_data, ref_image_data) def test_demo_samples_embedded_in_png_format(self): tests_data = self._make_tests_data(embedded=True, image_format='png') for test_data in tests_data: print('Testing template: %s' % test_data['source']) source_image_data = TestQRForApplications._get_rendered_template(test_data['source'], test_data.get('template_context')) match = IMAGE_TAG_BASE64_DATA_RE.search(source_image_data) source_image_data = match.group('data') source_image_data = base64.b64decode(source_image_data) if REFRESH_REFERENCE_IMAGES: write_png_content_to_file(test_data['ref_file_name'], source_image_data) ref_image_data = get_png_content_from_file_name(test_data['ref_file_name']) self.assertEqual(source_image_data, ref_image_data) def test_demo_sample_urls_in_svg_format(self): tests_data = self._make_tests_data(embedded=False) for test_data in tests_data: source_image_data = self._check_url_for_test_data(test_data).content.decode('utf-8') if REFRESH_REFERENCE_IMAGES: write_svg_content_to_file(test_data['ref_file_name'], source_image_data) ref_image_data = get_svg_content_from_file_name(test_data['ref_file_name']) self.assertEqual(minimal_svg(source_image_data), minimal_svg(ref_image_data)) def test_demo_sample_urls_in_png_format(self): tests_data = self._make_tests_data(embedded=False, image_format='png') for test_data in tests_data: source_image_data = self._check_url_for_test_data(test_data).content if REFRESH_REFERENCE_IMAGES: write_png_content_to_file(test_data['ref_file_name'], source_image_data) ref_image_data = get_png_content_from_file_name(test_data['ref_file_name']) self.assertEqual(source_image_data, ref_image_data) def _check_url_for_test_data(self, test_data): print('Testing template: %s' % test_data['source']) source_image_url = TestQRForApplications._get_rendered_template(test_data['source'], test_data.get('template_context')) response = self.client.get(source_image_url) self.assertEqual(response.status_code, 200) return response class TestIssues(SimpleTestCase): def test_reverse_lazy_url(self): from django.urls import reverse, reverse_lazy options = QRCodeOptions(image_format='svg', size=1) url1 = make_qr_code_url(reverse('qr_code:serve_qr_code_image'), options) url2 = make_qr_code_url(reverse_lazy('qr_code:serve_qr_code_image'), options) self.assertEqual(url1, url2) svg1 = make_embedded_qr_code(reverse('qr_code:serve_qr_code_image'), options) svg2 = make_embedded_qr_code(reverse_lazy('qr_code:serve_qr_code_image'), options) self.assertEqual(svg1, svg2) class TestWriteResourceData(SimpleTestCase): resource_file_base_name = 'TestWriteResourceData' def test_write_svg(self): response = self.client.get(make_qr_code_url(TEST_TEXT)) image_data = response.content.decode('utf-8') write_svg_content_to_file(TestWriteResourceData.resource_file_base_name, image_data) file_path_to_remove = os.path.join(get_resources_path(), TestWriteResourceData.resource_file_base_name + SVG_REF_SUFFIX) os.remove(file_path_to_remove) def test_write_png(self): response = self.client.get(make_qr_code_url(TEST_TEXT)) image_data = response.content write_png_content_to_file(TestWriteResourceData.resource_file_base_name, image_data) file_path_to_remove = os.path.join(get_resources_path(), TestWriteResourceData.resource_file_base_name + PNG_REF_SUFFIX) os.remove(file_path_to_remove) def get_svg_content_from_file_name(base_file_name): with open(os.path.join(get_resources_path(), base_file_name + SVG_REF_SUFFIX), 'r', encoding='utf-8') as file: return file.read() def get_png_content_from_file_name(base_file_name): with open(os.path.join(get_resources_path(), base_file_name + PNG_REF_SUFFIX), 'rb') as file: return file.read() def write_svg_content_to_file(base_file_name, image_content): with open(os.path.join(get_resources_path(), base_file_name + SVG_REF_SUFFIX), 'wt', encoding='utf-8') as file: file.write(image_content) def write_png_content_to_file(base_file_name, image_content): with open(os.path.join(get_resources_path(), base_file_name + PNG_REF_SUFFIX), 'wb') as file: file.write(image_content) django-qr-code-2.2.0/qr_code/urls.py000066400000000000000000000004201405664203600172620ustar00rootroot00000000000000from django.conf import settings from django.urls import path from qr_code import views app_name = 'qr_code' urlpatterns = [ path(getattr(settings, 'SERVE_QR_CODE_IMAGE_PATH', 'images/serve-qr-code-image/'), views.serve_qr_code_image, name='serve_qr_code_image') ] django-qr-code-2.2.0/qr_code/views.py000066400000000000000000000100651405664203600174400ustar00rootroot00000000000000import base64 import binascii import functools from django.conf import settings from django.core.exceptions import PermissionDenied, SuspiciousOperation from django.core.signing import BadSignature, Signer from django.http import HttpResponse from django.views.decorators.cache import cache_page from django.views.decorators.http import condition from qr_code.qrcode import constants from qr_code.qrcode.maker import make_qr_code_image from qr_code.qrcode.utils import QRCodeOptions from qr_code.qrcode.serve import get_url_protection_options, \ get_qr_url_protection_token, qr_code_etag, \ qr_code_last_modified, allows_external_request_from_user def cache_qr_code(): """ Decorator that caches the requested page if a settings named 'QR_CODE_CACHE_ALIAS' exists and is not empty or None. """ def decorator(view_func): @functools.wraps(view_func) def _wrapped_view(request, *view_args, **view_kwargs): cache_enabled = request.GET.get('cache_enabled', True) if cache_enabled and hasattr(settings, 'QR_CODE_CACHE_ALIAS') and settings.QR_CODE_CACHE_ALIAS: # We found a cache alias for storing the generate qr code and cache is enabled, use it to cache the # page. timeout = settings.CACHES[settings.QR_CODE_CACHE_ALIAS]['TIMEOUT'] key_prefix = 'token=%s.user_pk=%s' % (request.GET.get('url_signature_enabled') or constants.DEFAULT_URL_SIGNATURE_ENABLED, request.user.pk) response = cache_page(timeout, cache=settings.QR_CODE_CACHE_ALIAS, key_prefix=key_prefix)(view_func)(request, *view_args, **view_kwargs) else: # No cache alias for storing the generated qr code, call the view as is. response = (view_func)(request, *view_args, **view_kwargs) return response return _wrapped_view return decorator @condition(etag_func=qr_code_etag, last_modified_func=qr_code_last_modified) @cache_qr_code() def serve_qr_code_image(request) -> HttpResponse: """Serve an image that represents the requested QR code.""" qr_code_options = get_qr_code_option_from_request(request) # Handle image access protection (we do not allow external requests for anyone). check_image_access_permission(request, qr_code_options) try: text = base64.b64decode(request.GET.get('text', '')).decode(encoding='utf-8') except binascii.Error: raise SuspiciousOperation("Invalid base64 encoded string.") img = make_qr_code_image(text, qr_code_options=qr_code_options) return HttpResponse(content=img, content_type='image/svg+xml' if qr_code_options.image_format == 'svg' else 'image/png') def get_qr_code_option_from_request(request) -> QRCodeOptions: request_query = request.GET.dict() for key in ('text', 'token', 'cache_enabled'): request_query.pop(key, None) return QRCodeOptions(**request_query) def check_image_access_permission(request, qr_code_options) -> None: """Handle image access protection (we do not allow external requests for anyone).""" token = request.GET.get('token', '') if token: check_url_signature_token(qr_code_options, token) else: if not allows_external_request_from_user(request.user): raise PermissionDenied("You are not allowed to access this QR code.") def check_url_signature_token(qr_code_options, token) -> None: url_protection_options = get_url_protection_options() signer = Signer(key=url_protection_options[constants.SIGNING_KEY], salt=url_protection_options[constants.SIGNING_SALT]) try: # Check signature. url_protection_string = signer.unsign(token) # Check that the given token matches the request parameters. random_token = url_protection_string.split('.')[-1] if get_qr_url_protection_token(qr_code_options, random_token) != url_protection_string: raise PermissionDenied("Request query does not match protection token.") except BadSignature: raise PermissionDenied("Wrong token signature.") django-qr-code-2.2.0/qr_code_demo/000077500000000000000000000000001405664203600167335ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code_demo/__init__.py000066400000000000000000000000001405664203600210320ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code_demo/apps.py000066400000000000000000000002151405664203600202460ustar00rootroot00000000000000from django.apps import AppConfig class QRCodeDemoConfig(AppConfig): name = 'qr_code_demo' verbose_name = 'Demo of Django QR Code' django-qr-code-2.2.0/qr_code_demo/migrations/000077500000000000000000000000001405664203600211075ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code_demo/migrations/__init__.py000066400000000000000000000000001405664203600232060ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code_demo/templates/000077500000000000000000000000001405664203600207315ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code_demo/templates/qr_code_demo/000077500000000000000000000000001405664203600233515ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code_demo/templates/qr_code_demo/index.html000066400000000000000000000532121405664203600253510ustar00rootroot00000000000000 {% load qr_code %} Demo Site of django-qr-code {% block content %}

Django QR Code Demo Site

This is a demo site for the Django QR Code application.

Latest PyPI Version Documentation Status Build Status Coverage Status

Image Formats

The SVG is the default image format. It is a vector image format so it can be scaled as wanted. 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 now and it will work properly on any modern web browser.

Examples of qr_from_text Usages

The qr_from_text tag renders an inline QR code within your Django template. It comes with several options to customize the image format (SVG or PNG), the size, the border and the matrix size.

A tiny "hello world" QR code in SVG format (default format)

A tiny "hello world" QR code in PNG format

A small "hello world" QR code

Template code:
{% templatetag openblock %} qr_from_text "Hello World!" size="T" image_format="svg" {% templatetag closeblock %} {% templatetag openblock %} qr_from_text "Hello World!" size="T" image_format="png" {% templatetag closeblock %} {% templatetag openblock %} qr_from_text "Hello World!" size="S" {% templatetag closeblock %}
{% qr_from_text "Hello World!" size="T" image_format="svg" %}
{% qr_from_text "Hello World!" size="T" image_format="png" %}
{% qr_from_text "Hello World!" size="S" %}


A medium "hello world" QR code (default size) with level H of error correction (up to 30% damage)

A large "hello world" QR code with level L of error correction (up to 7% damage)

A huge "hello world" QR code with level M of error correction (default level, up to 15% damage)

Template code:
{% templatetag openblock %} qr_from_text "Hello World!" size="M" error_correction="H" {% templatetag closeblock %} {% templatetag openblock %} qr_from_text "Hello World!" size="L" error_correction="L" {% templatetag closeblock %} {% templatetag openblock %} qr_from_text "Hello World!" size="H" error_correction="M" {% templatetag closeblock %}
{% qr_from_text "Hello World!" size="M" error_correction="H" %}
{% qr_from_text "Hello World!" size="L" error_correction="L" %}
{% qr_from_text "Hello World!" size="H" error_correction="M" %}


A custom "hello world" QR code with size 8 and version 12 and dark modules in dark green finder and alignment patterns in black

A custom "hello world" QR code with size 10 and border 6

A custom "hello world" QR code using a QRCodeOptions instance. Here the QRCodeOptions instance has a size t, a border of 6 modules, and a level L of error correction (up to 7% damage).

Template code:
{% templatetag openblock %} qr_from_text "Hello World!" size=8 version=12 dark_color="darkgreen" finder_dark_color="#000" alignment_dark_color="#000" {% templatetag closeblock %} {% templatetag openblock %} qr_from_text "Hello World!" size=10 border=6 {% templatetag closeblock %} {% templatetag openblock %} qr_from_text "Hello World!" options=options_example {% templatetag closeblock %}
{% qr_from_text "Hello World!" size=8 version=12 dark_color="darkgreen" finder_dark_color="#000" alignment_dark_color="#000" %}
{% qr_from_text "Hello World!" size=10 border=6 %}
{% qr_from_text "Hello World!" options=options_example %}

Micro QR Codes

Micro QR Codes are generated if either version or micro indicate that a Micro QR Code is preferred.

{% templatetag openblock %} qr_from_text "Hello World!" size=8 dark_color="darkgreen" finder_dark_color="#000" alignment_dark_color="#000" micro=True {% templatetag closeblock %} {% templatetag openblock %} qr_from_text "Hello World!" size=20 border=6 version='M4' data_dark_color='#4B0082' {% templatetag closeblock %}
{% qr_from_text "Hello World!" size=8 dark_color="darkgreen" finder_dark_color="#000" alignment_dark_color="#000" micro=True %}
{% qr_from_text "Hello World!" size=20 border=6 version='M4' data_dark_color='#4B0082' %}

Examples of qr_url_from_text Usages

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.

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:

from django.conf.urls import include, url from qr_code import urls as qr_code_urls urlpatterns = [ path('qr_code/', include(qr_code_urls, namespace="qr_code")), ]

A medium "hello world" QR code that uses an URL to serve the image in SVG format

A "hello world" QR code in version 10 that uses an URL to serve the image in PNG format

A "hello world" QR code in version 20 that uses an URL to serve the image in SVG format, and disable caching for served image

Template code:
<img src="{% templatetag openblock %} qr_url_from_text "Hello World!" dark_color="darkblue" {% templatetag closeblock %}" alt="Hello World!"> <img src="{% templatetag openblock %} qr_url_from_text "Hello World!" size=8 version=10 image_format='png' dark_color="darkred" finder_dark_color="#000" {% templatetag closeblock %}" alt="Hello World!"> <img src="{% templatetag openblock %} qr_url_from_text "Hello World!" size=8 version=20 cache_enabled=False {% templatetag closeblock %}" alt="Hello World!">
Hello World!
Hello World!
Hello World!

QR Codes for Applications

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 email to a given address, add a contact to your phone book, connect to a Wi-Fi, start a SMS, etc. See this documentation 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.

Start an email

Template code:
{% templatetag openblock %} qr_for_email "john.doe@domain.com" {% templatetag closeblock %} <img src="{% templatetag openblock %} qr_url_for_email "john.doe@domain.com" {% templatetag closeblock %}">
{% qr_for_email 'john.doe@domain.com' %}

Compose a phone number

Template code:
{% templatetag openblock %} qr_for_tel "+41769998877" {% templatetag closeblock %} <img src="{% templatetag openblock %} qr_url_for_tel "+41769998877" {% templatetag closeblock %}">
{% qr_for_tel '+41769998877' %}

Start a SMS

Template code:
{% templatetag openblock %} qr_for_sms "+41769998877" {% templatetag closeblock %} <img src="{% templatetag openblock %} qr_url_for_sms "+41769998877" {% templatetag closeblock %}">
{% qr_for_sms '+41769998877' %}

Display a geolocation on default map app

Template code:
{% templatetag openblock %} qr_for_geolocation latitude=586000.32 longitude=250954.19 altitude=500{% templatetag closeblock %} <img src="{% templatetag openblock %} qr_url_for_geolocation latitude=586000.32 longitude=250954.19 altitude=500 {% templatetag closeblock %}">
{% qr_for_geolocation latitude=586000.32 longitude=250954.19 altitude=500 %}
Template code:
{% templatetag openblock %} qr_for_geolocation coordinates=geolocation_coordinates {% templatetag closeblock %} <img src="{% templatetag openblock %} qr_url_for_geolocation coordinates=geolocation_coordinates {% templatetag closeblock %}">
{% qr_for_geolocation coordinates=geolocation_coordinates %}

Display a geolocation on Google Maps

Template code:
{% templatetag openblock %} qr_for_google_maps latitude=586000.32 longitude=250954.19 {% templatetag closeblock %} <img src="{% templatetag openblock %} qr_url_for_google_maps latitude=586000.32 longitude=250954.19 {% templatetag closeblock %}">
{% qr_for_google_maps latitude=586000.32 longitude=250954.19 %}
Template code:
{% templatetag openblock %} qr_for_google_maps coordinates=google_maps_coordinates {% templatetag closeblock %} <img src="{% templatetag openblock %} qr_url_for_google_maps coordinates=google_maps_coordinates{% templatetag closeblock %}">
{% qr_for_google_maps coordinates=google_maps_coordinates %}

Configure Wi-Fi connexion

Template code:
{% templatetag openblock %} qr_for_wifi wifi_config {% templatetag closeblock %} <img src="{% templatetag openblock %} qr_url_for_wifi wifi_config {% templatetag closeblock %}">
{% qr_for_wifi wifi_config %}
Template code:
{% templatetag openblock %} qr_for_wifi wifi_config=wifi_config {% templatetag closeblock %} <img src="{% templatetag openblock %} qr_url_for_wifi wifi_config=wifi_config {% templatetag closeblock %}">
{% qr_for_wifi wifi_config=wifi_config %}
Template code:
{% templatetag openblock %} qr_for_wifi wifi_config options=options_example {% templatetag closeblock %} <img src="{% templatetag openblock %} qr_url_for_wifi wifi_config options=options_example {% templatetag closeblock %}">
{% qr_for_wifi wifi_config options=options_example %}

Add contact to phone book

Template code:
{% templatetag openblock %} qr_for_contact contact_detail {% templatetag closeblock %} <img src="{% templatetag openblock %} qr_url_for_contact contact_detail {% templatetag closeblock %}">
{% qr_for_contact contact_detail %}
Template code:
{% templatetag openblock %} qr_for_contact contact_detail=contact_detail {% templatetag closeblock %} <img src="{% templatetag openblock %} qr_url_for_contact contact_detail=contact_detail {% templatetag closeblock %}">
{% qr_for_contact contact_detail=contact_detail %}

Watch a YouTube video

Template code:
{% templatetag openblock %} qr_for_youtube 'J9go2nj6b3M' {% templatetag closeblock %} <img src="{% templatetag openblock %} qr_url_for_youtube 'J9go2nj6b3M' {% templatetag closeblock %}">
{% qr_for_youtube 'J9go2nj6b3M' %}
Template code:
{% templatetag openblock %} qr_for_youtube video_id {% templatetag closeblock %} <img src="{% templatetag openblock %} qr_url_for_youtube video_id {% templatetag closeblock %}">
{% qr_for_youtube video_id %}

Open a Google Play app page

Template code:
{% templatetag openblock %} qr_for_google_play 'ch.admin.meteoswiss' {% templatetag closeblock %} <img src="{% templatetag openblock %} qr_url_for_google_play 'ch.admin.meteoswiss' {% templatetag closeblock %}">
{% qr_for_google_play 'ch.admin.meteoswiss' %}
Template code:
{% templatetag openblock %} qr_for_google_play 'ch.admin.meteoswiss' options=options_example {% templatetag closeblock %} <img src="{% templatetag openblock %} qr_url_for_google_play 'ch.admin.meteoswiss' options=options_example {% templatetag closeblock %}">
{% qr_for_google_play 'ch.admin.meteoswiss' options=options_example %}
{% endblock %} django-qr-code-2.2.0/qr_code_demo/tests.py000066400000000000000000000000001405664203600204350ustar00rootroot00000000000000django-qr-code-2.2.0/qr_code_demo/urls.py000066400000000000000000000003401405664203600202670ustar00rootroot00000000000000from django.urls import path, include from qr_code_demo import views app_name = "qr_code_demo" urlpatterns = [ path('', views.index, name='index'), path('qr-code/', include('qr_code.urls', namespace="qr_code")), ] django-qr-code-2.2.0/qr_code_demo/views.py000066400000000000000000000031361405664203600204450ustar00rootroot00000000000000from datetime import date from django.shortcuts import render from qr_code.qrcode.utils import ContactDetail, WifiConfig, Coordinates, QRCodeOptions # Use a ContactDetail instance to encapsulate the detail of the contact. DEMO_CONTACT = ContactDetail( first_name='John', last_name='Doe', first_name_reading='jAAn', last_name_reading='dOH', tel='+41769998877', email='j.doe@company.com', url='http://www.company.com', birthday=date(year=1985, month=10, day=2), address='Cras des Fourches 987, 2800 Delémont, Jura, Switzerland', memo='Development Manager', org='Company Ltd', ) # Use a WifiConfig instance to encapsulate the configuration of the connexion. DEMO_WIFI = WifiConfig( ssid='my-wifi', authentication=WifiConfig.AUTHENTICATION.WPA, password='wifi-password' ) DEMO_COORDINATES = Coordinates(latitude=586000.32, longitude=250954.19, altitude=500) DEMO_OPTIONS = QRCodeOptions(size='t', border=6, error_correction='L') def index(request): """ Build the home page of this demo app. :param request: :return: HTTP response providing the home page of this demo app. """ # Build context for rendering QR codes. context = dict( contact_detail=DEMO_CONTACT, wifi_config=DEMO_WIFI, video_id='J9go2nj6b3M', google_maps_coordinates=DEMO_COORDINATES, geolocation_coordinates=DEMO_COORDINATES, options_example=DEMO_OPTIONS ) # Render the index page. return render(request, 'qr_code_demo/index.html', context=context) django-qr-code-2.2.0/readthedocs.yml000066400000000000000000000003421405664203600173220ustar00rootroot00000000000000# Required version: 2 build: image: latest # Build all formats formats: all python: version: 3.7 install: - method: pip path: . extra_requirements: - docs - method: setuptools path: .django-qr-code-2.2.0/requirements-dev.txt000066400000000000000000000000421405664203600203470ustar00rootroot00000000000000twine coverage mypy django-stubs django-qr-code-2.2.0/requirements-web-deployment.txt000066400000000000000000000000371405664203600225300ustar00rootroot00000000000000gunicorn==20.1.0 brotli==1.0.9 django-qr-code-2.2.0/requirements.txt000066400000000000000000000000341405664203600175740ustar00rootroot00000000000000django>=2.2.17 segno>=1.3.1 django-qr-code-2.2.0/scripts/000077500000000000000000000000001405664203600160025ustar00rootroot00000000000000django-qr-code-2.2.0/scripts/generate-pypi-release.sh000077500000000000000000000004241405664203600225300ustar00rootroot00000000000000#!/usr/bin/env bash ( python -m pip install --upgrade pip pip install --upgrade setuptools wheel twine cd ../ rm -r build/ dist/ django_qr_code.egg-info/ python setup.py check && python setup.py sdist && python setup.py bdist_wheel && twine upload dist/* )django-qr-code-2.2.0/scripts/run-demo-app.sh000077500000000000000000000004131405664203600206430ustar00rootroot00000000000000#!/usr/bin/env bash set -e cd .. echo --- Build stage test container docker-compose down || true docker-compose build --build-arg PYTHON_VERSION=3.8 echo --- Fire up staging site docker-compose up -d --remove-orphans echo --- Listing containers docker-compose ps django-qr-code-2.2.0/scripts/run-tests.sh000077500000000000000000000042511405664203600203070ustar00rootroot00000000000000#!/usr/bin/env bash output_folder_name=tests_result if [ -d "../${output_folder_name}" ]; then mv "../${output_folder_name}" "../${output_folder_name}.back" fi mkdir -p "../${output_folder_name}" log_file_name=log.txt ( cd ../ echo "--- Run type checking" pip install -r requirements-dev.txt mypy qr_code if [ $? -ne 0 ]; then echo echo --- Failed type checking. Abort tests! exit 1 else echo echo --- Type checking OK! echo fi echo "--- Tests started on $(date)on $(hostname) ($(uname -a))" echo "--- Computer: $(hostname) ($(uname -a), CPU: $(nproc --all)" echo "--- CPU: $(nproc --all)" echo "--- RAM: $(free -h)" python_versions=("3.6 3.7 3.8 3.9") django_versions=("2.2.23" "3.1.11" "3.2.4") for python_version in ${python_versions[@]} do DOCKER_COMPOSE_COMMAND="docker-compose -f docker-compose.yml" for django_version in ${django_versions[@]} do ${DOCKER_COMPOSE_COMMAND} down build_cmd="${DOCKER_COMPOSE_COMMAND} build --build-arg PYTHON_VERSION=${python_version}" echo --- Build test container for Python ${python_version}: "${build_cmd}" ${build_cmd} echo --- Testing against: Python ${python_version} and Django ${django_version} ${DOCKER_COMPOSE_COMMAND} up -d echo --- Force Django version ${DOCKER_COMPOSE_COMMAND} exec django-qr-code pip install --upgrade "django~=${django_version}" echo Output code for tests with Python ${python_version} and Django ${django_version}: $? echo --- Setup test environment ${DOCKER_COMPOSE_COMMAND} exec django-qr-code python manage.py collectstatic --noinput # Run tests ${DOCKER_COMPOSE_COMMAND} exec django-qr-code python -Wd manage.py test | tee "${output_folder_name}/python_${python_version}-django_${django_version}-${log_file_name}" echo --- Stop containers and remove them. ${DOCKER_COMPOSE_COMMAND} down done done wait echo "--- Tests finished at $(date)" ) | tee "../${output_folder_name}/${log_file_name}" django-qr-code-2.2.0/setup.py000066400000000000000000000030651405664203600160310ustar00rootroot00000000000000import re from setuptools import setup # Get version without importing with open('qr_code/__init__.py', 'rb') as f: VERSION = str(re.search('__version__ = \'(.+?)\'', f.read().decode('utf-8')).group(1)) setup( name='django-qr-code', version=VERSION, packages=['qr_code', 'qr_code.qrcode', 'qr_code.templatetags'], url='https://github.com/dprog-philippe-docourt/django-qr-code', license='BSD 3-clause', author='Philippe Docourt', author_email='philippe@docourt.ch', maintainer='Philippe Docourt', description='An application that provides tools for displaying QR codes on your Django site.', long_description="""This application provides tools for displaying QR codes on your `Django `_ site. This application depends on the `Segno QR Code generator `_. This app makes no usage of the Django models and therefore do not use any database. Only Python >= 3.6 is supported.""", install_requires=['segno', 'django>=2.2'], python_requires='>=3', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Internet :: WWW/HTTP', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 3 :: Only', 'Framework :: Django :: 2.2', 'Framework :: Django :: 3.0', 'Framework :: Django :: 3.1', 'Natural Language :: English' ], keywords='qr code django', )