I found the bbenne10s answer really useful, but it didn't work for me as is.
The way I did this is probably wrong, but it works. My problem is that I don't understand what action='append'
does as what it seems to do is wrap the value received in a list, but it doesn't make any sense to me. Can someone please explain whats the point of this in the comments?
So what I ended up doing is creating my own listtype
, get the list inside the value
param and then iterate through the list this way:
from flask.ext.restful import reqparse
def myobjlist(value):
result = []
try:
for v in value:
x = MyObj(**v)
result.append(x)
except TypeError:
raise ValueError("Invalid object")
except:
raise ValueError
return result
#and now inside views...
parser = reqparse.RequestParser()
parser.add_argument('a_list', type=myobjlist)
Not a really elegant solution, but at least it does the work. I hope some one can point us in the right direction...
Update
As bbenne10 has said in the comments, what action='append'
does is append all the arguments named the same into a list, so in the case of the OP, it doesn't seem to be very useful.
I have iterated over my solution because I didn't like the fact that reqparse
wasn't parsing/validating any of the nested objects so I what I have done is use reqparse
inside the custom object type myobjlist
.
First, I have declared a new subclass of Request
, to pass it as the request when parsing the nested objects:
class NestedRequest(Request):
def __init__(self, json=None, req=request):
super(NestedRequest, self).__init__(req.environ, False, req.shallow)
self.nested_json = json
@property
def json(self):
return self.nested_json
This class overrides the request.json
so that it uses a new json with the object to being parsed.
Then, I added a reqparse
parser to myobjlist
to parse all the arguments and added an except to catch the parsing error and pass the reqparse
message.
from flask.ext.restful import reqparse
from werkzeug.exceptions import ClientDisconnected
def myobjlist(value):
parser = reqparse.RequestParser()
parser.add_argument('obj1', type=int, required=True, help='No obj1 provided', location='json')
parser.add_argument('obj2', type=int, location='json')
parser.add_argument('obj3', type=int, location='json')
nested_request = NestedRequest()
result = []
try:
for v in value:
nested_request.nested_json = v
v = parser.parse_args(nested_request)
x = MyObj(**v)
result.append(x)
except TypeError:
raise ValueError("Invalid object")
except ClientDisconnected, e:
raise ValueError(e.data.get('message', "Parsing error") if e.data else "Parsing error")
except:
raise ValueError
return result
This way, even the nested objects will get parsed through reqparse and will show its errors