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

Use ModelSchema.session setter rather than OPTIONS_CLASS

Open antgel opened this issue 6 years ago • 1 comments

When I use webargs with flask-marshmallow, there is an issue whereby webargs calls schema.load(parsed), and fails because the DummySession is returned instead of the sqlalchemy scoped session.

I am relying on init_app() to bind the sqlalchemy session. I can see from other issues that people have suggested passing sqla_session in Meta, but I'd rather not copy and paste boilerplate if I can avoid it. Looking at the relevant line in marshmallow-sqlalchemy, it looks like ModelSchema.load expects self._session to be set, which ModelSchema.OPTIONS_CLASS.session doesn't do, but the setter does.

The tests still pass, but as a new user of this ecosystem, I'd be happy to know if I've missed something. In particular, I know a lot of people use this stuff, so I'm not sure how it works for others.

antgel avatar Jan 19 '19 00:01 antgel

I have the DummySession problem too, but I don't think the solution is to set self.ModelSchema.session = db.session cause it is not possible to get sqla_session in Meta again. I found that I use init_app manually after I create Marshmallow instance (I create flask app with factory mode), so the subclasses of ma.ModelSchema were created before init_app is called, thus the self.ModelSchema.OPTIONS_CLASS.session is always DummySession instance when the subclasses were created . My solution is to set ma.ModelSchema.OPTIONS_CLASS.session = db.session right after create the SQLAlchemy instance and the Marshmallow instance. It works for me, but the init_app also should be change.

ZinkLu avatar May 05 '19 11:05 ZinkLu