GET 数据作为函数参数与来自 requests.arg 的项目之间的区别

Difference between GET data as a function parameter and an item from requests.arg

我想知道有什么区别:

@app.route('/api/users/<int:id>', methods=['GET'])
def get_user(id):
    pass  # handle user here with given id

@app.route('/api/users')
def get_user():
    id = request.args.get('id')
    # handle user here with given id

另外,有没有办法在前者中获取多个参数?它们可以是可选参数吗?

是的,是的。

第一种方法:

@app.route('/api/users/<int:id>', methods=['GET']
def get_user(id):
    pass  # handle user here with given id

定义路线和方法。此功能仅在此路径上使用此方法触发。

第二种方法:

@app.route('/api/users')
def get_user():
    id = request.args.get('id')
    # handle user here with given id

它只是定义了一条路线。您可以使用所有方法执行该功能。

第一种方法中的路由是:webexample.com/api/users/1 for user 1

第二个路由是:webexample.com/api/users?id=1 for user 1

主要区别在于 URL 触发函数的方式不同。

如果你使用 flask 函数 url_for(我真的推荐),函数返回的 URL 结构将不同,因为你使用的所有变量都不是端点将被视为查询参数。

因此在这种情况下,您可以在不影响现有代码库的情况下更改路线。

换句话说,在你的情况下你会:

使用方法变量:

url_for('get_user', id=1) => '/api/users/1'

没有方法变量:

url_for('get_user', id=1) => '/api/users?id=1'

哪种方法更好取决于您所处理的上下文。 如果您想实现基于 REST 的 API,您应该将标识符参数定义为路径参数,将元数据定义为查询参数(您可以阅读更多相关内容 here)。