跳转到正文
中文
获取 API 密钥

YouTube 下载 / Python

将 YouTube 音频下载到你的 S3 存储桶

提交音频下载,跟踪后台任务,并获取已交付的 MP3 文件位置。

FlashData · 发布于

交付到对象存储的音频波形

准备存储桶

您需要 Python 3、具有可用积分的 FlashData API 密钥、Amazon S3 存储桶,以及可向该存储桶写入的存储凭据。请将这些凭据保存在服务器上。

bash
# Replace YOUR_API_KEY near the top of the code below.
export YOUTUBE_VIDEO_ID='FUfGcZ092b0'
export MEDIA_BUCKET='your-media-bucket'
export AWS_REGION='us-east-1'
export MEDIA_ACCESS_KEY='your-storage-access-key'
export MEDIA_SECRET_KEY='your-storage-secret-key'

请使用存储桶的实际区域。 MEDIA_BUCKET 是存储桶名称,不包含 s3:// 前缀或目录路径。请参阅 存储设置 ,用于兼容 S3 的目标存储。

提交并跟踪下载

将脚本保存为 delivery.py。它向以下端点提交音频下载: POST /v1/queries,选择 MP3 输出并提供 S3 目标存储。

python
import json
import gzip
import os
import urllib.error
import urllib.request

API_URL = "https://data.flashdata.dev"
API_KEY = "YOUR_API_KEY"


def api_request(path, payload=None, response_headers=None, base_url=API_URL):
    target = path if path.startswith(("https://", "http://")) else base_url + path
    request = urllib.request.Request(
        target,
        data=json.dumps(payload).encode() if payload is not None else None,
        headers={"X-API-Key": API_KEY, "Content-Type": "application/json"},
        method="POST" if payload is not None else "GET",
    )
    with urllib.request.urlopen(request, timeout=60) as response:
        if response_headers is not None:
            response_headers.update(response.headers)
        return json.load(response)


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, request, file_pointer, code, message, headers, new_url):
        return None


def result_request(url):
    request = urllib.request.Request(url, headers={"X-API-Key": API_KEY}, method="GET")
    try:
        with urllib.request.build_opener(NoRedirect).open(request, timeout=60):
            raise RuntimeError("Results endpoint did not redirect to storage")
    except urllib.error.HTTPError as response:
        if response.code != 302 or not response.headers.get("Location"):
            raise
        storage_url = response.headers["Location"]
        response.close()
    storage_request = urllib.request.Request(storage_url, headers={"Accept-Encoding": "gzip"})
    with urllib.request.urlopen(storage_request, timeout=60) as response:
        body = response.read()
        if response.headers.get("Content-Encoding") == "gzip":
            body = gzip.decompress(body)
        return json.loads(body)["results"]

import random
import time


def wait_for_job(submission, timeout_seconds=300):
    job_id = submission["id"]
    status_url = next(link["href"] for link in submission["links"] if link["rel"] == "self")
    deadline = time.monotonic() + timeout_seconds
    delay = 1.0
    while time.monotonic() < deadline:
        headers = {}
        payload = api_request(status_url, response_headers=headers)
        job = payload.get("job", payload)
        if job["status"] == "completed":
            results_url = next(link["href"] for link in job["links"] if link["rel"] == "results")
            return result_request(results_url)
        if job["status"] == "failed":
            raise RuntimeError(f"{job_id}: {job.get('error') or 'Job failed'}")
        hint = headers.get("Retry-After", headers.get("retry-after", "1"))
        delay = max(min(5.0, delay * 1.5), float(hint))
        time.sleep(min(delay * random.uniform(1.0, 1.2), max(0, deadline - time.monotonic())))
    raise TimeoutError(f"Keep this job ID and check again later: {job_id}")

storage = {
    "storage_type": "s3",
    "storage_url": os.environ["MEDIA_BUCKET"],
    "object_prefix": "YYYYMMDD",
    "region": os.environ["AWS_REGION"],
    "access_key": os.environ["MEDIA_ACCESS_KEY"],
    "secret_key": os.environ["MEDIA_SECRET_KEY"],
}

job = api_request("/v1/queries", {
    "source": "youtube_download",
    "video_id": os.environ["YOUTUBE_VIDEO_ID"],
    "params": {
        "download_type": "audio",
        "output_format": "mp3",
        "storage": storage,
    },
})
print("Save this job ID before polling:", job["id"], flush=True)
files = wait_for_job(job)
print(json.dumps(files, indent=2))
bash
python3 delivery.py

脚本会在轮询前输出任务 ID。请在应用中保存该 ID,避免重启或超时后丢失与已提交任务的关联。

读取任务回执

提交下载会返回回执,而不是媒体文件。这份已记录的回执包含任务 ID,以及用于跟踪进度和读取最终结果的链接。

json
{
  "id": "job_d265c693-950e-40bf-a13e-a432044d99ba",
  "source": "youtube_download",
  "status": "pending",
  "usage": {
    "credits": 0
  },
  "created_at": "2026-09-16T07:51:13.139Z",
  "links": [
    {
      "rel": "self",
      "href": "https://api.flashdata.dev/v2/jobs/job_d265c693-950e-40bf-a13e-a432044d99ba",
      "method": "GET"
    },
    {
      "rel": "results",
      "href": "https://api.flashdata.dev/v2/jobs/job_d265c693-950e-40bf-a13e-a432044d99ba/results",
      "method": "GET"
    }
  ]
}

使用同一 API 密钥读取状态链接。如果轮询超时,请保留 ID,稍后再检查。不要自动创建替代任务。

使用已交付的文件

文件上传后,任务状态变为 completed。结果端点会重定向到存储中的 JSON;脚本会跟随该重定向,但不会将你的 API 密钥转发给存储服务。

阅读 file_url, file_size 和结果中的输出格式字段。对于私有存储桶,使用你的存储凭证读取文件,或为最终用户创建签名链接。文件 URL 本身不会让对象变为公开可访问。

请在 24 小时的保留期限内保存任务的 JSON 结果。媒体对象仍受您自己的存储桶生命周期设置约束。下载用量按实际下载的数据量计算。