Skip to content

Commit

Permalink
🧹 Update Flask and Jinja2 to the latest version (#5348)
Browse files Browse the repository at this point in the history
The advantage of upgrading will be that we'll have a new version of Jinja2, which we will be able to better template analysis on.

Some APIs have changed, and we've moved to vendoring `flask-commonmark` in since the original authors are not maintaining it anymore.

**How to test**

Everything should work the same.
  • Loading branch information
rix0rrr authored Apr 3, 2024
1 parent a796e40 commit 7350174
Show file tree
Hide file tree
Showing 3 changed files with 142 additions and 10 deletions.
14 changes: 7 additions & 7 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
redirect, request, send_file, url_for, jsonify,
send_from_directory, session)
from flask_babel import Babel, gettext
from flask_commonmark import Commonmark
from website.flask_commonmark import Commonmark
from flask_compress import Compress
from urllib.parse import quote_plus

Expand Down Expand Up @@ -76,7 +76,12 @@
# Use 5 minutes as a reasonable default for all files we load elsewise.
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = datetime.timedelta(minutes=5)

babel = Babel(app)

def get_locale():
return session.get("lang", request.accept_languages.best_match(ALL_LANGUAGES.keys(), 'en'))


babel = Babel(app, locale_selector=get_locale)

jinja_partials.register_extensions(app)
app.template_filter('tojson')(proper_tojson)
Expand Down Expand Up @@ -258,11 +263,6 @@ def load_customized_adventures(level, customizations, into_adventures):
into_adventures.append(adv)


@babel.localeselector
def get_locale():
return session.get("lang", request.accept_languages.best_match(ALL_LANGUAGES.keys(), 'en'))


cdn.Cdn(app, os.getenv('CDN_PREFIX'), os.getenv('HEROKU_SLUG_COMMIT', 'dev'))


Expand Down
6 changes: 3 additions & 3 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
Flask==2.3.2
Flask==3.0.2
Werkzeug==3.0.1
lark==1.1.1
gunicorn==21.2.0
flask-compress==1.4.0
requests==2.31.0
attrs>=22.2.0
Flask-Commonmark==1.0.4
bcrypt==3.2.0
boto3>=1.16.50
MarkupSafe==2.1.2
Expand All @@ -20,7 +19,7 @@ regex==2021.8.28
retrying==1.3.3
pytest==8.0.0
parameterized==0.8.1
Flask-Babel==2.0.0
Flask-Babel==4.0.0
iso3166~=2.0.2
turtlethread>=0.0.6
pre-commit==2.20.0
Expand All @@ -34,3 +33,4 @@ doit==0.36.0
doit_watch>=0.1.0
uflash>=2.0.0
pyinstaller==6.3.0
commonmark==0.9.1
132 changes: 132 additions & 0 deletions website/flask_commonmark.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
# -*- coding: utf-8 -*-
# This file was copied from here:
# https://gitlab.com/doug.shawhan/flask-commonmark/-/blob/dev/flask_commonmark.py
# We vendor it in because that package hasn't changed in 4 years, while the Flask
# API has deprecated and removed the `Markup` class in the mean time and Jinja2
# has replaced 'evalcontextfilter' with 'pass_eval_context'.
"""
flask_commonmark
----------------
Commonmark filter class for Flask. One may notice a similarity to Dan Colish's
Flask-Markdown, from which I shamelessly copied a bunch of this. Does not have
all the nice provisions for extension baked in, but probably does what you need.
See https://commonmark.org/ for details.
Usage
::
from flask_commonmark import Commonmark
cm = Commonmark(app)
# or, if you are using the factory pattern
cm = Commonmark()
cm.init_app(app)
# Create routes in the usual way
@app.route("/commonmark")
def display_commonmark():
mycm = u"Hello, *commonmark* block."
return render_template("commonmark.html", mycm=mycm)
Templates
::
# one can just place raw markdown in the template. The filter expects
# your markdown to be fully left-aligned! Otherwise expect plaintext.
{% filter commonmark %}
# Nagasaki
1. Chew Terbaccy
1. Wicky-waky-woo
{% endfilter %}
# block style
{% filter commonmark %}{{ mycm }}{% endfilter %}
# inline style
{{mycm|commonmark}}
:copyright: (c) 2019 by Doug Shawhan.
:license: BSD, MIT see LICENSE for details.
"""
from markupsafe import Markup, escape
from jinja2 import pass_eval_context
import commonmark as cm


class Commonmark(object):
"""
Commonmark
----------
Wrapper class for Commonmark (aka "common markdown"), objects.
Args:
app (obj): Flask app instance
auto_escape (bool): Use Jinja2 auto_escape, default False
"""

def __init__(self, app=False, auto_escape=False):
"""
Create parser and renderer objects and auto_escape value.
Set filter.
"""
if not app:
return

self.init_app(app, auto_escape=auto_escape)

app.jinja_env.filters.setdefault(
"commonmark", self.__build_filter(self.auto_escape)
)

def __call__(self, stream):
"""
Render markdown stream.
Args:
stream (str): template stream containing markdown tags
Returns:
html (str): markdown rendered as html
"""
return self.cm_render.render(self.cm_parse.parse(stream))

def __build_filter(self, app_auto_escape):
"""
Jinja2 __build_filter
Args:
app_auto_escape (bool): auto_escape value (default False)
Returns:
commonmark_filter (obj): context filter
"""

@pass_eval_context
def commonmark_filter(eval_ctx, stream):
"""
Called by Jinja2 when evaluating the Commonmark filter.
Args:
eval_ctx (obj): Jinja2 evaluation context
stream (str): string to filter
"""
__filter = self
if app_auto_escape and eval_ctx.autoescape:
return Markup(__filter(escape(stream)))
return Markup(__filter(stream))

return commonmark_filter

def init_app(self, app, auto_escape=False):
"""
Create parser and renderer objects and auto_escape value.
Set filter.
"""
self.auto_escape = auto_escape
self.cm_parse = cm.Parser()
self.cm_render = cm.HtmlRenderer()

app.jinja_env.filters.setdefault(
"commonmark", self.__build_filter(self.auto_escape)
)

0 comments on commit 7350174

Please sign in to comment.