Accept int list in Flask url instead of single int

My API has a way to handle the user by the int id passed in the url. I would like to pass a list of identifiers so that I can make one bulk API request, rather than several separate requests. How can I accept a list of identifiers?

@app.route('/user/<int:user_id>')  # should accept multiple ints
def process_user(user_id):
    return str(user_id)
+4
source share
2 answers

Instead of passing it to a URL, pass the value of the form. Use request.form.getlistto get a list of values ​​for a key, not a single value. You can pass type=intto make sure all values ​​are 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
+6
source

URL, int, , int. API- , , , : /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
+3

All Articles