How to initialize database with some data when app startup? (fastapi, sqlalchemy)

Question:

I’m new to the fastapi and sqlalchemy. And I’m trying to initialize some data when I startup my app. Here is what I’m thinking of:

@app.on_event("startup")
async def startup_event():
    with SessionLocal() as session:
        country_dataframe = pd.read_csv('./initialize_data/country.csv')
        for index, row in country_dataframe.iterrows():
            session.add(models.Country(row.to_dict()))
        session.commit()

But I can’t get the db session when I start it, it shows an error code:

ERROR: Traceback (most recent call last): File
"C:UsersnewiaMiniconda3envsfastapilibsite-packagesstarletterouting.py",
line 540, in lifespan
async for item in self.lifespan_context(app): File "C:UsersnewiaMiniconda3envsfastapilibsite-packagesstarletterouting.py",
line 481, in default_lifespan
await self.startup() File "C:UsersnewiaMiniconda3envsfastapilibsite-packagesstarletterouting.py",
line 516, in startup
await handler() File "D:Software ProjectsPythonProjectsLanguageExchangeapp.py", line 27, in
startup_event
with SessionLocal() as session: AttributeError: enter

ERROR: Application startup failed. Exiting.

Is there any design pattern to do this? Any advice would be grateful.

Asked By: Ian

||

Answers:

You can check this starter fast API template. I think the section you be interested in the init_db.py

Answered By: Albert Marrero

You can also use fastapi_async_sqlalchemy so it is not required to import dependency in all endpoints in this project template you can find an awesome way hot to use it in a project.

Answered By: Jonathan Vargas
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.