![](/img/trans.png)
[英]RuntimeError: Working outside of application context. in my flask app
[英]Flask `RuntimeError: Working outside of application context.` from Middleware
这是中间件类:
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
类内部访问它?
想通了,我必须将actual or
完整的app into
传递app into
中间件, not just the
像这样not just the
wsgi`:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.