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

如何在drf-spectacular中设置响应媒体类型为application/octet-stream

在drf-spectacular中配置application/octet-stream类型的响应Schema

直接用@extend_schema装饰器,通过responses参数指定响应的媒体类型和结构即可,以下是完整实现示例:

1. 导入所需工具

from drf_spectacular.utils import extend_schema
from rest_framework.views import APIView
from rest_framework.response import Response

2. 编写视图并配置Schema

class FileDownloadView(APIView):
    @extend_schema(
        summary="下载文件",
        description="该API端点允许用户下载二进制文件",
        responses={
            200: {
                "description": "文件下载成功",
                "content": {
                    "application/octet-stream": {
                        "schema": {
                            "type": "string",
                            "format": "binary",
                            "description": "二进制文件"
                        }
                    }
                }
            }
        }
    )
    def get(self, request):
        # 这里编写你的文件下载逻辑(示例返回测试二进制内容)
        response = Response(b"test binary content", content_type="application/octet-stream")
        response["Content-Disposition"] = 'attachment; filename="test.bin"'
        return response

生成的Schema效果

最终生成的OpenAPI Schema会和你期望的结构一致:

paths:
  /file-download:
    get:
      summary: 下载文件
      description: 该API端点允许用户下载二进制文件
      responses:
        '200':
          description: 文件下载成功
          content:
            application/octet-stream:
              schema:
                type: string
                format: binary
                description: 二进制文件

关键说明

  • 在responses字典中,以状态码为键,值是包含description和content的配置字典
  • content的键直接指定目标媒体类型application/octet-stream,对应值内定义二进制文件的Schema结构
  • 视图返回时记得设置content_type="application/octet-stream",保证实际响应和Schema定义一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 09:14:56