django 如何下载音频MP3文件并保存?

k5hmc34c  于 2022-11-18  发布在  Go
关注(0)|答案(1)|浏览(196)

我的检视:

class UserSearchView(APIView):

    def get(self, request, link):
        url = config('BASE_URL')
        querystring = {"track_url": f'{link}'}
        headers = {
            "X-RapidAPI-Key": config('API_KEY'),
            "X-RapidAPI-Host": config('API_HOST')
        }

        response = requests.request("GET", url, headers=headers, params=querystring)

        data = response.json()

        return JsonResponse(data)

我的回应:

{
    "url": "https://result.s3.amazonaws.com/2022-11-13/61566981.mp3"
}

不知道该如何进行,有人能帮忙吗?----------------------

uujelgoq

uujelgoq1#

你走到这一步,很好。

response = requests.request("GET", url, headers=headers, params=querystring)

现在,只要保存MP3。

with open("music.mp3", "wb") as fout:
            fout.write(response.content)

编辑
这是一个演示。

#! /usr/bin/env python3
from pathlib import Path

import requests

def download(url, out_file="audio.mp3"):
    out_file = Path(f"~/Desktop/{out_file}").expanduser()
    resp = requests.get(url)
    resp.raise_for_status()
    with open(out_file, "wb") as fout:
        fout.write(resp.content)

if __name__ == "__main__":
    npr = "https://play.podtrac.com/npr-500005/edge1.pod.npr.org/anon.npr-mp3/npr"
    download(f"{npr}/newscasts/2022/11/13/20221113_newscasts_long_140735.mp3")

相关问题