如何在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
相关产品推荐
相关产品推荐

