django 使用FileField,在插入数据库之前打开文件

rseugnpd  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(99)

我有modelsserializer和带有FileField的视图集

class Drawing(SafeDeleteModel):
    drawing = f.FileField(upload_to='uploads/')

class DrawingSerializer(ModelSerializer):
    drawing = serializers.FileField()

class DrawingViewSet(viewsets.ModelViewSet):
    queryset = m.Drawing.objects.all()
    serializer_class = s.DrawingSerializer
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)    
        serializer.is_valid(raise_exception=True)
            
        print("serializer request:",request.data['drawing']) # this is myfile.pdf
        self.perform_create(serializer)
        print("serializer seliarizer",serializer.data['drawing']) 
 # myfile_ccA3TjY.pdf
        try:
         doc = fitz.open(file_path) # open to check if it is correct pdf
        except;
         raise Exception("file is not valid pdf")

字符串
上传文件时,request.data['drawing']myfile.pdfserializer.data['drawing']为真实的myfile_ccA3TjY.pdf。(当存在同名文件时)
因此,要使用fitz打开文件,我需要知道真实的名称myfile_ccA3TjY.pdf
我必须执行self.perform_create才能知道真实的的文件名,它会创建行。但是,我想取消插入到数据库时,文件不是有效的pdf。
使用此代码,即使文件不正确,也会执行数据库插入。
有没有办法不调用self.perform_create就打开文件?

qyswt5oh

qyswt5oh1#

根据文档,可以从内存中创建文件对象。你可以这样做:

def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)    
        serializer.is_valid(raise_exception=True)
            
        
        try:
         doc = fitz.open(“pdf”, request.data['drawing'])
         # or doc = fitz.open(“pdf”, request.data['drawing'].read())
        except;
         raise Exception("file is not valid pdf") 
        self.perform_create(serializer)

字符串

相关问题