Dynamic QR Code Generator

Project Structure

dynamic_qr/

├── app.py

├── templates/

│   ├── index.html

│   ├── qr_display.html

│   ├── update.html

└── qr_data.db



 app.py

from flask import Flask, render_template, request, redirect, url_for

import qrcode

import sqlite3

import io, base64


app = Flask(__name__)

DB = 'qr_data.db'


# --- Initialize Database ---

def init_db():

    conn = sqlite3.connect(DB)

    c = conn.cursor()

    c.execute('''CREATE TABLE IF NOT EXISTS qr_links (

                    id INTEGER PRIMARY KEY AUTOINCREMENT,

                    code TEXT UNIQUE,

                    target_url TEXT

                )''')

    conn.commit()

    conn.close()


init_db()


# --- Generate Dynamic QR ---

@app.route('/', methods=['GET', 'POST'])

def index():

    if request.method == 'POST':

        link = request.form['link']

        code = str(hash(link))[-6:]  # simple code for uniqueness

        short_url = request.host_url + "r/" + code


        conn = sqlite3.connect(DB)

        c = conn.cursor()

        c.execute("INSERT OR REPLACE INTO qr_links (code, target_url) VALUES (?,?)", (code, link))

        conn.commit()

        conn.close()


        # Generate QR

        img = qrcode.make(short_url)

        buf = io.BytesIO()

        img.save(buf, format='PNG')

        qr_base64 = base64.b64encode(buf.getvalue()).decode('utf-8')


        return render_template('qr_display.html', qr_img=qr_base64, short_url=short_url)

    return render_template('index.html')



# --- Redirect Handler ---

@app.route('/r/<code>')

def redirect_qr(code):

    conn = sqlite3.connect(DB)

    c = conn.cursor()

    c.execute("SELECT target_url FROM qr_links WHERE code=?", (code,))

    row = c.fetchone()

    conn.close()

    if row:

        return redirect(row[0])

    return "QR link not found!", 404



# --- Update Target URL ---

@app.route('/update', methods=['GET', 'POST'])

def update_qr():

    if request.method == 'POST':

        code = request.form['code']

        new_link = request.form['new_link']

        conn = sqlite3.connect(DB)

        c = conn.cursor()

        c.execute("UPDATE qr_links SET target_url=? WHERE code=?", (new_link, code))

        conn.commit()

        conn.close()

        return " Updated successfully!"

    return render_template('update.html')



if __name__ == "__main__":

    app.run(debug=True)

templates/index.html

<!DOCTYPE html>
<html>
<head>
    <title>Dynamic QR Generator</title>
</head>
<body>
    <h2> Generate Dynamic QR Code</h2>
    <form method="POST">
        <input type="text" name="link" placeholder="Enter destination URL" required>
        <button type="submit">Generate QR</button>
    </form>
    <br>
    <a href="/update">Update existing QR link</a>
</body>
</html>

templates/qr_display.html

<!DOCTYPE html>
<html>
<head><title>QR Generated</title></head>
<body>
    <h2> Your Dynamic QR Code</h2>
    <img src="data:image/png;base64,{{ qr_img }}" alt="QR Code"><br>
    <p>Share this link: <b>{{ short_url }}</b></p>
    <a href="/">Generate another</a>
</body>
</html>
templates/update.html

<!DOCTYPE html>
<html>
<head><title>Update QR Link</title></head>
<body>
    <h2>Update QR Destination</h2>
    <form method="POST">
        <input type="text" name="code" placeholder="Enter QR code ID" required><br><br>
        <input type="text" name="new_link" placeholder="Enter new destination URL" required><br><br>
        <button type="submit">Update</button>
    </form>
</body>
</html>

No comments: