我的API有一个路由,用于通过在url中传递的int id来处理用户。我想传递一个ID列表,这样我就可以向API发出一个批量请求,而不是几个单一的请求。我如何接受ID列表?接受Flask url中的ints列表,而不是一个int
@app.route('/user/<int:user_id>') # should accept multiple ints
def process_user(user_id):
return str(user_id)
我的API有一个路由,用于通过在url中传递的int id来处理用户。我想传递一个ID列表,这样我就可以向API发出一个批量请求,而不是几个单一的请求。我如何接受ID列表?接受Flask url中的ints列表,而不是一个int
@app.route('/user/<int:user_id>') # should accept multiple ints
def process_user(user_id):
return str(user_id)
而不是传递它的URL,传递一个表单值。使用request.form.getlist
可以获取某个键的值列表,而不是单个值。您可以通过type=int
以确保所有值均为整数。
@app.route('/users/', methods=['POST'])
def get_users():
ids = request.form.getlist('user_ids', type=int)
users = []
for id in ids:
try:
user = whatever_user_method(id)
users.append(user)
except:
continue
returns users
写custom url converter接受由分隔符,而不是只有一个INT整数的列表。例如,Stack Exchange API接受以分号分隔的多个ID:/answers/1;2;3
。用您的应用程序注册转换器并在您的路线中使用它。
from werkzeug.routing import BaseConverter
class IntListConverter(BaseConverter):
"""Match ints separated with ';'."""
# at least one int, separated by ;, with optional trailing ;
regex = r'\d+(?:;\d+)*;?'
# this is used to parse the url and pass the list to the view function
def to_python(self, value):
return [int(x) for x in value.split(';')]
# this is used when building a url with url_for
def to_url(self, value):
return ';'.join(str(x) for x in value)
# register the converter when creating the app
app = Flask(__name__)
app.url_map.converters['int_list'] = IntListConverter
# use the converter in the route
@app.route('/user/<int_list:ids>')
def process_user(ids):
for id in ids:
...
# will recognize /user/1;2;3 and pass ids=[1, 2, 3]
# will 404 on /user/1;2;z
# url_for('process_user', ids=[1, 2, 3]) produces /user/1;2;3