类视图集的自定义装饰器

时间:2016-09-30 07:27:42

标签: python django python-decorators

我有一个像这样的视图集

class NeProjectsViewSet(viewsets.ViewSet):

   def list(self, request,org_unique_id):
       ''' something '''

   def create(self, request,org_unique_id):
       ''' something '''

   def retrieve(self):
       ''' something '''

   def update(self, request, pk):
       ''' something '''

   def partial_update(self, request):
       ''' something '''

   def destroy(self, request):
       ''' something '''

我有一个像这样的方法

def check_session(self,request):
    current_datetime = datetime.now()
    if ('last_login' in request.session):
        last = (current_datetime - datetime.strptime(request.session['last_login'], "%Y-%m-%d %H:%M:%S.%f")).seconds
        if last > base.SESSION_IDLE_TIMEOUT:
            del request.session['token']
            raise ValueError('Session Expired')
    else:
        request.session['last_login'] = str(current_datetime)
    return (request.session['token'] == request.META['HTTP_AUTHORIZATION'])

验证每个请求的会话,因为我需要在视图集中的每个方法之前调用此方法。我在某处编写自定义装饰器是更好的方法,所以如何为我的视图集实现自定义装饰器来检查会话请求

1 个答案:

答案 0 :(得分:0)

假设您正在使用DRF。

我认为你的方向错了。如果这是您的权限层的一部分,您应该只为视图集添加自定义权限类

http://www.django-rest-framework.org/api-guide/permissions/

from rest_framework import permissions

class ValidateSession(permissions.BasePermission):
    """
    Validate session expiration
    """

    def has_permission(self, request, view):
        current_datetime = datetime.now()
        if ('last_login' in request.session):
            last = (current_datetime - datetime.strptime(request.session['last_login'], "%Y-%m-%d %H:%M:%S.%f")).seconds
            if last > base.SESSION_IDLE_TIMEOUT:
                del request.session['token']
                return False
        else:
            request.session['last_login'] = str(current_datetime)
        return (request.session['token'] == request.META['HTTP_AUTHORIZATION'])

然后像这样添加

class NeProjectsViewSet(viewsets.ViewSet):
    permission_classes = (ValidateSession,)
    ...

假设您正在使用普通django

from django.contrib.auth.mixins import AccessMixin

class ValidateSessionMixin(AccessMixin):
    """
    Validate session
    """
    def has_permission(self):
        current_datetime = datetime.now()
        request = self.request
        if ('last_login' in request.session):
            last = (current_datetime - datetime.strptime(request.session['last_login'], "%Y-%m-%d %H:%M:%S.%f")).seconds
            if last > base.SESSION_IDLE_TIMEOUT:
                del request.session['token']
                return True
        else:
            request.session['last_login'] = str(current_datetime)
        return (request.session['token'] == request.META['HTTP_AUTHORIZATION'])

    def dispatch(self, request, *args, **kwargs):
        if not self.has_permission():
            return self.handle_no_permission()
        return super(ValidateSessionMixin, self).dispatch(request, *args, **kwargs)

然后像这样应用这个混合

class NeProjectsViewSet(ValidateSessionMixin, viewsets.ViewSet):
    ...