#!/usr/bin/env python3 import bottle import io import qrcode import qrcode.image.styledpil as qrstyled import sqlite3 application = bottle.default_app() connection = sqlite3.connect("db.sqlite") cursor = connection.cursor() cursor.execute( """ CREATE TABLE IF NOT EXISTS visitors ( id INTEGER PRIMARY KEY AUTOINCREMENT, event TEXT, time DATETIME, name TEXT, address TEXT, contact TEXT ); """ ) def url(route): return "%s://%s/%s" % ( bottle.request.urlparts.scheme, bottle.request.urlparts.netloc, route, ) @application.get("/") @bottle.view("template/new.tpl") def new_get(): pass @application.post("/") @bottle.view("template/new.tpl") def new_post(): event = bottle.request.forms.get("event", "") if event: bottle.redirect(url("qr/" + event)) return dict(event=event, feedback=True) @application.get("/static/") def static_get(file): return bottle.static_file(file, root="static") @application.get("/qr/") @bottle.view("template/qr.tpl") def qr_get(event): return dict(event=event, url=url("event/" + event)) @application.get("/qr/img/.png") def qr_img_get(event): qr = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=20) qr.add_data(url("event/" + event)) image = qr.make_image( image_factory=qrstyled.StyledPilImage, embeded_image_path="heizhaus_logo_square.png", ) buffer = io.BytesIO() image.save(buffer, format="PNG") bottle.response.content_type = "image/png" return buffer.getvalue() @application.get("/event/") @bottle.view("template/event.tpl") def event_get(event): return dict(event=event) @application.post("/event/") @bottle.view("template/event.tpl") def event_post(event): data = dict(feedback=True, success=True) for field in ("event", "name", "address", "contact"): data[field] = bottle.request.forms.get(field, "") data["success"] = data["success"] and data[field] if data["success"]: cursor.execute( """ INSERT INTO visitors (event, time, name, address, contact) VALUES (:event, datetime('now'), :name, :address, :contact); """, data, ) connection.commit() return data @application.get("/cleanup") def cleanup(): cursor.execute( """ DELETE FROM visitors WHERE time < datetime('now', '-1 month'); """ ) connection.commit() if __name__ == "__main__": bottle.run(host="0.0.0.0", port=8080) else: application.catchall = False