Django REST框架-解析上传的csv文件

2sbarzqh  于 2023-01-27  发布在  Go
关注(0)|答案(2)|浏览(158)

我已经设置了Django REST框架端点,允许我上传一个csv文件。
www.example.com看起来像这样:serializers.py looks like this:

from rest_framework import serializers

class UploadSerializer(serializers.Serializer):
    file_uploaded = serializers.FileField()
    class Meta:
        fields = ['file_uploaded']

在我的www.example.com文件中,我尝试从上传的csv中读取数据,如下所示:views.py file, I'm trying to read data from uploaded csv like this:

class UploadViewSet(viewsets.ViewSet):
    serializer_class = UploadSerializer

    def create(self, request):
        file_uploaded = request.FILES.get('file_uploaded')
    
        with open(file_uploaded, mode ='r')as file:
            csvFile = csv.reader(file)
            for lines in csvFile:
                print(lines)

我收到以下错误:

... line 37, in create
    with open(file_uploaded, mode ='r') as file:
TypeError: expected str, bytes or os.PathLike object, not InMemoryUploadedFile

我已经检查了file_uploaded的类型(),它是<class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
我怎样才能把这个文件读入字典或 Dataframe ,以便从中提取所需的数据?

fcwjkofz

fcwjkofz1#

当你请求.FILES.get('file_uploaded')时,它返回一个InMemoryUploadedFile,它是一个文件对象的 Package 器。你可以使用file属性访问文件对象。

file_uploaded # <InMemoryUploadedFile: xxx (xxx/xxx)>
file_object = file_uploaded.file

然后可以打开此file_object。

sgtfey8w

sgtfey8w2#

InMemoryFileObject的使用方式与打开文件的使用方式几乎相同,因此您不需要打开它。

def create(self, request):
    file_upload = request.FILES.get("file_uploaded")
    csvFile = csv.reader(file_upload)
    for line in csvFile:
        print(line)

这里有一些关于django中文件处理的有用信息。
https://docs.djangoproject.com/en/4.1/topics/http/file-uploads/#handling-uploaded-files-with-a-model

相关问题