Python';无法在中间件中获取头值

Python';无法在中间件中获取头值,python,flask,Python,Flask,我必须计划在我的新项目中使用flask框架。所以我今天就开始学习了。我能理解基本的路由和中间件。我试图在中间件中读取头值,之后,我需要验证这些头。但我无法读取标题的中间件。请看下面我的代码 app.py from flask import Flask from flask_restx import Resource, Api import middleware app = Flask(__name__) app.wsgi_app = middleware.middleware(app.wsgi

我必须计划在我的新项目中使用flask框架。所以我今天就开始学习了。我能理解基本的路由和中间件。我试图在中间件中读取头值,之后,我需要验证这些头。但我无法读取标题的中间件。请看下面我的代码

app.py

from flask import Flask
from flask_restx import Resource, Api
import middleware

app = Flask(__name__)
app.wsgi_app = middleware.middleware(app.wsgi_app)
api = Api(app)


@api.route('/hello')
class HelloWorld(Resource):
    def get(self):
        return {'hello': 'world'}


if __name__ == '__main__':
    app.run(debug=True)
中间件.py

从烧瓶进口请求

class middleware():
    '''
    Simple WSGI middleware
    '''

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

    def __call__(self, environ, start_response):
        if 'auth-key' in request.headers:
            authKey = request.headers['auth-key']
            print(authKey)
        return self.app(environ, start_response)
但是我得到了下面的错误

Traceback (most recent call last):
  File "/home/testuser/Projects/Python/m-registry/lib/python3.8/site-packages/flask/app.py", line 2464, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/testuser/Projects/Python/m-registry/middleware.py", line 14, in __call__
    if 'auth-key' in request.headers:
  File "/home/testuser/Projects/Python/m-registry/lib/python3.8/site-packages/werkzeug/local.py", line 347, in __getattr__
    return getattr(self._get_current_object(), name)
  File "/home/testuser/Projects/Python/m-registry/lib/python3.8/site-packages/werkzeug/local.py", line 306, in _get_current_object
    return self.__local()
  File "/home/testuser/Projects/Python/m-registry/lib/python3.8/site-packages/flask/globals.py", line 38, in _lookup_req_object
    raise RuntimeError(_request_ctx_err_msg)
RuntimeError: Working outside of request context.

This typically means that you attempted to use functionality that needed
an active HTTP request.  Consult the documentation on testing for
information about how to avoid this problem.
请大家帮忙解决这个问题


提前感谢

在Flask应用程序中创建了
请求
对象,但您的中间件基本上位于WSGI服务器和该Flask应用程序之间。因此,您无法访问中间件中的请求对象

您可以尝试将逻辑编写为@before\u请求处理程序或类似的东西。比如说

@app.before_request
     def handle_every_request():
            if 'auth-key' in request.headers:
                authKey = request.headers['auth-key']
                #DO SOEMTHIGN HERE?