繁体   English   中英

如何在 django 中为每个请求添加过滤器?

[英]How to add a filter in django for every request?

I want to add a security filter so that every request to my django app will go through the filter first and then let the request go through if the token from the header is valid.

我怎样才能在 django 中做到这一点?

谢谢。

您可以像这样添加新的中间件:

class SecurityMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        token = request.META.get('HTTP_AUTHORIZATION')
        if token != "Some Value":
             return HttpResponse('Unauthorized', status=401)
        response = self.get_response(request)
        return response

然后将其添加到settings.pyMIDDLEWARE中。

MIDDLEWARE = [
    ...
    'path.to.SecurityMiddleware'
]

更多信息可以在 自定义中间件文档和请求和响应 object文档中找到。

FYI, if you want to implement a standard authentication system like JWT or basic auths, consider using thrid party libraries like Simple JWT with Django Rest Framework or so on.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM