Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accept list of ints in Flask url instead of one int

Tags:

python

flask

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. How can I accept a list of ids?

@app.route('/user/<int:user_id>')  # should accept multiple ints
def process_user(user_id):
    return str(user_id)
like image 554
frazman Avatar asked Dec 10 '22 21:12

frazman


1 Answers

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'])
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
like image 132
DevLounge Avatar answered Dec 13 '22 09:12

DevLounge