marshmallow-code/flask-smorest

Inject constructed arguments schema into view method

juledwar opened this issue · 4 comments

Using this example from the documentation:

@blp.arguments(PetQueryArgsSchema, location="query")

The arguments decorator will make sure the results of the PetQueryArgsSchema are injected into the wrapped view method, but the schema object is thrown away once finished with.

It would be very useful to also optionally inject the constructed schema object as well, since I have quite a few schemas that set internal context that is required in subsequent processing.

Marshmallow schemas have a similar thing when doing their own @post_dump etc decorators where you can use pass_orig to get at the original data before the schema processed it. I suggest we have a pass_schema to add an extra schema= kwarg to the wrapped method.

It's possible that this needs to happen in the webargs use_args function and not here, but I thought I'd gather opinions on this enhancement before attempting a fix myself.

Hi.

Before adding another feature, I'd like to see if this can be addressed with current code with a trick on your side.

Do you think you could define a base Schema with a post_load method adding the context as attribute to the deserialized data? (You might need to change the schema dict_class to a type that allows setattr. I think using an attr is better that adding an item to the returned data.)

Hmm, an ugly hack, :)

This could work in some situations, but not all (mostly as you say the objects that the schema returns that don't have __setattr__ on them).

My schemas sometimes return SQLAlchemy models, so it does work there but makes me nervous about potential DB column clashes.

However, the biggest problem is that Marshmallow doesn't guarantee the ordering of the post_load methods. So your proposal could end up copying context before it's available.

The cleanest solution would be the one I proposed, I think.