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

Django REST Framework API上传格式限制与用户认证方法咨询

我来帮你搞定DRF上传API的格式限制和用户认证这两个问题,下面是具体的实现方案和代码修正:

一、限制上传API仅接收JSON和Excel(csv/xls/xlsx)格式

1. 配置请求解析器

首先要在视图中明确指定允许的解析器,只保留JSONParser(处理JSON请求)和MultiPartParser(处理文件上传的多部分表单请求),去掉不需要的FormParser。

2. 验证上传文件格式

在视图的post方法里添加格式校验逻辑,既可以通过文件后缀快速校验,也可以用更严谨的文件MIME类型检测(防止后缀篡改)。

二、推荐的用户认证方法

根据不同的业务场景,DRF有几种常用的认证方案供你选择:

  • TokenAuthentication:适合简单的服务端-客户端场景,每个用户对应一个固定Token,实现成本低,容易维护。
  • SessionAuthentication:如果你的API和Django Web应用共用会话体系,这个方案最方便,适合前后端不分离的项目。
  • JWTAuthentication:适合前后端分离或跨平台场景,Token自带用户信息,无需服务器存储会话,扩展性强。
  • BasicAuthentication:仅适合测试或内部服务场景,安全性低,不建议生产环境使用。

三、修正后的完整代码示例

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser, JSONParser
from rest_framework.response import Response
from rest_framework import status
from rest_framework.authentication import TokenAuthentication, SessionAuthentication
from rest_framework.permissions import IsAuthenticated
# 如果需要更严谨的MIME类型检测,需要先安装python-magic库:pip install python-magic
# import magic

class UploadAPIView(APIView):
    # 指定允许的解析器:JSON请求 + 文件上传请求
    parser_classes = [JSONParser, MultiPartParser]
    # 同时支持Token和Session认证,可根据需求调整
    authentication_classes = [TokenAuthentication, SessionAuthentication]
    # 要求用户必须认证才能访问该API
    permission_classes = [IsAuthenticated]

    def post(self, request, *args, **kwargs):
        # 处理JSON格式的请求
        if request.content_type == 'application/json':
            json_data = request.data
            # 这里添加你的JSON数据处理逻辑
            return Response(
                {"message": "JSON数据接收成功", "data": json_data},
                status=status.HTTP_200_OK
            )
        
        # 处理文件上传请求
        file_obj = request.FILES.get('file')
        if not file_obj:
            return Response(
                {"error": "请上传文件"},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        # 方式1:通过文件后缀验证格式
        allowed_extensions = ['csv', 'xls', 'xlsx']
        file_ext = file_obj.name.split('.')[-1].lower()
        if file_ext not in allowed_extensions:
            return Response(
                {"error": f"仅支持上传{', '.join(allowed_extensions)}格式的文件"},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        # 方式2:更严谨的MIME类型检测(可选)
        # file_mime = magic.from_buffer(file_obj.read(1024), mime=True)
        # allowed_mimes = [
        #     'text/csv', 
        #     'application/vnd.ms-excel', 
        #     'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        # ]
        # if file_mime not in allowed_mimes:
        #     return Response(
        #         {"error": "文件格式不符合要求,请上传合法的Excel/CSV文件"},
        #         status=status.HTTP_400_BAD_REQUEST
        #     )
        # # 注意:读取文件后要重置文件指针,避免后续处理出错
        # file_obj.seek(0)
        
        # 这里添加你的文件处理逻辑(比如读取Excel内容、写入数据库等)
        # ...
        
        return Response(
            {"message": f"文件{file_obj.name}上传成功"},
            status=status.HTTP_201_CREATED
        )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:38:46