接受Flask url中的int列表而不是一个int

Moh*_*hit 4 python flask

我的API有一个通过url中传递的int id处理用户的路由.我想传递一个id列表,这样我就可以向API发出一个批量请求,而不是几个单个请求.我如何接受ID列表?

@app.route('/user/<int:user_id>')  # should accept multiple ints
def process_user(user_id):
    return str(user_id)
Run Code Online (Sandbox Code Playgroud)

Ant*_*rot 9

不是将其传递给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
Run Code Online (Sandbox Code Playgroud)


dav*_*ism 7

编写一个自定义 url 转换器,它接受由分隔符分隔的一系列整数,而不仅仅是一个整数。例如,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
Run Code Online (Sandbox Code Playgroud)


Hen*_*l B 5

就这么简单

@app.route('/user/<users>')
def process_user(users):
    users = list(users.split(","))
    print(users)
Run Code Online (Sandbox Code Playgroud)

输入

/users/[1,2,3,4]
Run Code Online (Sandbox Code Playgroud)

输出

[1,2,3,4]
Run Code Online (Sandbox Code Playgroud)