【发布时间】: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 类中访问它?
【问题讨论】: