最近,我在Django中启动了一个新的简单项目。我写了一些中间件。但是在一种中间件中,我想知道调用哪个URL,因为我必须做出与URL相关的决定。
我使用了此代码:
import os
path = os.environ['PATH_INFO']
但是会产生错误,如下所述:
raise KeyError(key) from None
KeyError: 'PATH_INFO'
所以如何知道中间件中的URL?
您可以使用request
或request.path
attribute [Django-doc]获得request.path
中的路径。例如,您可以使用以下简单的中间件打印request.path_info
attribute [Django-doc]:
request.path_info
您可以使用path
访问URL的架构(from django.utils.deprecation import MiddlewareMixin
class MyMiddleware(MiddlewareMixin):
def process_request(self, request):
print(request.path)
,request.schema
attribute [Django-doc]等),并使用request.schema
访问请求的方法(http
,[C0 ],https
,request.method
attribute [Django-doc],request.method
等)。>