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

在Django REST Framework的APIView中替代rfile.read()的方案

在Django REST Framework的APIView中替代rfile.read()的方案

在DRF的APIView里,你可以通过以下两种方式替代rfile.read()获取原始请求内容:

1. 直接获取完整请求体(request.body)

request.body是DRF Request对象自带的属性,直接返回字节类型的原始请求体,和rfile.read()读取全部内容的效果完全一致,适合请求体体积不大的场景:

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

class CustomAPIView(APIView):
    def post(self, request):
        # 获取原始字节格式的请求体
        raw_body = request.body
        # 按需解码为字符串(示例用UTF-8编码)
        body_str = raw_body.decode('utf-8')
        # 后续业务处理逻辑...
        return Response({"received_content": body_str})

2. 流式读取请求体(request.stream)

如果需要像rfile那样流式分块读取(比如处理大文件上传、超大请求),可以用request.stream,它是一个类文件对象,支持read()方法:

class StreamAPIView(APIView):
    def post(self, request):
        # 一次性读取全部流式内容
        full_raw_data = request.stream.read()
        
        # 或者分块读取(示例:每次读取1024字节)
        chunk_size = 1024
        current_chunk = request.stream.read(chunk_size)
        while current_chunk:
            # 处理当前块的业务逻辑
            current_chunk = request.stream.read(chunk_size)
        
        return Response({"status": "stream_processed"})

注意事项

  • request.body会把整个请求体加载到内存,请求体过大时可能导致内存占用过高,这种情况优先用request.stream流式处理。
  • 同一请求中,一旦通过request.body读取过内容,request.stream的指针会移到末尾,后续再读取request.stream会返回空;反之亦然,所以只能选择一种读取方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 07:48:45