Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

How to save Audio file to django model from the server itself with REST API

I am:

  • Sending .wav file with API Class
  • Converting to .mp3 with pydub
  • Saving converted file to MEDIA_ROOT

I want:

  • Save the converted file (.mp3) to my model.

I have:

  • AWS S3 bucket on production, everything saved in my models lands there.
  • I have model with FileField:
def content_file_name(instance, filename):
    filename = "{}_".format(today.strftime("%y-%d-%m")) + filename
    return os.path.join('content', "{}".format(instance.user.email), 'tracks', filename)


class Track(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE, null=True
    )

    # ...
    file = models.FileField(
        upload_to=content_file_name, null=True, blank=True)
  • I am using MultiPartParser and audio gets saved correctly but the original one in .wav. I want to save mp3 once I convert it.
from django.core.files.storage import FileSystemStorage


class TrackAPIView(UpdateAPIView):
    serializer_class = FileSerializer
    permission_classes = (permissions.IsAuthenticated,)
    parser_classes = [MultiPartParser, ]
    queryset = Track.objects.all()
    lookup_field = 'uid'

    def put(self, request, *args, **kwargs):
        file_obj = request.data

        # Using File storage to save file for future converting
        fs = FileSystemStorage()
        file_name = fs.save(audio_file.name, audio_file)
        audio_file_url = fs.url(file_name)

        # Preparing paths for convertion
        upstream = os.path.dirname(os.path.dirname(os.path.dirname(
            os.path.abspath(__file__))))
        path = os.path.join(upstream, 'media', audio_file.name)
        mp3_filename = '.'.join([audio_file.name.split('.')[0], 'mp3'])
        new_path = os.path.join(
            upstream, 'media', mp3_filename)

        # Converting to mp3 here
        wma_version = AudioSegment.from_file(path, "wav")
        wma_version.export(new_path, format="mp3")
        
        user_id = self.request.user.id
        
        # I was trying to create a Track instance, the mp3 get's saved but it is not being saved using location specified in models.
        track = Track.objects.create(user_id=user_id)
        track.file.name = mp3_filename
        track.save()
        serializer = FileSerializer(track, data={})

        if not serializer.is_valid():
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)

WHen I am trying to use this solution: https://docs.djangoproject.com/en/3.1/topics/files/#using-files-in-models

I am getting error:

{
    "file": [
        "No file was sent."
    ]
}

Any idea what I might be doing wrong? I want to save the converted mp3 file as it was an incoming file in request.FILES['file']

But I am not sure How to prepare it and if I should use the serialiser.

Thank you for any ideas

question from:https://stackoverflow.com/questions/65601769/how-to-save-audio-file-to-django-model-from-the-server-itself-with-rest-api

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...