我正在尝试在实例化 Flask 应用程序时针对类实例化一个对象,但是我收到关于在 Flask 应用程序上下文之外工作的错误。以下是我当前的代码,任何帮助将不胜感激。我正在等待引入该模块并针对它调用一个对象,直到“create_app”成功运行之后,但仍然无法确定我的问题的根本原因。
from app import create_app
import os
app = create_app()
# instantiate the object
from app.main.dpt_manager import DPTManager
obj = DPTManager() # here is where I am instantiating the object I would like
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=5000)
应用初始化:
from flask_api import FlaskAPI
from app.config import Config
def create_app():
"""Instantiates and initialize the Flask application"""
app = FlaskAPI(__name__)
app.config.from_object(Config)
from app.api.casify_service.authorization import auth
from app.api.casify_service.predict import predict
app.register_blueprint(auth)
app.register_blueprint(predict)
return app
配置文件:
import os
from os.path import join, dirname
from dotenv import load_dotenv
class Config:
"""Base configuration."""
dotenv_path = join(dirname(__file__), ".env")
load_dotenv(dotenv_path)
ldaps_config = dict()
API_VERSION = "1.0.0"
# auth related key / values
SECRET_KEY = os.environ.get("SECRET_KEY")
TOKEN_EXPIRE_HOURS = 24
DPTManager 类:
from flask import current_app
class DPTManager:
def __init__(self):
token_age_h = current_app.config.get("TOKEN_EXPIRE_HOURS") # failure occurs here
回溯:
Traceback (most recent call last):
File "/Users/aclinton/Documents/projects/casify_autoescalation/casify/casify-service/run.py", line 10, in <module>
dpt_manager = DPTManager()
File "/Users/aclinton/Documents/projects/casify_autoescalation/casify/casify-service/app/main/dpt_manager.py", line 21, in __init__
token_age_h = current_app.config.get("TOKEN_EXPIRE_HOURS")
File "/Users/aclinton/Documents/environments/casify-service/lib/python3.9/site-packages/werkzeug/local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
File "/Users/aclinton/Documents/environments/casify-service/lib/python3.9/site-packages/werkzeug/local.py", line 306, in _get_current_object
return self.__local()
File "/Users/aclinton/Documents/environments/casify-service/lib/python3.9/site-packages/flask/globals.py", line 52, in _find_app
raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context(). See the
documentation for more information.