""" handler.py a flask "blueprint" that handles the form, showing the results. """ from flask import Blueprint, render_template, request, g, session from formy.db import open_db from random import random bp = Blueprint("handler", __name__) def process_form(): """ Do whatever processing of the data needs to be done. Return a dictionary of stuff that the template can display. """ # read database into g['db'] open_db() # session dictionary encoded automatically in cookie # automatically using app.config['SECRET_KEY'] if 'id' not in session: # create a new user_id & store in session. session['id'] = str(random())[2:] # 0.123... => '123..' # Put this user_id into the database if it isn't there already. id = session['id'] if id not in g.db: g.db[id] = { 'username': '?', 'visits': 0 } # store stuff that we want to use on the webpage. # (Later pass this to the template for it to display.) stuff = { 'username' : g.db[id]['username'], 'visits' : g.db[id]['visits'], 'formname' : request.form.get('name', '') } # update name in database g.db[id]['username'] = request.form.get('name', '') # update visit count g.db[id]['visits'] = int(g.db[id]['visits']) + 1 # The database will be written out when the request terminates # because we've registered the db_close() function. # Flask automatically puts the session stuff into a cookie. return stuff @bp.route('/handler', methods=('POST',)) def handler(): stuff = process_form() # See https://flask.palletsprojects.com/en/1.1.x/templating/ # and https://jinja.palletsprojects.com/en/2.11.x/templates/ return render_template('handler.html', # in templates/ stuff=stuff # accessible in template )