【发布时间】:2020-05-19 05:34:50
【问题描述】:
我正在为我的应用程序使用烧瓶、sqlalchemy、sqlite 和 python。当我运行 db init 来创建数据库时,我希望将一些默认值集添加到数据库中。我已经尝试了这两件事来将记录添加到表中。一种方法是使用“事件”。
from sqlalchemy.event import listen
from sqlalchemy import event, DDL
@event.listens_for(studentStatus.__table__, 'after_create')
def insert_initial_values(*args, **kwargs):
db.session.add(studentStatus(status_name='Waiting on admission'))
db.session.add(studentStatus(status_name='Waiting on student'))
db.session.add(studentStatus(status_name='Interaction Initiated'))
db.session.commit()
当我跑步时
python manage_db.py db init,
python manage_db.py db migrate,
python manage_db.py db upgrade
我没有遇到任何问题,但没有创建记录。
我尝试的另一种方法是,在我包含的 models.py 中
record_for_student_status = studentStatus(status_name="Waiting on student")
db.session.add(record_for_student_status)
db.session.commit()
print(record_for_student_status)
类模型代码:
class StudentStatus(db.Model):
status_id = db.Column(db.Integer,primary_key=True)
status_name = db.Column(db.String)
def __repr__(self):
return f"studentStatus('{self.status_id}','{self.status_name}')"
当我运行 python manage_db.py db init 时,我得到一个错误 Student_status,没有这样的表。
有人可以帮我在运行 db init 时如何将默认值添加到 student_status 表中吗?
我也尝试过使用烧瓶播种机。我已经安装了烧瓶播种器并添加了一个名为 seed.py 的新文件,然后我运行了烧瓶种子运行
我的seeds.py 看起来像这样
class studentStatus(db.Model):
def __init__(self, status_id=None, status_name=None):
self.status_id = db.Column(db.Integer,primary_key=True)
self.status_name = db.Column(db.String,status_name)
def __str__(self):
return "ID=%d, Name=%s" % (self.status_id, self.status_name)
class DemoSeeder(Seeder):
# run() will be called by Flask-Seeder
def run(self):
# Create a new Faker and tell it how to create User objects
faker = Faker(
cls=studentStatus,
init={
"status_id": 1,
"name": "Waiting on Admission"
}
)
# Create 5 users
for user in faker.create(5):
print("Adding user: %s" % user)
self.db.session.add(user)
我运行了 db init、db migrate 和 db upgrade。我没有得到任何问题。当我运行烧瓶种子运行时,出现此错误
Error: Could not locate a Flask application. You did not provide the "FLASK_APP" environment variable, and a "wsgi.py" or "app.py" module was not found in the current directory
我用谷歌搜索过,我试过了 导出 FLASK_APP=seeds.py
Then I ran the flask seed run ,I am getting an error ``` error could not import seeds.py```
Please help me in this.
What I need finally is when I do db initialization for the first time some default value have to be added to the database.
【问题讨论】:
标签: python-3.x sqlite flask sqlalchemy flask-sqlalchemy