당신의 물통을 준비
Python 3, FlashData API 키 사용 가능한 크레딧, Amazon S3 버킷 및 저장 자격 증명이 물통에 쓸 수 있습니다. 서버에서 그 자격 증명을 유지하십시오.
# 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:// prefix 또는 디렉토리 경로. 더 보기 저장 설정 S3 호환 대상.
제출 및 다운로드 추적
스크립트를 저장 delivery.py. 오디오 다운로드를 제출 POST /v1/queries, MP3 출력을 선택하고 S3 목적지를 제공합니다.
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))
python3 delivery.py스크립트는 투표하기 전에 ID를 인쇄합니다. 응용 프로그램에서 ID를 저장하므로 재시작 또는 타임아웃은 이미 제출한 링크를 잃지 않습니다.
작업 영수증 읽기
다운로드 제출은 영수증을 반환, 미디어 파일이 아닙니다. 이 기록 된 영수증은 ID 및 링크를 포함하고 진행 상황을 추적하고 정기적인 결과를 읽습니다.
{
"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 자체는 객체를 공개하지 않습니다.
JSON 결과가 24-hour 보유 기간 내에 저장합니다. 미디어 객체는 자신의 버킷의 수명주기 설정에 따라 남아 있습니다. 다운로드 사용은 실제 다운로드된 데이터 볼륨에 근거합니다.