如何知道在中间件中输入了哪种类型的URL?

问题描述 投票:0回答:1

最近,我在Django中启动了一个新的简单项目。我写了一些中间件。但是在一种中间件中,我想知道调用哪个URL,因为我必须做出与URL相关的决定。

我使用了此代码:

import os

path = os.environ['PATH_INFO']

但是会产生错误,如下所述:

    raise KeyError(key) from None
KeyError: 'PATH_INFO'

所以如何知道中间件中的URL?

django middleware url-pattern
1个回答
1
投票

您可以使用requestrequest.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 ],httpsrequest.method attribute [Django-doc]request.method等)。>

© www.soinside.com 2019 - 2024. All rights reserved.