我正在开发一个带有机器学习模型的应用程序,以预测具有特定功能的汽车的价格。
作者在this tutorial中指出:
未在app.app_context()中导入,初始化或注册的任何应用程序部分均有效 不存在。
并在app_context()中导入路由:
def create_app():
...
with app.app_context():
# Include our Routes
from . import routes
在我的'init.py'中,我必须在app_context内部导入并初始化MLModelConfigs
,因为否则会导致RuntimeError: Working outside of application context.
但是,我可以将routes
导入app_context
之外,它仍然可以使用。
为什么会有不同的行为?
我的情况是:
我具有以下结构:
├── webapp
├── car_prices.py
├── congif.py #paths
│ ├── app
│ ├── static
│ ├── templates
│ ├── routes.py
│ ├── utils.py
│ ├── models.py
│ ├── __init__.py
'car_prices.py':
from app import app
' init .py'
from flask import Flask
from config import Config
app = Flask(__name__)
app.config.from_object(Config)
with app.app_context():
from app.models import MLModelConfigs
model_config = MLModelConfigs
from app import routes
'models.py'
from .utils import process_features, load_freshest_model
from flask import current_app
class MLModelConfigs:
__tablename__ = 'MLmodelConfigs'
model = load_freshest_model(current_app.config['PATH_MODELS'])
features_info, option_values = process_features(current_app.config['PATH_FEATURES_INFO'])
问题:
1.为什么在app_context()之外导入路由有效?
2.为什么在外部导入和初始化MLModelConfigs
app_context导致RuntimeError: Working outside of application context.
´