1

My REST APIs:

class FileView(APIView):
    parser_classes = (MultiPartParser,)
    authentication_classes = (BasicAuthentication,)
    permission_classes = (IsAuthenticated,)

@method_decorator(csrf_exempt)
@method_decorator(operation_logger)
def dispatch(self, request, *args, **kwargs):
    return super(FileView, self).dispatch(request, *args, **kwargs)

def post(self, request):
    print "xxxxpost"

The customized decorator:

def operation_logger(view_func):
    @wraps(view_func)
    def wrapper(request, *args, **kwargs):
        print "xxxx"
        comments = []
        psfile = None
        op = None
        remote_addr = request.META.get('REMOTE_ADDR')
        if request.user:
            user = request.user
            print request.user.username
        else:
            print "request.user is None"

        return view_func(request, *args, **kwargs)

    return wrapper

It seems that my decorator running before authentication finished. How to fix it? Thanks

UPDATE I added my middleware list below. But I am not sure it is related, because I created a branch new app for APIs, which is using djangorestframework.

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'lib.middleware.SessionTimeout',
    'lib.middleware.ForceTemporaryPasswordChange'
)
1

1 Answer 1

0

You can change the order your decorators are applied: the one nearest to def line will run first.

@method_decorator(operation_logger)
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
    return super(FileView, self).dispatch(request, *args, **kwargs)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.