Flask route using path with leading slash

情到浓时终转凉″ 提交于 2019-11-29 12:58:23

问题


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.



来源:https://stackoverflow.com/questions/24000729/flask-route-using-path-with-leading-slash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!