Flask route using path with leading slash

2019-03-20 01:26发布

问题:

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 

回答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:

from werkzeug.routing import PathConverter

class EverythingConverter(PathConverter):
    regex = '.*?'

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

@api.route('/records/<hostname>/<metric>/<everything:context>') 

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