flask-smorest icon indicating copy to clipboard operation
flask-smorest copied to clipboard

Inject constructed arguments schema into view method

Open juledwar opened this issue 1 year ago • 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.

juledwar avatar May 29 '23 00:05 juledwar

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

lafrech avatar May 30 '23 07:05 lafrech

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.

juledwar avatar May 30 '23 21:05 juledwar

This would indeed have to be done on webargs.

Seems like a corner case, but if the change is not too impacting, it could be acceptable.

Would you like to take a stab at it?

lafrech avatar Jul 09 '24 21:07 lafrech

I'll see what I can do, I'll have to re-familiarise myself with the problem since it's been over a year.

juledwar avatar Jul 09 '24 21:07 juledwar