DEV Community

Cover image for How to build a QR Generator using Flask and qrcode
IvanDev
IvanDev

Posted on

How to build a QR Generator using Flask and qrcode

Introduction

Have you ever wondered how to build a QR code generator? This is the right tutorial for you. If we want to build such a tool, we need to think about the right language, so guess which one? You got it: "Python," which is a general high-level language for building anything in this digital world and also physical robots (software).

Setting Up the Environment

Prerequisites:

  • Basic Python language

  • Code Editor

  • Basic command line

Step 1: Setting Up the Project

  • Install Python here. From the Python page, download the latest stable version of Python. Once you've downloaded the installation file, execute it, install it on your computer, and follow all the recommended prompts.

  • Clone the repository and move to it:

qr-code-generator-app

Your projects would then be located in paths like:

/home/your-username/Projects/my_project (Linux)

/Users/your-username/Projects/my_project (Mac)

  • Open VS Code at the top of the bar and press Terminal in the dropdown box. Select New Terminal.

  • For Windows using Linux subsystem WSL:

  • Open VS Code, press F1, and select connect to WSL.

  • Follow the previous steps from Linux/Mac.

Type the following command in the terminal:

cd qr-code-generator-app
Enter fullscreen mode Exit fullscreen mode

In the qr-code-generator-app type the following in the terminal:

mkdir static templates
Enter fullscreen mode Exit fullscreen mode

This action will create two directories at once static to store ouput qr code file image, and templates directory to show the UI index.html.

Let's create the files in the project's structure:

touch app.py
Enter fullscreen mode Exit fullscreen mode

That was the application's entry point because I'm using Flask as the server to display the UI index.html.

Next, create an index.html file in the templates directory:

touch templates/index.html
Enter fullscreen mode Exit fullscreen mode

Step 2: Install libraries

pip install qrcode Flask
Enter fullscreen mode Exit fullscreen mode

In the previous command, I'm using qrcode to generate PNG files and Flask to render the endpoint index.html

Step 3: Write the code

Import the libraries

import qrcode

from flask import Flask, request, render_template, send_file
Enter fullscreen mode Exit fullscreen mode

The code import our qrcode so we can generate our precious QR codes, Flask a web framework to create a simple web server, request helps handle incoming form data (data input from a user), render_template to render HTML templates, and finally the send_file to send files (generated QR code image) to the user.

Create Flask App:

import qrcode 
from flask import Flask, request, render_template, send_file 

app = Flask(__name__)

@app.route("/", methods=["GET", "POST"])
def generate_qr():
    if request.method == "POST":
        data = request.form["data"]
        qr_img = qrcode.make(data)

        qr_path = "static/qr_code.png"
        qr_img.save(qr_path)

        return send_file(qr_path, mimetype='image/png')

    return render_template("index.html")

if __name__ == "__main__":
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode
  • Flask App Setup: `app = Flask(name) initializes the web app.
  • Route Definition: @app.route("/", methods=["GET, POST"]) handles both GET and POST requests at the root URL.
  • Form Handling (POST): When the form is submitted(POST), the user input is fetched and a QR code is generated and saved as static/qr_code.png image file.
  • Send QR Code: The saved QR code is returned to the browser using send_file method.
  • Render HTML(GET): On a GET requests, the index.html template is rendered.
  • Run the App: app.run(debug=True) starts the app in debug mode for easy error tracing.

index.html

index.html image

  • HTML Structure: Basic webpage with UTF-8 encoding. Form: This provides a form where users can input text or a URL. It uses the POST method to send the input to the Flask app, and then the "Generate QR Code" button is clicked.
  • QR Code Display: After form submission, if a QR code is generated, it checks {% if qr_code %} and displays the QR code image the <img> tag. This uses Flask templating to dynamically insert the QR code image source {{ qr_code }}.

Test the App

Now that the app is done, I'm ready to show you how to test it, like copying and pasting a URL from any website that gives in return a QR image so you can scan it to send to other friends:

Again, if you did all the steps as I did before, type the following command in the same level directory qr-code-generator-app:

bash
python3 app.py

You will have the following output in the terminal:

Output terminal

So, open it in the browser, and you can see this result:

Server page qr

Now copy any page like: https://google.com and paste it in the input box and just press the button Generate QR Code:

Button qr generator

And here you have the result QR code image:

Generated QR code

Summary

This was a small tutorial, we build a simple Flask application that allows users to generate their own QR codes. The app accepts user input (text or a URL), converts it into QR code, and displays the generated QR code on the browser. We used the Flask framework for creating the web app, the qrcode library for generating QR codes, and basic HTML for the front-end form and displaying the output as template.

Conclusion

As we did this tutorial, we learned how to create a basic web app using Flask, it's an amazing framework for python dynamic pages and integrate a Python library qrcode to generate QR codes from user input. Moreover, we saw how to handle GET and POST requests, render HTML templates using Flask, and display images dynamically in a web application. This project demonstrated the simplicity and power of Flask for building lightweight web applications.

References

About the Author

Ivan Duarte is a backend developer with experience working freelance. He is passionate about web development and artificial intelligence and enjoys sharing their knowledge through tutorials and articles. Follow me on X, Github, and LinkedIn for more insights and updates.

Top comments (0)