Freelancing for Pale Blue

Looking for flexible work opportunities that fit your schedule?


Generate a QR code programmatically in Python

Python Jan 28, 2023

Nowadays, QR codes are everywhere. From the restaurant menu to graffiti, it's the easiest way to place an internet link into the physical world.

There are countless websites only that allows you to create QR codes using their services. Some even offer an API to let you create a QR code programmatically. In case your Python/Django project needs a way to quickly create QR codes programmatically, an external API may be overkill.

You see, there are quite a few open-source Python libraries that offer this programmatic creation of QR codes with a few lines of code.

In this post, we'll show how to create programmatically a QR code and then download that code as an image.

Set up

The QR library that we will use in this post is qrcode. For image generation, we will use the popular pillow library. To install both of them in one line, just run:

pip install qrcode[pil]

Sample code

In the following snippet, we have a sample Django view that will generate and prompt the user to download a QR code in a PNG format that links to the URL of the current page.

class QrCodeView(View):

    def get(self, request):
        # 1.
        path = request.GET["path"]
        url = f"https://{get_current_site(self.request).domain}{path}"

        # 2.
        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4,
        )
        qr.add_data(url)
        qr.make(fit=True)
        
        # 3.
        img = qr.make_image(fill_color="black", back_color="white")
        temp_file = NamedTemporaryFile(delete=True)
        img.save(temp_file.name)

        # 4.
        response = HttpResponse(temp_file)
        response["Content-Disposition"] = f"attachment; filename=qr.png"
        return response
  1. This is how we get the absolute URL to the existing page. Remember that the usual Django utilities (e.g. reverse()) return relative URLs.
  2. We use the qrcode library to create the QR code in memory. The library offers multiple parameters to customize the generated QR code. These are some of the default ones, briefly explained:
    - version: Controls the size of the QR Code, version=1 is a 21x21 matrix.
    - error_correction: The amount of "backup" pixels to be added in the image in case there's a section that is dirty or damaged (more details).
    - box_size: Number of pixels for each "box" of the QR code.
    - border: How thick the border should be.
    I strongly urge you to check the library's documentation for a list of all the available parameters to customize your QR code.
  3. Use the pillow library to convert that QR code into a PNG image and store it in a temporary file.
  4. Prompt the user to download the PNG image file.

Hopefully, this was a quick and easy intro to how to create and download a QR code in Django programmatically.

Happy coding!

Tags

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.