'share db session across multiple lambda invocations using Mangum

So far, I've been declaring my db connection outside of my web server app creation:

# src/main.py
db_session = ... # connection 
app = FastAPI()
handler = Mangum(app)

# other files would import db_session from src.main
# and query the db through it

For better unit testing, I decided to move the db declaration as part of the app state:


def create_app(settings: Settings):
    app = FastApi()
    app.state.config = settings
    app.state.db_session = ... # here is the db declaration, using `settings` to get db credentials
    ...
    return app

app = create_app(settings)
handler = Mangum(app)

does anyone know if, by wrapping the app around Mangum, db session won't be shared anymore across multiple lambda invocations ? I don't know to which extent app here is within the handler real code.



Solution 1:[1]

There is a pretty good answer citing the AWS documentation here: Scope of Python globals in AWS Lambda

In your case, app is a global variable and anything connected to it should stay global. Passing it onto the function call (or class constructor) of Mangum won't change that.

I'm not familiar with Mangum, but unless it does some sort of trickery, it should be a regular global variable.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Maurice