apispec
apispec copied to clipboard
What is the best way to handle post_dump hooks and "tweak" the generated spec?
I have some schemas which handle some messy/complicated cases by means of (sometimes elaborate) pre_dump and post_dump hooks.
To give a (contrived) example, a schema might look like so:
class MySchemaEncodingAPeculiarList(Schema):
data = fields.Nested(OtherSchema(many=True))
@pre_dump
def filter_data(self, data, **kwargs):
contents = [x for x in data["foo"] if data["bar"][x] % 2 == 0]
return {"data": contents}
@post_dump
def unwrap_data(self, obj, **kwargs):
return obj["data"]
class MySchema(Schema):
foos = fields.Nested(MySchemaEncodingAPeculiarList)
When my output schemas are passed into apispec, MySchema
will show up something like
{
"foos": {
"data": [
...
]
}
}
But the field data
shouldn't really be there -- it's just an artifact of the way that these pre_dump
and post_dump
hooks are manipulating the data.
apispec cannot reasonably be asked to know what to do with this out of the box. post_dump and pre_dump hooks could do anything.
But I would like to know how I can or should customize the marshmallow plugin in order to handle MySchemaEncodingAPeculiarList
, or maybe to handle it at the level of MySchema
. I couldn't figure this out from the documentation, and would appreciate any help or guidance.
(I am also looking at restructuring the schemas, but the real use-case is a lot more complex than this toy example.)
Hi @sirosen, did you ever figure out how to resolve this issue? I am facing the same problem.
It's unfortunately been a bit too long since I did my relevant work here for me to be sure, but I scanned my old code for this and it looked like my solution was to define a custom converter and restructure my schemas a little bit. It wasn't a "clean" job or anything generalizable though.
I think the production app where I did this at $WORK
is too complex for me to extract an example. But I know that I learned a lot by looking at the oneofschema converter which someone produced as a separate library.