Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

What is the best way to handle post_dump hooks and "tweak" the generated spec? #613

Open
sirosen opened this issue Nov 24, 2020 · 2 comments
Labels

Comments

@sirosen
Copy link

sirosen commented Nov 24, 2020

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.)

@sponsfreixes
Copy link

Hi @sirosen, did you ever figure out how to resolve this issue? I am facing the same problem.

@sirosen
Copy link
Author

sirosen commented Mar 23, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants