从登录用户的请求对象访问装饰器中的用户对象

时间:2019-07-26 10:04:41

标签: django-rest-framework

在由APIView()驱动的DRF应用程序中,我想添加一个装饰器。装饰器是:

<?php 
global $blog_id;
switch_to_blog(1); // site id from which you want to get the data
$pageid = 903; // post id from which you want to get the data
$post = get_post( $pageid ); 

restore_current_blog(); // restore to current blog
?>

错误出现在 request.user.user_profile.iccd 行中,该行指出user_profile不存在(确实存在)。

from django.core.exceptions import PermissionDenied
from payment.models import Purchase

def client_has_paid(function):
    '''
    Has the client paid or have active subscription fee?
    '''

    def wrap(request, *args, **kwargs):

        iccd = request.user.user_profile.iccd
        filters = {'iccd': iccd , 'active': 1 } 

        try:
            purchase = Purchase.objects.get(**filters)
            return function(request, *args, **kwargs)
        except:
            raise PermissionDenied

    wrap.__doc__ = function.__doc__
    wrap.__name__ = function.__name__
    return wrap

发出AnnonymousUser

在没有装饰器的情况下,只要传递的令牌有效,API便会打印正确的用户信息。

使用它的API是:

     print(request.user)

1 个答案:

答案 0 :(得分:0)

您可以直接创建drf样式权限类,并在装饰器中使用它,这将更加方便。只需尝试:

collectionView

并在您的视图中使用它,例如:

from rest_framework import permissions


class CustomPermission(permissions.BasePermission):

    def has_permission(self, request, view):

        iccd = request.user.user_profile.iccd
        filters = {'iccd': iccd , 'active': 1 } 

        try:
            purchase = Purchase.objects.get(**filters)
            return True
        except:
            raise False