Search code examples
pythonpostgresqlsqlalchemyfastapialembic

how to perform an action when launching the app with FastAPI


I want to check when launching the application if there is an administrator in the user table. If it is not there, then it should be automatically added to the postgresql(sqlalchemy) table. Is it possible to do this?

It turns out that I need to initialize the administrator account along with the first launch of the application.

I will be grateful for any help!

I have model with class User():

`class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    username = Column(String)
    password_hash = Column(String)
    role = Column(String, default='admin')
    created_at = Column(DateTime, default=func.now())
    created_by = Column(Integer, ForeignKey('users.id'), default=1)
    modified_at = Column(DateTime, default=func.now(), onupdate=func.now())
    modified_by = Column(Integer, ForeignKey('users.id'), default=1)`

And I want to use username and password from .env file, corresponding to the login and password from the sql server.

I'm trying to use core events in sqlalchemy, but I don't understand if this can help.

https://docs.sqlalchemy.org/en/14/core/events.html


Solution

  • I can recommend you to use migration tool for your db (like alembic). Then you can create "Init" migration where you can add query to create admin. But then you need to run your program like alembic upgrade head && uvicorn main:app