换句话说,如何为数据库创建生成迁移,或者这是一种反模式?
我在跑步
python manage.py db migrate -m "init"
获取
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) FATAL: database "auth" does not exist
manage.py
# manage.py
import os
import unittest
import coverage
from flask_script import Manager
from authentek.app import create_app as initialize_app
from authentek.logger import log
from authentek.extensions import db, migrate
from authentek.database.models import User, BlacklistToken # noqa
from flask_migrate import MigrateCommand
app = initialize_app(False, True)
manager = Manager(app)
migrate.init_app(app)
manager.add_command('db', MigrateCommand)
print(app.extensions)
COV = coverage.coverage(
branch=True,
include='authentek/*',
omit=[
'authentek/tests/*',
]
)
COV.start()
@manager.command
def test():
"""Runs the unit tests without test coverage."""
tests = unittest.TestLoader().discover('authentek/tests', pattern='test*.py')
result = unittest.TextTestRunner(verbosity=2).run(tests)
if result.wasSuccessful():
return 0
return 1
@manager.command
def cov():
"""Runs the unit tests with coverage."""
tests = unittest.TestLoader().discover('authentek/tests')
result = unittest.TextTestRunner(verbosity=2).run(tests)
if result.wasSuccessful():
COV.stop()
COV.save()
print('Coverage Summary:')
COV.report()
basedir = os.path.abspath(os.path.dirname(__file__))
covdir = os.path.join(basedir, 'tmp/coverage')
COV.html_report(directory=covdir)
print('HTML version: file://%s/index.html' % covdir)
COV.erase()
return 0
return 1
@manager.command
def drop_db():
"""Drops the db tables."""
db.drop_all()
if __name__ == '__main__':
manager.run()
答案 0 :(得分:1)
出于安全目的,您不希望赋予应用程序创建或销毁数据库的权力,您所想要的就是使应用程序可以对单个数据库进行读写访问。
因此,您通常必须手动创建数据库,或者通过具有数据库管理权限的单独脚本创建数据库。
对于单元测试,我认为只要您有用于测试的单独数据库服务器,配置数据库管理员凭据就不会有风险,因此不会影响测试环境之外的其他数据库。在这种情况下,您可以添加使用SQL创建和销毁数据库的函数。