Skip to content Skip to sidebar Skip to footer

Accept List Of Ints In Flask Url Instead Of One Int

My API has a route to process a user by an int id passed in the url. I'd like to pass a list of ids so I can make one bulk request to the API rather than several single requests.

Solution 1:

Rather than passing it in the url, pass a form value. Use request.form.getlist to get a list of values for a key, rather than a single value. You can pass type=int to make sure all the values are ints.

@app.route('/users/', methods=['POST'])defget_users():
    ids = request.form.getlist('user_ids', type=int)
    users = []

    foridin ids:
        try:
            user = whatever_user_method(id)
            users.append(user)
        except:
            continue

    returns users

Solution 2:

Write a custom url converter that accepts a list of ints separated by a delimiter, rather than just one int. The Stack Exchange API, for example, accepts multiple ids delimted by semicolons: /answers/1;2;3. Register the converter with your app and use it in your route.

from werkzeug.routing import BaseConverter

classIntListConverter(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 functiondefto_python(self, value):
        return [int(x) for x in value.split(';')]

    # this is used when building a url with url_fordefto_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>')defprocess_user(ids):
    foridin 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

Solution 3:

Simple as this

@app.route('/user/<users>')defprocess_user(users):
    users = list(users.split(","))
    print(users)

Input

/users/[1,2,3,4]

Output

[1,2,3,4]

Post a Comment for "Accept List Of Ints In Flask Url Instead Of One Int"