I am trying to get Flask using a simple route with a path converter:
@api.route('/records/<hostname>/<metric>/<path:context>')
It works unless the "path" part of the URL uses a leading slash. In this case I get a 404. I understand the error but what I don't get is that there is no workaround in the documentation or anywhere on the Internet about how to fix this. I feel like I am the first one trying to do this basic thing.
Is there a way to get this working with meaningful URL? For example this kind of request:
http://localhost:5000/api/records/localhost/disks.free//dev/disk0s2
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")
class EverythingConverter(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With