# 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](https://www.python.org/downloads/). 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](https://github.com/ivansing/qr-code-generator-app.git)

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:

```bash
cd qr-code-generator-app
```

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

```bash
mkdir static templates
```

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:

```bash
touch app.py
```

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:

```bash
touch templates/index.html
```

## **Step 2: Install libraries**

```bash
pip install qrcode Flask
```

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**
    

```python
import qrcode

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

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:**
    

```python
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)
```

* **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`](http://app.run)`(debug=True)` starts the app in debug mode for easy error tracing.
    

### **index.html**

```xml
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>QR Code Generator</title>
</head>
<body>
    <h1>QR Code Generator</h1>
    <form method="POST">
        <label for="data">Enter Text or a URL:</label>
        <input type="text" id="data" name="data" required>
        <button type="submit">Generate QR Code</button>
    </form>

    {% if qr_code %}
      <h2>Generated QR Code:</h2>
      <img src="{{ qr_code }}" alt="QR Code">
    {% endif %}  
  
</body>
</html>
```

* **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:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1728060151858/48aa1883-54a1-46b5-ac10-e0c21f2e0b6f.png align="center")

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

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1728060174568/aec5fd44-f8ec-41a5-9045-99e4627f0260.png align="center")

Now copy any page like: [`https://google.com`](https://google.com%60) and paste it in the input box and just press the button `Generate QR Code`:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1728060189869/69328596-badd-4af9-8f3e-edd60ce774e4.png align="center")

And here you have the result QR code image:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1728060267389/60b66e35-1bec-471e-9569-509eac021198.png align="center")

## **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

* [Python Official](https://www.python.org/downloads/)
    
* [Flask](https://flask.palletsprojects.com/en/3.0.x/)
    
* [qrcode](https://pypi.org/project/qrcode/)
