SQLAlchemy 不创建表

2024-05-01

我正在尝试像教程中那样设置数据库,但是当我尝试添加表时出现编程错误,表不存在User

这是错误的文件(database.py):

from sqlalchemy import create_engine, MetaData
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base


engine = create_engine(
    "mysql+pymysql://testuser:testpassword@localhost/test?charset=utf8",
    connect_args = {
        "port": 3306
    },
    echo="debug",
    echo_pool=True
)

db_session = scoped_session(
    sessionmaker(
        bind=engine,
        autocommit=False,
        autoflush=False
    )
)

Base = declarative_base()

def init_db():
    import models
    Base.metadata.create_all(bind=engine)

    from models import User
    db_session.add(
        User(username="testuser", password_hash=b"", password_salt=b"", balance=1)
    )
    db_session.commit()

    print("Initialized the db")


if __name__ == "__main__":
    init_db()

要初始化数据库(创建表),我只需运行该文件。 创建测试用户时出错。

Here is models.py:

from sqlalchemy import Column, Integer, Numeric, Binary, String
from sqlalchemy.orm import relationship

from database import Base


class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True)

    username = Column(String(16), unique=True)
    password_hash = Column(Binary(32))
    password_salt = Column(Binary(32))

    balance = Column(Numeric(precision=65, scale=8))

    def __repr__(self):
        return "<User(balance={})>".format(balance)

I tried:

  • 在添加用户之前提交(之后create_all)
  • 从数据库中删除现有表(尽管该表似乎永远不会被提交)
  • from models import User代替import models(前create_all)

抱歉,如果有这么多类似的问题,我保证我会寻找答案,但我确保我没有犯(或至少是我看到的那些),这总是愚蠢的错误。

我正在使用 MariaDB。

抱歉,帖子很长,非常感谢。


The Base in database.py不一样Base被导入到models.py.

一个简单的测试是放一个print('creating Base')函数调用就在上面Base = declarative_base()语句,您会看到它被创建了两次。

Python调用正在执行的模块'__main__',你知道,因为你有if __name__ == '__main__'条件位于模块底部。所以第一个Base所创建的是__main__.Base。然后,在models.py, from database import Base导致database再次解析模块,创建database.Base在命名空间中,那就是Base从中User继承。然后回到database.py, the Base.metadata.create_all(bind=engine)调用正在使用来自的元数据__main__.Base其中没有表,因此什么也没有创建。

不要在创建的模块之外执行Base实例。创建另一个名为main.py(或其他什么),然后移动你的init_db()在那里运行并导入Base, db_session and engine from database.py into main.py。这样,您始终使用相同的Base实例。这是一个例子main.py:

from database import Base, db_session, engine
from models import User


def init_db():

    Base.metadata.create_all(bind=engine)

    db_session.add(
        User(username="testuser", password_hash=b"", password_salt=b"", balance=1)
    )
    db_session.commit()

    print("Initialized the db")


if __name__ == "__main__":
    init_db()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SQLAlchemy 不创建表 的相关文章

随机推荐