【问题标题】:Python Flask : list of multiple routes or endpointsPython Flask:多个路由或端点的列表
【发布时间】:2020-01-15 00:42:36
【问题描述】:

使用 Python 3.8 和 Flask,我需要下面的服务器端代码:

1) 将未知长度的端点列表传递给 app.route(),

2) 通过打印添加的路线,确保它们被列为有效路线。

以下代码没有错误,但似乎没有做任何事情。

# server.py
from flask import Flask 

methods = ['GET','POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS', 'PATCH']
endpoints = ['users','countries', <etc>] # <etc> to indicate list of unknown length

app = Flask(__name__)
for endpoint in endpoints:
    #print(endpoint)
    app.route('/<str:endpoint>', methods=methods)

print(app.url_map) 

if __name__ == '__main__':
    app.run()

print(app.url_map) 只返回: Map([&lt;Rule '/static/&lt;filename&gt;' (GET, HEAD, OPTIONS) -&gt; static&gt;]) ...我认为这意味着我列出的端点都没有被添加!

使用上面代码的以下 3 个请求,只有前 2 个的端点是有效的:

'http://127.0.0.1:5000/users',
'http://127.0.0.1:5000/countries',
'http://127.0.0.1:5000/xxx'

没有列出客户端代码,因为它与上述问题无关。

【问题讨论】:

    标签: python flask


    【解决方案1】:

    如果您想动态绑定端点,请使用app_url_rule 方法(即不使用app.route 装饰器)

    app_url_rule 的烧瓶文档:

    @app.route('/') 
    def index():
        pass
    

    等价于:

    def index():
        pass 
    app.add_url_rule('/', 'index', index)
    

    如果未提供 view_func,您将需要连接端点 像这样的视图函数:

    app.view_functions['index'] = index
    

    【讨论】:

    • 太棒了。感谢您的帮助。
    • 不客气。满意请采纳答案
    【解决方案2】:

    函数 app.route() 是一个装饰器。它用于指定应为接收到对特定资源 (URI) 的请求而调用的方法。您上面的代码只是生成一个装饰器,而不是实际使用它来绑定一个函数。

    以下是 app.route() 工作原理的示例:

    from flask import Flask
    
    app = Flask(__name__)
    
    
    @app.route('/')
    def hello_world():
        return "Hello World"
    

    在您的代码中,没有将路由绑定到的函数。

    例如,如果您想将列表中的所有路由绑定到 hello world,您可以使用以下代码:

    from flask import Flask
    
    app = Flask(__name__)
    
    
    methods = ['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS', 'PATCH']
    endpoints = ['users', 'countries']  # <etc> to indicate list of unknown length
    
    for endpoint in endpoints:
        @app.route(endpoint, methods=methods)
        def hello_world():
            return "Hello World"
    

    但是,我不确定您为什么需要将相同的函数绑定到数量不定的资源。

    【讨论】:

    • 您指定的代码给出以下错误:AssertionError: View function mapping is overwriting an existing endpoint function: hello_world
    猜你喜欢
    • 1970-01-01
    • 2023-03-23
    • 2020-06-04
    • 2014-03-25
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 2017-05-16
    相关资源
    最近更新 更多