使用带有斜线的路径的烧瓶路线 [英] Flask route using path with leading slash

查看:173
本文介绍了使用带有斜线的路径的烧瓶路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

除非URL的路径部分使用前导斜杠。在这种情况下,我得到了一个404。我明白这个错误,但我没有得到的是,在文档或Internet上的任何地方没有解决这个问题的方法。我觉得我是第一个试图做这个基本的东西。

有没有办法让这个工作与有意义的URL?例如这样的请求:

$ p $ http:// localhost:5000 / api / records / localhost / disks.free // dev / disk0s2


解决方案

PathConverter URL转换器显式地不会包括领先的斜线;这是故意的,因为大多数路径不应该包含这样的斜线。



请参阅 PathConverter 源代码


  regex ='[^ /]。*?'


这个表达式匹配任何东西,只要它不以 /



你不能编码路径;试图在路径中使用不是URL分隔符的路径,而是通过将它们编码为%2F 的值的一部分,大部分(如果不是全部的话)解码在将它传递给WSGI服务器之前,请指定URL路径。



您必须使用不同的转换器:

<来自werkzeug.routing的pre> import PathConverter

类EverythingConverter(PathConverter):
regex ='。*?'

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

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

注册转换器必须在Flask app 对象上完成,不能在蓝图上完成。


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:

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.

这篇关于使用带有斜线的路径的烧瓶路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆