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?

1 Answer 1

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']]
Sign up to request clarification or add additional context in comments.

1 Comment

For whoever stumbles on this keep in mind request parser is deprecated and a library like marshmallow is recommended instead: flask-restx.readthedocs.io/en/latest/parsing.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.