【问题标题】:Flask `RuntimeError: Working outside of application context.` from Middleware烧瓶`RuntimeError:在应用程序上下文之外工作。`来自中间件
【发布时间】:2021-09-30 18:48:24
【问题描述】:

这是中间件类:

class Middleware:
    def __init__(self, app):
        self.app = app


    def __call__(self, environ, start_response):
        request = Request(environ)
        cookies = request.cookies
        path = request.path

        environ['isAuthenticated'] = isAuthenticated(cookies)

        return self.app(environ, start_response)


def isAuthenticated(cookies):
    if (len(cookies)) > 0 :
        if 'jwt' in cookies:
            payload = decodeJWT(cookies['jwt'])
            connection = connect_db()
            
            
            return payload
    else:
        return False

这里是ConnectDB.py

def connect_db():
    host = current_app.config['HOST']
    db = current_app.config['DB']
    username = current_app.config['USERNAME']
    password = current_app.config['PASSWORD']
    
    connection = psycopg2.connect(host=host, database=db, user=username, password=password, port=5432, cursor_factory=RealDictCursor)
    return connection

我在激怒middleware 喜欢这个:

app = Flask(__name__)
app.config.from_object('SETTINGS')
app.wsgi_app = Middleware(app.wsgi_app)

我收到了这个错误:

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.

我知道我需要从应用程序上下文中调用 connect_db 来访问数据库凭据,但我如何从 Middleware 类中访问它?

【问题讨论】:

标签: python flask


【解决方案1】:

想通了,我必须像这样传递actual or fullapp intoMiddlewarenot just thewsgi`:

app = Flask(__name__)
app.config.from_object('SETTINGS')
app.wsgi_app = Middleware(app.wsgi_app, app)

然后Middleware变成这样:

class Middleware:
    def __init__(self, wsgi, app):
        self.wsgi = wsgi
        self.app = app


    def __call__(self, environ, start_response):
        request = Request(environ)
        cookies = request.cookies
        path = request.path

        with self.app.app_context():
            environ['isAuthenticated'] = isAuthenticated(cookies)

        return self.wsgi(environ, start_response)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-09
    • 2012-10-29
    • 1970-01-01
    • 2015-10-05
    • 1970-01-01
    相关资源
    最近更新 更多