You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3 Django中如何在装饰器wrapper函数中访问request数据

解决Django APIView装饰器无法访问request数据的问题

你遇到的问题根源是类视图的方法(比如APIView的post)第一个参数是类实例self,而非request,但你写的装饰器wrapper把第一个参数当成了request,导致实际传入的是self,而self没有data属性,因此无法正确访问请求数据。

以下是两种可行的解决方法:

方法一:调整装饰器适配类方法参数

修改装饰器的wrapper函数,先接收self,再接收request参数,调用原视图方法时传入self:

def my_decorator(view_func):
    def wrapper(self, request, *args, **kwargs):
        print('-start-')
        print(request.data)  # 此时request是正确的请求对象
        print(args)
        print(kwargs)
        print('-now-')
        response = view_func(self, request, *args, **kwargs)
        return response
    return wrapper


class HandymanCompleteProfileIos(APIView):
    @my_decorator
    def post(self, request, format=None):
        return JsonResponse({"A":"a"})

方法二:使用Django官方method_decorator(推荐)

method_decorator是Django提供的工具,专门用于将函数装饰器转换为可适配类方法的装饰器,自动处理self参数的传递,无需修改原装饰器:

  1. 先导入method_decorator:
from django.utils.decorators import method_decorator
  1. 装饰类视图方法:
def my_decorator(view_func):
    def wrapper(request, *args, **kwargs):
        print('-start-')
        print(request.data)
        print(args)
        print(kwargs)
        print('-now-')
        response = view_func(request, *args, **kwargs)
        return response
    return wrapper


class HandymanCompleteProfileIos(APIView):
    @method_decorator(my_decorator)
    def post(self, request, format=None):
        return JsonResponse({"A":"a"})

也可以直接装饰整个类(指定要应用装饰器的方法名):

@method_decorator(my_decorator, name='post')
class HandymanCompleteProfileIos(APIView):
    def post(self, request, format=None):
        return JsonResponse({"A":"a"})

这种方式的优势是你的装饰器可以同时兼容普通函数视图和类视图,通用性更强。

内容的提问来源于stack exchange,提问作者Jaskaran Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 06:35:55