List of query params with Flask request.args

前端 未结 1 874
礼貌的吻别
礼貌的吻别 2020-12-19 10:24

I am trying to pass comma separated query parameters to a Flask endpoint.

An example URI would be:

localhost:3031/someresource#?status=1001,1002,1003

相关标签:
1条回答
  • 2020-12-19 10:56

    Its not uncommon REST API design to have commas to pass multiple values for the same key - makes it easier for the user. You're parsing GET args anyway, parsing strings is not that much more hacky. You can choose to raise a 400 HTTP error if their string with commas isn't well formatted.

    Some other languages (notably PHP) support 'array' syntax, so that is used sometimes:

    /request?status[]=1000&status[]=1001&status[]=1002

    The flask variant getlist expects multiple keys:

    from flask import Flask, request
    
    app = Flask(__name__)
    
    @app.route('/')
    def status():
        first_status = request.args.get("status")
        statuses = request.args.getlist("status")
        return "First Status: '{}'\nAll Statuses: '{}'".format(first_status, statuses)
    
    ❯ curl "http://localhost:5000?status=5&status=7"
    First Status: '5'
    All Statuses: '['5', '7']'
    

    There's no standard for this, how multiple GET args are parsed/passed depends on which language/framework you're using; flask is built on werkzeug so it allows this style, but you'll have to look it up if you switch away from flask.

    0 讨论(0)
提交回复
热议问题