简体   繁体   中英

Django REST framework - parse uploaded csv file

I have setup Django REST framework endpoint that allows me to upload a csv file.

The serializers.py looks like this:

from rest_framework import serializers

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

In my 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)

I'm getting the following error:

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

I have checked type() of file_uploaded and It is <class 'django.core.files.uploadedfile.InMemoryUploadedFile'>

How can I read this file into dictionary or dataframe so I can extract the data I need from it?

When you do request.FILES.get('file_uploaded') it returns back an InMemoryUploadedFile which is a wrapper around a file object. You can access the file object using the file attribute.

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

This file_object can then be opened.

an InMemoryFileObject can be used pretty much in the same way as an open file., so you don't need to open it.

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

This has some good information on file handling in django.

https://docs.djangoproject.com/en/4.1/topics/http/file-uploads/#handling-uploaded-files-with-a-model

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM