3

I am creating Python server using Flask and Flask-RESTX modules. I would like to define route e. g. for this URL:

/users?sort=age,asc&sort=name,desc

So when I read sort query parameter, I will have list of pairs, where each pair is (property, order) where order is asc or desc. I have following code:

from flask_restx import Resource
from flask import request
from flask_restx import reqparse

parser = reqparse.RequestParser()
parser.add_argument("sort", type=str)


@api.route("/users")
class Users(Resource):

    @api.marshal_list_with(...)
    @api.expect(parser)
    def get(self):
        print(request.args.getlist("sort"))

The code prints ['age,asc', 'name,desc'] which is fine, however I have to manually split values by comma and check if there are only 2 values (e. g. age and asc) in each item.

Is there any better way to handle this?

Michal
  • 1,755
  • 3
  • 21
  • 53

1 Answers1

3

Add action argument with value: 'split' for the RequestParser to get a splitted list of values.

And get values form parsed arguments dictionary.

Your example given my comment:

from flask_restx import Resource
from flask import request
from flask_restx import reqparse

parser = reqparse.RequestParser()
parser.add_argument("sort", type=str, action="split")


@api.route("/users")
class Users(Resource):

    @api.marshal_list_with(...)
    @api.expect(parser)
    def get(self):
        print(parser.parse_args()["sort"])

The result should look like this:

[['age', 'asc'], ['name', 'desc']]
Nicolay
  • 71
  • 2
  • 5
  • For whoever stumbles on this keep in mind request parser is deprecated and a library like marshmallow is recommended instead: https://flask-restx.readthedocs.io/en/latest/parsing.html – Martin Gergov Jul 12 '22 at 19:57