DEV Community

RockAndNull
RockAndNull

Posted on • Originally published at rockandnull.com on

Generate a QR code programmatically in Python

Generate a QR code programmatically in Python

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]
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode
  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:
  3. version: Controls the size of the QR Code, version=1 is a 21x21 matrix.
  4. 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).
  5. box_size: Number of pixels for each "box" of the QR code.
  6. 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.
  7. Use the pillow library to convert that QR code into a PNG image and store it in a temporary file.
  8. 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!

Top comments (0)