在应用程序上下文之外工作

2024-09-30 12:18:02 发布

您现在位置:Python中文网/ 问答频道 /正文

当我实例化flask应用程序时,我正试图针对类实例化一个对象,但是我收到了一个关于在flask应用程序上下文之外工作的错误。下面是我目前的代码,任何帮助都将不胜感激。我正在等待引入该模块并针对其调用对象,直到“创建应用程序”成功运行,但仍然无法确定问题的根本原因

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.

Tags: theinfromimportconfigappflaskget

热门问题