Skip to main content

Building a URL Redirector in Python for Dynamic QR Codes

Β· 4 min read
Serhii Hrekov
software engineer, creator, artist, programmer, projects founder

If you print 1,000 posters with a QR code and the website URL changes next week, a "Static" QR code becomes a pile of wasted paper. The solution is a Dynamic QR code.

Instead of encoding your final destination (like myshop.com/promo-january), you encode a "Short URL" that you control (like myqr.link/offer). When a user scans it, your server looks up where offer should go today and redirects them instantly.

1. The Architecture of a Dynamic System​

A dynamic system requires three parts:

  1. The Database: Stores the "Key" (e.g., offer) and the "Target" (e.g., myshop.com/promo).
  2. The Redirector: A small web server (Flask) that listens for scans.
  3. The Generator: A script that points the QR code to your server.

2. The Backend: Flask + SQLite​

We will use Flask to handle the web traffic and SQLite to manage our links.

from flask import Flask, redirect, abort
import sqlite3

app = Flask(__name__)

def get_target_url(slug):
"""Lookup the destination URL from our database."""
conn = sqlite3.connect("links.db")
cursor = conn.cursor()
cursor.execute("SELECT target FROM redirects WHERE slug=?", (slug,))
result = cursor.fetchone()
conn.close()
return result[0] if result else None

@app.route('/<slug>')
def dynamic_redirect(slug):
"""The 'Entry Point' for the QR code."""
target = get_target_url(slug)
if target:
# 302 redirect means 'Found/Temporary'
# This tells browsers not to cache the destination
return redirect(target, code=302)
else:
return abort(404)

if __name__ == '__main__':
app.run(port=5000)


3. The Generator: Pointing to the Redirector​

When you generate the QR code, you no longer use your final website address. You use your server's address.

import qrcode

# Your server address (for local testing)
SERVER_BASE = "[http://127.0.0.1:5000/](http://127.0.0.1:5000/)"
LINK_KEY = "winter_sale"

# This code stays the same forever!
qr_data = f"{SERVER_BASE}{LINK_KEY}"
img = qrcode.make(qr_data)
img.save("dynamic_qr.png")


4. Updating the Destination​

To change where the code points, you simply run a SQL command. You do not need to regenerate the image.

-- To update the destination from old_site.com to new_site.com:
UPDATE redirects
SET target = '[https://newsite.com/february-deals](https://newsite.com/february-deals)'
WHERE slug = 'winter_sale';


πŸ“‘ Why This is Professional-Grade​

FeatureStatic QRDynamic QR
EditingImpossible after printingUnlimited updates anytime
TrackingBasic (via UTMs only)Advanced (Time, Location, Device)
Scan SpeedDense (long URLs slow scan)Clean (short URLs scan faster)
CostFree / One-timeRequires hosting / Database

πŸ“š Sources & Technical Refs​