From 73987737140b07c2a22f542fe23205b4d5bc560b Mon Sep 17 00:00:00 2001 From: Sage Vaillancourt Date: Sat, 31 Jul 2021 23:14:59 -0400 Subject: [PATCH] Cache the default rendered home page A bit hacky, since CLForm can't seem to initialize properly without being part of a request. To avoid a reference-before-assignment error, the INDEX variable is first initialized as a global in __init__.py. But it is definitely faster. Repeated renders take around 2ms each. Reading the cached value takes about 0.002ms. Also split index() into index_get() and index_post(), since GET calls always use the cached version, and POST calls never do. --- flaskr/__init__.py | 2 ++ writing.py | 16 +++++++++++++--- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/flaskr/__init__.py b/flaskr/__init__.py index 17955fe..a4a7a34 100644 --- a/flaskr/__init__.py +++ b/flaskr/__init__.py @@ -10,6 +10,8 @@ from flask import ( import writing +INDEX = None + def optimize_css(): import re root = os.path.dirname(os.getcwd()) diff --git a/writing.py b/writing.py index 8ff8d5d..71a14e7 100644 --- a/writing.py +++ b/writing.py @@ -5,6 +5,7 @@ from wtforms import Form, BooleanField, StringField, TextAreaField, validators import urllib.parse from latty import CLData +import flaskr writing_blueprint = Blueprint('writing', __name__,) @@ -47,10 +48,19 @@ class CLForm(Form): default=body_string ) -@writing_blueprint.route('/', methods=('GET', 'POST')) -def index(): +@writing_blueprint.route('/', methods=['GET']) +def index_get(): + if flaskr.INDEX == None: + flaskr.INDEX = render_template( + 'writing.html', + form=CLForm() + ) + return flaskr.INDEX + +@writing_blueprint.route('/', methods=['POST']) +def index_post(): form = CLForm(request.form) - if request.method == 'POST' and form.validate(): + if form.validate(): data = CLData( username=form.username.data, company=form.company.data,