在使用FastAPI启动应用时执行操作的方法如何?

huangapple go评论74阅读模式
英文:

how to perform an action when launching the app with FastAPI

问题

我想检查在启动应用程序时用户表中是否有管理员。 如果没有,那么它应该自动添加到PostgreSQL(SQLAlchemy)表中。这是否可能?

事实证明,我需要在应用程序首次启动时初始化管理员帐户。

我将非常感激任何帮助!

我有一个名为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)

我希望使用.env文件中的用户名和密码,与SQL服务器中的登录名和密码相对应。

我尝试使用SQLAlchemy中的核心事件,但我不确定这是否有助于解决问题。

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

英文:

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

答案1

得分: 0

我建议你使用数据库迁移工具(例如alembic)。然后,你可以创建一个名为“Init”的迁移,其中你可以添加用于创建管理员的查询。但接下来,你需要运行你的程序,类似于 alembic upgrade head && uvicorn main:app

英文:

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

huangapple
  • 本文由 发表于 2023年2月24日 00:58:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75547983.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定