Access request data from django decorator.

Access request data from django decorator.

Example django view:

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status



class ExampleAPIView(APIView):
    @check_user_identity
	def post(self, request):

    	# write your rest of the code here
        return Response(data=your_response, status=status.HTTP_200_OK)

A decorator takes a function add some functionality and returns it. This is also called meta-programming because a part of the program tries to modify another part of the program at compile time. Here is your example decorator:

from rest_framework.response import Response
from rest_framework import status


def check_user_identity(function):
	def wrap(request, *args, **kwargs):
	    response_check_user, status_code = check_user_validity(requested_data=args[0].data)
	    if status_code == status.HTTP_200_OK:
	        return function(request, *args, **kwargs)
	    return Response(data=INVALID_USER, status=status.HTTP_400_BAD_REQUEST)
	

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

Here you can access requested data from decorator by args[0].data. As simple as that :)

要查看或添加评论,请登录

Md Imran Sheikh的更多文章

社区洞察

其他会员也浏览了