django 如何多次访问WSGIRequest?

bqucvtff  于 2023-07-01  发布在  Go
关注(0)|答案(1)|浏览(128)

我有一个APIView调用另一个APIView进行检查,但经过几个小时的搜索,我现在知道它不容易访问HttpRequest后变成流对象,并会导致以下错误:
django.http.request.RawPostDataException:从请求的数据流中阅读后无法访问正文
有些人建议使用request.data而不是request.body,但在这种情况下我不能这样做:

B.views.py

from rest_framework import views
from rest_framework.response import Response

from A.views import A

class B(views.APIView):

   def post(self, request, *args, **kwargs):

       http_response = A.as_view()(request._request)

       # So far so good, but if I want to access request.data after calling A.as_view() will raise 
       # the exception. 

       return Response(http_response.data)

如何处理这个问题?

来源issue2774

9ceoxa92

9ceoxa921#

我发现了很多建议:
1-使用Middleware来存储request.body,以便以后需要时使用。
2-使用自定义解析器类,在将原始数据转换为stream对象之前,将其存储为request对象中的属性。
我发现这两个都有点复杂,所以我改变了从某个DRF View调用另一个APIView的方式,如图所示:

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

from A.views import A
from C.views import C

class B(views.APIView):

   def post(self, request, *args, **kwargs):

       # Initialize a new instance of class view 'A'  
       a_view = A()

       # Calling HTTP 'POST' method with DRF request object.
       a_http_response = a_view.post(request)

       if a_http_response.status_code == status.status.HTTP_200_OK:

          # Initialize a new instance of class view 'C'  
          c_view = C()

          # Another calling HTTP 'POST' method with DRF request object.
          c_http_response = c_view.post(request)

          return(c_http_response.data)
       
       else:
          return Response(a_http_response.data)

相关问题