Python 作为函数参数获取数据与从requests.arg获取项目之间的差异

Python 作为函数参数获取数据与从requests.arg获取项目之间的差异,python,python-3.x,flask,flask-restful,Python,Python 3.x,Flask,Flask Restful,我想知道以下两者之间是否有区别: @app.route('/api/users/<int:id>', methods=['GET']) def get_user(id): pass # handle user here with given id 此外,在前者中是否有获得多个参数的方法?它们可以是可选参数吗?是的,可以 第一种方法: @app.route('/api/users/<int:id>', methods=['GET'] def get_user(i

我想知道以下两者之间是否有区别:

@app.route('/api/users/<int:id>', methods=['GET'])
def get_user(id):
    pass  # 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
它只是定义了一条路线。您可以使用所有方法执行该函数

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


第二条路径是:
webexample.com/api/users?id=1
对于用户1

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

如果您使用flask函数(我真的推荐),那么该函数返回的URL结构将不同,因为您使用的所有变量(不是端点的一部分)都将被视为查询参数

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

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

使用方法变量:

url_for('get_user', id=1) => '/api/users/1'
没有方法变量:

url_for('get_user', id=1) => '/api/users?id=1'
哪种方法更好取决于您所处的环境。
如果要实现基于REST的API,应该将identifiers参数定义为路径参数,将元数据定义为查询参数(您可以阅读更多相关内容)

第一个不包含参数
id
是端点的一部分,因此您可以像
/api/users/32
一样点击它。在第二个示例中,您可以从url获取查询参数,例如
/api/users/?name=foo&id=32
。作为你的第二个问题,看看答案。
url_for('get_user', id=1) => '/api/users/1'
url_for('get_user', id=1) => '/api/users?id=1'