【问题标题】:django read mp3 file and send it as responsedjango 读取 mp3 文件并将其作为响应发送
【发布时间】:2021-07-25 12:28:01
【问题描述】:

views.py

from . import models, serializers
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.views import APIView

class getSongData(APIView):
    serializer_class=serializers.SongSerializer

    def get(self, request, id, format=None):
        serializer = serializers.SongSerializer(models.Song.objects.get(id=id))
        file_loc = serializer.data['audio_file'] # go below to see the data

        # read the mp3 file

        return Response(file_data)

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('songs/audio/<int:id>', views.getSongData.as_view(), name='audio')
]

serializers.py

from rest_framework import serializers
from . import models

class SongSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Song
        fields = '__all__'

models.py

from django.db import models
from datetime import datetime

class Song(models.Model):
    title = models.CharField(max_length=64)
    audio_file = models.FileField()
    genre = models.CharField(max_length=64)
    created_at = models.DateTimeField(default=datetime.utcnow)

数据

[
    {
        "id": 1,
        "title": "Kubbi | Cascade",
        "audio_file": "/media/Kubbi__Cascade.mp3",
        "genre": "Instrumental",
        "created_at": "2021-07-24T10:21:48Z"
    }
]

当用户点击一首歌曲时(假设歌曲的 id=1),一个请求被发送到 'http://localhost:8000/api/songs/audio/1' 然后在 views.py 我提取歌曲的位置通过 serializer.data['audio_file'] = "/media/Kubbi__Cascade.mp3",我想要做的就是读取这个音频文件并将数据作为响应发送回前端,我尝试了很多解决方案但他们正在抛出错误......

【问题讨论】:

  • 您的意思是将可播放的音频作为文件返回吗?
  • 可以,方便用户播放/下载

标签: python django django-rest-framework


【解决方案1】:

如果你想使用纯 django 来做这件事

from django.http import FileResponse


class getSongData(APIView):
    serializer_class=serializers.SongSerializer

    def get(self, request, id, *args, **kwargs):
        song = models.Song.objects.get(id=id)        
        return FileResponse(song.audio_file.open())

但最好通过反向代理提供文件以获得更好的性能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-06
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多