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)
No comments:
Post a Comment