Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save hodgesmr/2db123b4e1bd8dcca5c4 to your computer and use it in GitHub Desktop.
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.
"""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.
@alexandrupatrascu
Copy link

Great stuff, had this issue with Flask = "^2.1.3"; strict_slashes=False or app.url_map.strict_slashes = False was not helpful, the override did the job.

@erickhun
Copy link

Thank you @hodgesmr ... so many weird behaviors with flask trying to do too much magic...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment