Reputation: 2073
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?
Upvotes: 3
Views: 8110
Reputation: 91
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']]
Upvotes: 3