Search code examples
pythonflaskqr-code

Creating a Flask app with a QR code that redirects to a specific endpoint


As title says I'm creating a Flask app with a QR code that redirects to a specific endpoint. When I manually visit the endpoint, it works, but when I scan the QR code, it doesn't redirect to the correct location.

from flask import Flask, request, redirect
import logging
from datetime import datetime
import qrcode

app = Flask(__name__)

logging.basicConfig(filename = 'device_info.log', level = logging.INFO)

@app.route('/redirect')
def redirect_to_youtube():
    device_info = {
        "timestamp": datetime.now().isoformat(),
        "ip_address": request.remote_addr,
        "user_agent": request.headers.get('User-Agent'),
    }

    logging.info(device_info)

    return redirect("https://www.youtube.com", code=302)

server_url = "http://127.0.0.1:5000/redirect"

qr = qrcode.QRCode(
    version = 1,
    error_correction = qrcode.constants.ERROR_CORRECT_L,
    box_size = 10,
    border = 4,
)

qr.add_data(server_url)
qr.make(fit = True)

img = qr.make_image(fill_color="black", back_color="white")

file_name = "redirect_qr_code.png"
img.save(file_name)

I checked that the Flask server is running, tested the endpoint manually, and it works. I also regenerated the QR code to ensure it points to the correct URL, but it still doesn't redirect properly.

The Flask server output indicates it's running on localhost:5000, but when I scan the QR code, it doesn't redirect as expected. I don't see any error messages in the console.


Solution

  • There are two things you need to do here.

    First, because you are using your iPhone to scan the QR code, your iPhone and your laptop must be in the same network. To access the server running on your laptop you need to enter your laptop's IP address in your iPhone's browser.

    Using 127.0.0.1 won't work. Because it is a loopback address which just points back to the device you are trying to reach with.

    So, to find the IP address of your laptop, just run ipconfig in the command line and look for IPv4 Address, something like 192.168.xx.xxx. Write this IP in your server_url variable.

    Finally, you have to make sure your flask server is publicly available. For this run flask run --host=0.0.0.0. With this your server will listen to all public IPs.