question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Sington provider with setup and teardown methods?

See original GitHub issue

How can I create a Singleton object based on a generator?

For example


def session_factory(connection):
   with connection() as conn:
        session = Session(bind=conn)
        yield session
        try:
            session.commit()
        except:
            session.rollback()
        finally:
            session.close()


class Container(containers.DeclarativeContainer):
    session = providers.ThreadLocalSingleton(session_factory, connection=...)

Issue Analytics

  • State:open
  • Created 2 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

3reactions
lmtanicommented, Apr 1, 2022

I’m trying to do the same thing but still struggling.

It works if we inject the Resource in the route, using the Closing marker.

For example:

# containers.py
def get_session(session_factory):
    with session_factory() as session:
        logging.warning("Started session")
        yield session
    logging.warning("Ended session")

class Container(containers.DeclarativeContainer):
    db = providers.Singleton(Database, db_url=config.db.url)
    session = providers.Resource(get_session, session_factory=db.provided.session)

    my_repository = providers.Factory(WorkflowRepository, session=session)
    my_service = providers.Factory(MyService, my_repository=my_repository)


# Flask route
@bp.route("/", methods=["GET"])
@inject
def more(db_session: Session = Closing[Provide[Container.session]], my_service: MyService = Provide[Container.my_service]):
    return my_service.execute("something")

I’m not sure if it’s working the way I imagine it is, but it seems to work.

0reactions
tad3jcommented, Mar 22, 2022

I’m looking at the same situation when trying to open DB session per FastAPI request by using Resource provider.

As a base I’ve used example from docs and added resource with:

def get_database_session(database_session_factory: Database.session):
    with database_session_factory() as database_session:
        yield database_session
        
database_session = Resource(
        get_database_session,
        database_session_factory=database.provided.session,
    )

Issue with this code is that database session is only opened once (on first request) then object is stored globally and server for every consecutive request. I’m also noticing that session is never closed, I guess because generator is not called for the 2nd time.

It seems like some hybrid between Factory (executes on every request) and Resource (supports yield and doesn’t need a class) provider would do the job? Was looking through docs and fiddling with it but it seems like there is no appropriate provider available, did I miss any?

I think this issue may also be related to https://github.com/ets-labs/python-dependency-injector/issues/495.

Read more comments on GitHub >

github_iconTop Results From Across the Web

TestNG setup/teardown methods | Learn Selenium
These are the setup and teardown methods. ... When you build the test class, there will be certain Java methods annotated with @Test...
Read more >
SetUp and TearDown
Teardown methods (again, both types) are called on derived classes first, then on the base class. The teardown methods at any level in...
Read more >
Googletest FAQ
For each TEST_F , googletest will create a fresh test fixture object, immediately call SetUp() , run the test body, call TearDown() ,...
Read more >
Chapter 26. Jersey Test Framework
JerseyTestNg.ContainerPerClassTest creates one container to run all the tests in. Setup method is annotated with @BeforeClass , teardown method with @AfterClass ...
Read more >
NUnit global initialization - bad idea?
[SetUpFixture]. This is the attribute that marks a class that contains the one-time setup or teardown methods for all the test fixtures under...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found