【发布时间】:2022-01-17 08:54:29
【问题描述】:
我的 product_api/models.py
中有这个from . import db
from datetime import datetime
class Product(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255), unique=True, nullable=False)
slug = db.Column(db.String(255), unique=True, nullable=False)
price = db.Column(db.Integer, nullable=False)
image = db.Column(db.String(255), unique=False, nullable=True)
date_added = db.Column(db.DateTime, default=datetime.utcnow)
date_updated = db.Column(db.DateTime, onupdate=datetime.utcnow)
def to_json(self):
return {
'id': self.id,
'name': self.name,
'slug': self.slug,
'price': self.price,
'image': self.image
}
我运行 db init 和 db migrate 在 migrate 命令之后我收到这条消息UserWarning: Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. Defaulting SQLALCHEMY_DATABASE_URI to "sqlite:///:memory:". 但是它下面的几行说 INFO [alembic.autogenerate.compare] Detected added table 'product'
我手动检查 MySQL 数据库,果然,表不存在,我无法访问我的 API 端点。
我可以看到迁移在迁移文件
中创建了一些东西revision = '66be5d817908'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('product',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=255), nullable=False),
sa.Column('slug', sa.String(length=255), nullable=False),
sa.Column('price', sa.Integer(), nullable=False),
sa.Column('image', sa.String(length=255), nullable=True),
sa.Column('date_added', sa.DateTime(), nullable=True),
sa.Column('date_updated', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name'),
sa.UniqueConstraint('slug')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('product')
这是我的 run.py
from application import create_app, db
from application import models
from flask_migrate import Migrate
app = create_app()
migrate = Migrate(app, db)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5002)
在使用另一个数据库创建我的其他微服务时,我已经经历了这个确切的场景,并且在迁移创建表时没有任何问题。我考虑将 db.create_all() 添加到我的 run.py 中,但它并没有真正起作用。我尝试删除数据库并重新开始,但这也不起作用。我很困惑为什么第一个微服务正在运行,而这个微服务导致了这些问题。
编辑 1 - 这是我的 config.py
# config.py
import os
from dotenv import load_dotenv
dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
if os.path.exists(dotenv_path):
load_dotenv(dotenv_path)
class Config:
SQLALCHEMY_TRACK_MODIFICATIONS = False
class DevelopmentConfig(Config):
ENV = "development"
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://kkan@localhost:3306/product';
SQLALCHEMY_ECHO = True
class ProductionConfig(Config):
pass
它看起来和我的其他微服务一样。
【问题讨论】:
-
您确定在实例化 db 对象之前 在 app.config 中设置了 SQLALCHEMY_DATABASE_URI 吗?
-
如果您想看一下,我已将我的 config.py 添加到编辑中
标签: python database flask migration microservices