Last active
June 18, 2024 15:22
-
-
Save hodgesmr/2db123b4e1bd8dcca5c4 to your computer and use it in GitHub Desktop.
Automatically register Flask routes with and without trailing slash. This way you avoid the 301 redirects and don't have to muddy up your blueprint with redundant rules.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Flask Blueprint sublcass that overrides `route`. | |
Automatically adds rules for endpoints with and without trailing slash. | |
""" | |
from flask import Blueprint, Flask | |
class BaseBlueprint(Blueprint): | |
"""The Flask Blueprint subclass.""" | |
def route(self, rule, **options): | |
"""Override the `route` method; add rules with and without slash.""" | |
def decorator(f): | |
new_rule = rule.rstrip('/') | |
new_rule_with_slash = '{}/'.format(new_rule) | |
super(BaseBlueprint, self).route(new_rule, **options)(f) | |
super(BaseBlueprint, self).route(new_rule_with_slash, **options)(f) | |
return f | |
return decorator | |
blueprint = BaseBlueprint('blueprint', __name__) | |
@blueprint.route('/test/', methods=['POST']) | |
def test(): | |
"""Simple example; return 'ok'.""" | |
return 'ok' | |
@blueprint.route('/test2', methods=['POST']) | |
def test2(): | |
"""Simple example; return 'ok'.""" | |
return 'ok' | |
app = Flask('my_app') | |
app.register_blueprint(blueprint) | |
app.run(port=9001) | |
# Now `/test`, `/test/`, `/test2`, and `/test2/` are registered and can accept | |
# POSTs without having worry about redirects. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great stuff, had this issue with
Flask = "^2.1.3"
;strict_slashes=False
orapp.url_map.strict_slashes = False
was not helpful, the override did the job.