Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
flask-restful NestedRequestParser
from flask import request
from flask.ext.restful.reqparse import Argument, RequestParser
class NestedArgument(Argument):
def __init__(self, name, **kwargs):
pieces = name.split('.')
self.full_name = name
if len(pieces) > 1:
name = pieces.pop()
super(NestedArgument, self).__init__(name, **kwargs)
def source(self, request):
pieces = self.full_name.split('.')
source = super(NestedArgument, self).source(request)
if len(pieces) == 1:
return source
for piece in pieces[:-1]:
source = source.get(piece, None)
if source is None:
u"{0} is required in {1}".format(
return source
class NestedRequestParser(RequestParser):
def __init__(self):
super(NestedRequestParser, self).__init__(argument_class=NestedArgument)
def parse_args(self, req=None):
if req is None:
req = request
namespace = self.namespace_class()
for arg in self.args:
pieces = arg.full_name.split('.')
current = namespace
# setup namespace for nested arguments
# given a `full_name` of `a.b.c`, we create namespace { 'a': { 'b': {} } }
if len(pieces) > 1:
for i in range(0, len(pieces) - 1):
if current.get(pieces[i]) is None:
current[pieces[i]] = {}
current = current[pieces[i]]
current[arg.dest or] = arg.parse(req)
return namespace
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment