How to use Factory Boy with SQLAlchemy session (Lazy Loaded) correctly? How to use Factory Boy with SQLAlchemy session (Lazy Loaded) correctly? flask flask

How to use Factory Boy with SQLAlchemy session (Lazy Loaded) correctly?


You can define the factory_boy factories without setting the SQLAlchemy session and then set it up in between initialising the Flask app and using the factories by assigning to the _meta property of the factory class:

db_session = set_up_a_db_session_somehow()MyFactoryClass._meta.sqlalchemy_session = db_session

This seems to work fine with a scoped session.


Ok I see now one of my mistakes. I create a scoped session. Instead I should be using a normal session for my application. The problem here is - how can I lazy init a normal session?

I will thread this issue in another question

for the scoped session I found the answer to this particular issue. The thing is, with the scoped session my whole app won't work but the tests will..

this code works with the scoped session, for this issue.

def _create_fixtures(self):    db.begin()    self.user = UserFactory()    db.add(self.user)    db.commit()