【问题标题】:django.http.request.RawPostDataException: You cannot access body after reading from request's data streamdjango.http.request.RawPostDataException:从请求的数据流中读取后,您无法访问正文
【发布时间】:2020-11-12 16:40:07
【问题描述】:

我正在制作一个 API,我得到了 django.http.request.RawPostDataException: You cannot access body after reading from request's data stream 这个错误 我认为您无法访问数据 scnd 时间: 这是我的代码

def get_posts(request):
    print('Called')
    print(request.body)
    data = json.loads(request.body) #Error here
        
    user = data['user']
    print(user)
    
    user_profile = User.objects.all().get(username=user).profile
    
    posts = Post.objects.all().filter(user=user_profile)
    
    if len(posts) == 0:
        return JsonResponse({'last':True,'posts':None})
    
    
    if len(posts) < 4:
        
        data_ = PostSerilizer(data=posts,many=True)
        
        return Response(data=data_)
    
    
    
    else:
        deliverd_count = data['deliverd_count']
        
        posts_to_be_returned = posts[deliverd_count:deliverd_count+4]
        
        to_be_returned = {
            'posts':posts_to_be_returned,
            'last':False,
        }
        
        return JsonResponse(to_be_returned) 

我如何才能第二次访问数据 以下是错误的原因,但我不知道如何解决 当我使用 api_view 装饰器时——这是必要的——并且它访问数据并且由于 django 只允许您访问数据一次,我无法访问它

【问题讨论】:

  • 你不能先将request.body分配给一个变量吗?然后稍后再次读取变量?我还没试过,只是好奇。
  • 其实没有,因为是装饰器自动加入的
  • 当你第一次分配copy_body = request.body时它使用装饰器,但是当你访问copy_body时它不应该再次访问request.body。
  • 谢谢,但我解决了,我接受了 request.data,它有点像。仍然需要回复

标签: javascript python django django-rest-framework


【解决方案1】:

我现在得到了答案。你可以说 data = request.data ,是一样的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-08
    • 2021-03-13
    • 1970-01-01
    • 2019-11-21
    • 2023-03-14
    • 2014-02-18
    • 2020-01-29
    • 2017-06-19
    相关资源
    最近更新 更多