import sqlite3 import random from flask import Flask, g, request, render_template, make_response app = Flask(__name__) def get_db(): db = getattr(g, '_database', None) if db is None: db = g._database = sqlite3.connect("./web.db") return db @app.route("/", methods = ['GET', 'POST']) def root(): db = get_db() user_cookie = request.cookies.get("userid") if user_cookie is None: user_cookie = str(random.randint(100000, 999999)) print(f"Userid was None, nieuw UID: {user_cookie}") if request.method == "POST": new_submission = request.form.get("text") print(f"insert into posts values ({user_cookie},'{new_submission}');") db.cursor().execute(f"insert into posts values ({user_cookie},'{new_submission}');") db.commit() posts = db.cursor().execute(f"select * from posts where userid = {user_cookie};").fetchall() resp = make_response(render_template('./index.html', posts=posts)) resp.set_cookie("userid",str(user_cookie)) return resp @app.teardown_appcontext def close_connection(exception): db = getattr(g, '_database', None) if db is not None: db.close()