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

Django中GET方法调用异常出现RecursionError问题排查与修复建议

问题:Django APIView GET请求出现RecursionError递归错误

代码实现

视图类代码

class merge(APIView):
 def get(self, request):
        id = request.GET.get('id')
        comp = request.GET.get('comp')
        queryset = tablename.objects.filter(id=id, comp=comp)
        token_instance = queryset.first()
        if token_instance:
            acnt_token = token_instance.token
            serializer = AcToknSerializers(queryset, many=True)
            return acnt_token, serializer.data
        else:
            return None, []

序列化器代码

class AcToknSerializers(serializers.ModelSerializer):
    class Meta:
        model = tablename
        fields = ['token']

请求URL

http://127.0.0.1:8000/api/syncall/0aabf5ee/75v20375n02

错误信息

RecursionError at http://127.0.0.1:8000/api/comp-info/syncall/0aabf5ee/75v20375n02
maximum recursion depth exceeded while calling a Python object

Request Method: GET
Request URL: http://127.0.0.1:8000/api/comp-info/syncall/0aabf5ee/75v20375n02
Django Version: 5.0.1
Exception Type: RecursionError
Exception Value:
maximum recursion depth exceeded while calling a Python object
Exception Location: C:\Users\AmiteshSahay\AppData\Local\Programs\Python\Python310\lib\logging_init_.py, line 424, in usesTime


修复方案

问题根源

  1. 返回值不符合DRF要求:APIView的get方法必须返回Response对象,直接返回元组或None会触发DRF内部异常处理逻辑,进而引发递归调用。
  2. 参数获取方式错误:请求URL用的是路径参数(/0aabf5ee/75v20375n02),但代码里用request.GET.get()获取查询参数(即?id=xxx&comp=xxx格式),导致id和comp始终为None,查询不到数据后返回非法值,加剧问题。

修复后的代码

视图类(修正返回值与参数获取)

from rest_framework.response import Response
from rest_framework import status

class merge(APIView):
    def get(self, request, id, comp):  # 接收URL路径参数
        token_instance = tablename.objects.filter(id=id, comp=comp).first()
        if token_instance:
            return Response({
                'acnt_token': token_instance.token,
                'data': AcToknSerializers(token_instance).data
            }, status=status.HTTP_200_OK)
        else:
            return Response({
                'acnt_token': None,
                'data': []
            }, status=status.HTTP_404_NOT_FOUND)

URL配置(确保路径参数与视图匹配)

from django.urls import path
from .views import merge

urlpatterns = [
    path('api/syncall/<str:id>/<str:comp>/', merge.as_view(), name='syncall'),
]

额外注意事项

  • 模型类名tablename建议遵循Python命名规范改为首字母大写(如TableName)。
  • 序列化单个实例时无需添加many=True参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 13:13:36