Home > other >  Django REST framework - parse uploaded csv file
Django REST framework - parse uploaded csv file

Time:01-26

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?

CodePudding user response:

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.

CodePudding user response:

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

  • Related