Python Flask:多个路由或端点的列表

2024-04-25 09:59:34 发布

您现在位置:Python中文网/ 问答频道 /正文

使用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([<Rule '/static/<filename>' (GET, HEAD, OPTIONS) -> static>])。。。我想这意味着没有添加我列出的端点

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

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

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


Tags: 代码apphttpflask路由get端点route
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"

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

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

用于app_url_rule的烧瓶文档:

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

Is equivalent to the following:

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

If the view_func is not provided you will need to connect the endpoint to a view function like so:

app.view_functions['index'] = index

相关问题 更多 >

    热门问题