class Middleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): request = Request(environ) cookies = request.cookies path = request.path if not isAuthenticated(cookies): #Redirect to /login return self.app(environ, start_response)
所以我有一个Middleware类,它应该从中获取cookies,request然后将其发送给一个isAuthenticated返回的函数True,或者False现在如果函数返回,False我需要重定向到/login页面,这可能吗?即使我没有request对象,我只有environ?
Middleware
cookies
request
isAuthenticated
True
False
/login
environ
是的,即使你只有 environ 而没有直接的 request 对象,你也可以通过修改 WSGI 中的 start_response 和返回适当的响应体来实现重定向功能。
start_response
以下是一个实现方法:
request.path
isAuthenticated()
302
Location
修改后的代码如下:
from werkzeug.wrappers import Request, Response class Middleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): # Create a request object using the WSGI environ request = Request(environ) cookies = request.cookies path = request.path # Check authentication if not isAuthenticated(cookies): # Redirect to /login response = Response("Redirecting to /login...", status=302) response.headers['Location'] = '/login' return response(environ, start_response) # If authenticated, continue with the original app return self.app(environ, start_response) # Example function to simulate user authentication check def isAuthenticated(cookies): # Example check: Look for a specific cookie return cookies.get("session_id") == "valid_session"
werkzeug.wrappers.Response
使用 response.headers['Location'] = '/login' 指定重定向目标。
response.headers['Location'] = '/login'
调用 Response(environ, start_response):
Response(environ, start_response)
Response 对象支持直接将 WSGI 环境 environ 和 start_response 传递给它,以便返回正确的 HTTP 响应。
Response
继续传递请求:
self.app(environ, start_response)
werkzeug.wrappers.Request
bash pip install werkzeug
创建一个简单的 WSGI 应用程序: python def app(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) return [b"Hello, authenticated user!"]
python def app(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) return [b"Hello, authenticated user!"]
包裹应用程序: python app_with_middleware = Middleware(app)
python app_with_middleware = Middleware(app)
使用 WSGI 服务器运行,例如 wsgiref: ```python from wsgiref.simple_server import make_server
wsgiref
if name == ‘main’: server = make_server(‘localhost’, 8080, app_with_middleware) print(“Serving on http://localhost:8080") server.serve_forever() ```
访问 http://localhost:8080,未认证用户将被重定向到 /login 页面,而已认证用户将看到 Hello, authenticated user! 的响应。
http://localhost:8080
Hello, authenticated user!