Skip to content Skip to sidebar Skip to footer

Flask Route Using Path With Leading Slash

I am trying to get Flask using a simple route with a path converter: @api.route('/records///') It works unless the 'path' part o

Solution 1:

The PathConverter URL converter explicitly doesn't include the leading slash; this is deliberate because most paths should not include such a slash.

See the PathConverter source code:

regex = '[^/].*?'

This expression matches anything, provided it doesn't start with /.

You can't encode the path; attempting to make the slashes in the path that are not URL delimiters but part of the value by URL-encoding them to %2F doesn't fly most, if not all servers decode the URL path before passing it on to the WSGI server.

You'll have to use a different converter:

import werkzeug
from werkzeug.routing import PathConverter
from packaging import version

# whether or not merge_slashes is available and true
MERGES_SLASHES = version.parse(werkzeug.__version__) >= version.parse("1.0.0")

classEverythingConverter(PathConverter):
    regex = '.*?'

app.url_map.converters['everything'] = EverythingConverter

config = {"merge_slashes": False} if MERGES_SLASHES else {}
@api.route('/records/<hostname>/<metric>/<everything:context>', **config) 

Note the merge_slashes option; if you have Werkzeug 1.0.0 or newer installed and leave this at the default, then multiple consecutive / characters are collapsed into one.

Registering a converters must be done on the Flask app object, and cannot be done on a blueprint.

Post a Comment for "Flask Route Using Path With Leading Slash"