如何仅在django中为某些路径定义中间件? [英] how to define middleware only for certain paths in django?
问题描述
有没有在Django中为特定的路由或路由组定义中间件?就像laravel一样,我们可以将其定义如下:
is there anyway to define middleware for specific route or route groups in django? like laravel which we can define it as follows:
Route :: get('admin/profile',function(){})-> middleware('auth');
推荐答案
从历史上看,您可以利用一些钩子来执行类似的操作.但是如今,您可以肯定要重写:
Historically there have been a few hooks you can exploit to do something like this. But nowadays you can for sure override:
def process_view(self, request, view_func, view_args, view_kwargs):
...
在您的中间件类中,然后您可以从 request.path
解析视图/路由,并调度自定义逻辑(如果匹配或不匹配),或者可以匹配 view_func .__ name __ 代码>或类似的名称,等等.这取决于您的需求.
in your middleware class and then you could resolve the view/route from request.path
and dispatch custom logic if it matches or not, or you could match over view_func.__name__
or something similar, etc. Depends on your needs.
https://docs.djangoproject.com/zh/2.0/topics/http/middleware/#process-view
这篇关于如何仅在django中为某些路径定义中间件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!