我第一次尝试同时使用flask应用程序工厂模式和pytest框架。我从sqlite db后端的基本健全性测试开始,虽然到目前为止测试运行良好,并且我看到测试db文件创建成功,但falsk_sqlalchemy告诉我它没有定义db后端。我试图找出pdb和交互式控制台的问题--一切看起来都很正常。看起来这似乎与谁能帮我弄明白问题出在哪里有关?
(venv) C:\Users\dv\PycharmProjects\ste-speach-booking>python -m pytest tests/
=========================== test session starts ============================
platform win32 -- Python 3.6.8, pytest-5.1.1, py-1.8.0, pluggy-0.12.0
rootdir: C:\Users\dv\PycharmProjects\ste-speach-booking
collected 3 items
tests\test_models.py ... [100%]
============================= warnings summary =============================
tests/test_models.py::test_init
C:\Users\d837758\PycharmProjects\ste-speach-booking\venv\lib\site-packages\flask_sqlalchemy\__init__.py:814: UserWarning: Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. Defaulting SQLALCHEMY_DATABASE_URI to "sqlite:///:memory:".
'Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. '
Test_models中的初始测试:
import pytest
import src.models
import datetime
def test_ActionTypes(db):
actiontype1 = src.models.Act_types(action_tyoe='workshop')
db.session.add(actiontype1)
db.session.commit()
actiontype2 = src.models.Act_types(action_tyoe='speech')
db.session.add(actiontype2)
db.session.commit()
count = db.session.query(src.models.Act_types).count()
assert count is 2
def test_meeting_creation(db):
meeting = src.models.Meeting(
_date = datetime.datetime.strptime('2018-12-19', "%Y-%m-%d"),
)
db.session.add(meeting)
db.session.commit()
db的conftest fixture:
import os
import pytest
import src.config
from src import create_app
from src import db as _db
@pytest.fixture(scope='session')
def db():
"""Session-wide test database."""
TESTDB_PATH = src.config.testDB
print(TESTDB_PATH)
if os.path.exists(TESTDB_PATH):
os.unlink(TESTDB_PATH)
app = create_app(config=src.config.TestingConfig)
with app.app_context():
_db.create_all()
yield _db
_db.drop_all()
os.unlink(TESTDB_PATH)
应用程序工厂:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def create_app(config=None):
"""Construct the core application."""
app = Flask(__name__, instance_relative_config=True)
db.init_app(app)
if config is None:
app.config.from_object(config.BaseConfig)
else:
app.config.from_object(config)
with app.app_context():
# Imports
from . import routes
db.create_all()
return app
config.py:
basedir = os.path.abspath(os.path.dirname(__file__))
baseDB = os.path.join(basedir, 'app.db')
devDB = os.path.join(basedir, 'dev_app.db')
testDB = os.path.join(basedir, 'testing_app.db')
class BaseConfig(object):
DEBUG = False
TESTING = False
SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
'sqlite:///' + baseDB
SQLALCHEMY_TRACK_MODIFICATIONS = False
class TestingConfig(BaseConfig):
DEBUG = False
TESTING = True
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
'sqlite:///' + testDB
发布于 2019-08-30 14:33:44
问题出在create_app()
中应用程序组件的配置顺序上。
调用db.init_app(app)
时,它执行的第一个操作是(source):
if (
'SQLALCHEMY_DATABASE_URI' not in app.config and
'SQLALCHEMY_BINDS' not in app.config
):
warnings.warn(
'Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. '
'Defaulting SQLALCHEMY_DATABASE_URI to "sqlite:///:memory:".'
)
注意到这个警告了吗?
它会立即在app.config
中查找所需的配置。该方法继续接受应用程序提供的配置或设置默认值,在本例中,默认值是内存中的数据库。
在您的create_app()
实现中,对db.init_app()
的调用是在配置应用程序本身之前进行的,其中包含以下内容:
db.init_app(app)
if config is None:
app.config.from_object(config.BaseConfig)
else:
app.config.from_object(config)
在填充app.config
之前,应用程序上不存在任何带有SQLALCHEMY_
前缀的配置,因此当db.init_app()
查找它们时,它们不会被找到,并使用默认值。将db
的配置移动到app
的配置之后可以解决此问题:
if config is None:
app.config.from_object(config.BaseConfig)
else:
app.config.from_object(config)
db.init_app(app)
这与this question非常相似,但是我认为您的是典型设置( create_app()
的范围和配置方法)的一个更好的例子,因此值得回答。
发布于 2021-09-25 19:42:42
确保app.config
字典具有以下内容:
app = Flask(__name__) # The URI config should be initialized after flask
['SQLALCHEMY_DATABASE_URI'] = 'to your database string'
然后:
db = SQAlchemy(app)
也有同样的问题,因为我在数据库Uri连接之后进行了Flask初始化。
https://stackoverflow.com/questions/57720565
复制相似问题