본문으로 건너뛰기
KO
API 키 받기
문서 둘러보기

예제

동영상 다운로드

Amazon S3 버킷에 하나의 MP4를 전달하고 Python 또는 Bash 파일을 검색하고 확인할 수 있습니다.

이 페이지의 내용

시작하기 전에

youtube_download 권한 및 사용 가능한 크레딧으로 소유자 액세스. 다운로드는 임시 시약 체험 액세스에 포함되지 않습니다. 기존 Amazon S3 버킷과 비디오를 다운로드 할 수 있습니다.

제품 정보 Python 3.10+ 요청 및 boto3, 또는 Bash 으로 cURL, jq, OpenSSL와 AWS CLI v2..com 으로 Windows에서 Git Bash를 Bash 버전으로 사용하십시오.

주요 특징를 위해
FLASHDATA_API_KEY직무 제출 및 해당 상태 및 배송 기록 검색.
FLASHDATA_STORAGE_ACCESS_KEY / FLASHDATA_STORAGE_SECRET_KEYS3 업로드 정체성은 FlashData로 전송하여 선택한 버킷과 접두사로 작성합니다.
로컬 AWS 프로필 또는 역할boto3 또는 AWS CLI와 함께 개인 객체를 단계 4에 읽으십시오. s3:GetObject 액세스가 필요합니다.

1. 비디오 및 목적지 선택

저장소 밖에서 개인 다운로드 비디오 폴더를 만듭니다. request.json를 저장하고 그 폴더에 터미널을 엽니 다. AWS 지역을 가진 당신의 물통 이름과 지역을 가진 storage_url를 대체하십시오; 11-character 영상 ID를 사용하십시오.

이 요리법은 MP4로 비디오, 최대 720p에서, recipes/clip-001/.의 밑에 물통을 개인 유지. 별도의 다운로드를 위해 신선한 접두사를 사용하므로 다른 작업은 이 객체의 경로를 덮을 수 없습니다.

download-video/request.json
{
  "source": "youtube_download",
  "video_id": "jNQXAC9IVRw",
  "params": {
    "download_type": "audio_video",
    "video_quality": "<=720",
    "output_format": "mp4",
    "storage": {
      "storage_type": "s3",
      "storage_url": "your-media-bucket",
      "region": "us-east-1",
      "object_prefix": "recipes/clip-001"
    }
  }
}

2. 1개의 다운로드 작업 제출

하나의 버전을 선택하고 실행하기 전에 request.json 옆에 스크립트를 저장하십시오. 스크립트는 위의 세 가지 환경 변수를 읽거나 숨겨진 프롬프트에서 요청합니다. 대리인은 그들의 비밀 상점에서 그(것)들을 공급해야 합니다. request.json에서 키를 넣지 마십시오.

새로운 작업-001 폴더는 하나의 동기화 요청을 보냅니다. 그것은 업로드 credentials, 타임스탬프, HTTP 응답 및 작업 ID없이 요청을 저장합니다. 폴더가 제출을 중지하는 재사용; 그것은 두 번째 작업을 만들지 않습니다.

Python 환경에서 설치
python -m pip install requests boto3
download-video/submit.py
# Save as download-video/submit.py.
import getpass
import json
import os
import re
import sys
from datetime import datetime, timezone
from pathlib import Path

import requests

ROOT = Path(__file__).resolve().parent


def read_json(path):
    return json.loads(path.read_text(encoding="utf-8-sig"))


def secret(name):
    value = os.environ.get(name) or getpass.getpass(name + ": ")
    if not value.strip():
        raise ValueError("Missing " + name)
    return value


def main():
    os.umask(0o077)
    folder = sys.argv[1]
    if not re.fullmatch(r"[A-Za-z0-9_-]+", folder):
        raise ValueError("Use a simple output folder name, such as job-001.")
    directory = ROOT / folder
    if directory.exists():
        raise ValueError("Keep this attempt. Run collect.py with the same folder.")
    request = read_json(ROOT / "request.json")
    storage = request["params"]["storage"]
    if (request["source"] != "youtube_download"
            or not re.fullmatch(r"[A-Za-z0-9_-]{11}", request["video_id"])
            or request["params"]["download_type"] != "audio_video"
            or request["params"]["output_format"] != "mp4"
            or storage["storage_type"] != "s3"
            or set(storage) != {"storage_type", "storage_url", "region", "object_prefix"}
            or not re.fullmatch(r"[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]", storage["storage_url"])
            or not re.fullmatch(r"[a-z0-9-]+", storage["region"])
            or not re.fullmatch(r"[A-Za-z0-9_-]+(/[A-Za-z0-9_-]+)*", storage["object_prefix"])):
        raise ValueError("Check the video, MP4 options and Amazon S3 destination.")
    key = secret("FLASHDATA_API_KEY")
    access = secret("FLASHDATA_STORAGE_ACCESS_KEY")
    secret_key = secret("FLASHDATA_STORAGE_SECRET_KEY")
    directory.mkdir(mode=0o700)
    # Save the plan BEFORE sending. Keep upload credentials out of this file.
    (directory / "request.json").write_text(json.dumps(request, indent=2), encoding="utf-8")
    (directory / "submitted-at.txt").write_text(
        datetime.now(timezone.utc).isoformat(), encoding="utf-8")
    storage.update(access_key=access, secret_key=secret_key)
    response = requests.post(
        "https://data.flashdata.dev/v1/queries", json=request,
        headers={"X-API-Key": key, "Accept": "application/json"},
        timeout=(10, 120), allow_redirects=False)
    (directory / "submission.json").write_bytes(response.content)
    (directory / "submission-headers.txt").write_text(
        "\n".join(f"{k}: {v}" for k, v in response.headers.items()), encoding="utf-8")
    (directory / "submission-http.txt").write_text(str(response.status_code))
    if response.status_code not in (200, 201, 202):
        raise ValueError(f"HTTP {response.status_code}. Inspect the saved attempt.")
    receipt = response.json()
    if (receipt.get("source") != "youtube_download"
            or not re.fullmatch(r"[A-Za-z0-9_-]+", receipt.get("id", ""))):
        raise ValueError("Missing job ID. Check History before submitting again.")
    print("Submitted:", receipt["id"], "— keep", directory)


if __name__ == "__main__":
    try:
        main()
    except (IndexError, KeyError, OSError, ValueError, requests.RequestException) as error:
        print("Network request failed. Keep this attempt and inspect its saved files."
              if isinstance(error, requests.RequestException) else str(error), file=sys.stderr)
        sys.exit(1)
다운로드 - 비디오 /에서 실행
python submit.py job-001

예상된 영수증

성공 인쇄 제출: job_... 저장 submission.json. 영수증은 그 일을 받아들였다는 것을 확인합니다; 완료된 납품 또는 마지막 책임은 아닙니다.

job-001/submission.json · 약어
{
  "id": "job_example",
  "source": "youtube_download",
  "status": "pending",
  "usage": {
    "credits": 0
  }
}

3. 배달을 기다리고 그 기록을 저장

을 읽으십시오 collect.py 기타 시설 submit.py, 또는 collect.sh 기타 시설 submit.sh. 같은 작업-001 폴더로 실행합니다. 한 번 저장된 작업을 확인합니다. 보류 또는 처리의 경우 10 초를 기다립니다.

완료되면 delivery.json를 저장합니다. 여기에 서명 된 리디렉션 JSON 납품 기록, MP4가 아닌; 스크립트는 당신의 전달 없이 따릅니다 FlashData 주요. 저장된 delivery.json는 다른 API 요구 없이 재사용됩니다.

download-video/collect.py
# Save as download-video/collect.py, beside submit.py.
import os
import re
import sys
from urllib.parse import urlsplit

import requests
from submit import ROOT, read_json, secret


def main():
    os.umask(0o077)
    folder = sys.argv[1]
    if not re.fullmatch(r"[A-Za-z0-9_-]+", folder):
        raise ValueError("Use the saved output folder name.")
    directory = ROOT / folder
    if (directory / "delivery.json").exists():
        print("Already saved:", directory / "delivery.json")
        return
    receipt = read_json(directory / "submission.json")
    job_id = receipt["id"]
    if receipt["source"] != "youtube_download" or not re.fullmatch(r"[A-Za-z0-9_-]+", job_id):
        raise ValueError("Inspect submission.json before continuing.")
    headers = {"X-API-Key": secret("FLASHDATA_API_KEY"), "Accept": "application/json"}
    url = "https://api.flashdata.dev/v2/jobs/" + job_id

    def get(url, name, headers):
        response = requests.get(url, headers=headers, timeout=(10, 120), allow_redirects=False)
        (directory / name).write_bytes(response.content)
        (directory / (name + ".headers")).write_text(
            "\n".join(f"{k}: {v}" for k, v in response.headers.items()), encoding="utf-8")
        (directory / (name + ".http")).write_text(str(response.status_code))
        return response

    status = get(url, "job-status.json", headers)
    if status.status_code != 200:
        raise ValueError(f"HTTP {status.status_code}. Inspect job-status.json and its headers.")
    job = status.json()["job"]
    if job["id"] != job_id or job["source"] != "youtube_download":
        raise ValueError("The job does not match the saved receipt.")
    if job["status"] in ("pending", "processing"):
        print(job["status"] + ". Wait 10 seconds, then run this command again.")
        return
    if job["status"] != "completed":
        raise ValueError("Job " + job["status"] + ". Inspect job-status.json; do not resubmit.")
    result = get(url + "/results", "delivery.pending.json", headers)
    if result.status_code == 302:
        location = result.headers.get("Location", "")
        parsed = urlsplit(location)
        if parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password:
            raise ValueError("Expected an HTTPS result URL.")
        # This URL retrieves the JSON delivery record, not the video.
        # Never forward the FlashData key to the signed storage URL.
        result = get(location, "delivery.pending.json", {})
    if result.status_code != 200:
        raise ValueError(f"HTTP {result.status_code}. Run collect.py again after resolving it.")
    delivery = result.json()
    if (delivery.get("source") != "youtube_download" or delivery.get("status") != "done"
            or not isinstance(delivery.get("results"), list) or len(delivery["results"]) != 1):
        raise ValueError("Inspect delivery.pending.json before using the result.")
    (directory / "delivery.pending.json").replace(directory / "delivery.json")
    print("Saved:", directory / "delivery.json")
    print("Usage:", delivery.get("usage"))


if __name__ == "__main__":
    try:
        main()
    except (IndexError, KeyError, OSError, ValueError, requests.RequestException) as error:
        print("Network request failed. Keep this attempt and inspect its saved files."
              if isinstance(error, requests.RequestException) else str(error), file=sys.stderr)
        sys.exit(1)
자주 묻는 질문
python collect.py job-001

delivery.json는 무엇을 포함합니다

결과는 바이트와 md5에 file_url, file_size를 포함합니다. 사용법은 완성되는 일을 책임 보고합니다. 전체 기록을 유지하십시오. URL는 S3 개체를 이름 짓습니다; 그것은 개인 물통을 공개적으로 읽기 쉬운 만들지 않습니다.

job-001/delivery.json · 설명 필드
{
  "source": "youtube_download",
  "status": "done",
  "results": [
    {
      "file_url": "https://your-media-bucket.s3.us-east-1.amazonaws.com/recipes/clip-001/jNQXAC9IVRw.mp4",
      "file_size": 1048576,
      "md5": "0123456789abcdef0123456789abcdef"
    }
  ]
}

4. 개인 객체를 읽고 그것을 확인

다른 스크립트 옆에 검증 스크립트를 저장합니다. 구성된 로컬 AWS ID를 사용하여 객체에 대한 액세스를 읽습니다. 스크립트는 S3 버킷, 접두사 및 비디오 파일 이름에 속한 배달이 media.mp4.part에 다운로드한다는 것을 확인합니다.

매칭 바이트 수와 MD5는 media.mp4 및 verified.json를 생산합니다. 다시 실행 검증은 기존 media.mp4를 로컬로 확인합니다. 이 단계는 S3 개체를 읽습니다. 다른 FlashData 다운로드를 제출하지 않습니다.

download-video/verify.py
# Save as download-video/verify.py, beside submit.py.
import hashlib
import json
import os
import re
import sys
from contextlib import closing
from datetime import datetime, timezone
from urllib.parse import urlsplit

import boto3
from submit import ROOT, read_json


def main():
    os.umask(0o077)
    folder = sys.argv[1]
    if not re.fullmatch(r"[A-Za-z0-9_-]+", folder):
        raise ValueError("Use the saved output folder name.")
    directory = ROOT / folder
    request = read_json(directory / "request.json")
    receipt = read_json(directory / "submission.json")
    job = read_json(directory / "job-status.json")["job"]
    delivery = read_json(directory / "delivery.json")
    if (request["source"] != "youtube_download" or receipt["source"] != "youtube_download"
            or job["id"] != receipt["id"] or job["source"] != "youtube_download"
            or job["status"] != "completed" or delivery.get("source") != "youtube_download"
            or delivery.get("status") != "done" or len(delivery["results"]) != 1):
        raise ValueError("Check the saved request, receipt, status and delivery.")
    storage = request["params"]["storage"]
    bucket, region, prefix = (storage[k] for k in ("storage_url", "region", "object_prefix"))
    file = delivery["results"][0]
    parsed = urlsplit(file["file_url"])
    # This recipe uses an ASCII prefix and the MP4 filename generated for the video.
    object_key = prefix + "/" + request["video_id"] + ".mp4"
    if (storage["storage_type"] != "s3" or parsed.scheme != "https"
            or parsed.netloc != bucket + ".s3." + region + ".amazonaws.com"
            or parsed.path != "/" + object_key or parsed.query or parsed.fragment
            or type(file.get("file_size")) is not int or file["file_size"] <= 0
            or not re.fullmatch(r"[A-Fa-f0-9]{32}", file.get("md5", ""))):
        raise ValueError("Delivery URL, byte count or MD5 does not match this recipe's request.")
    local = directory / "media.mp4"
    pending = directory / "media.mp4.part"
    if not local.exists():
        # Boto3 uses your local AWS read identity, not the upload key sent to FlashData.
        with pending.open("xb") as output:
            s3 = boto3.client("s3", region_name=region)
            with closing(s3.get_object(Bucket=bucket, Key=object_key)["Body"]) as stream:
                while chunk := stream.read(1024 * 1024):
                    output.write(chunk)
        local = pending
    size, digest = 0, hashlib.md5(usedforsecurity=False)
    with local.open("rb") as stream:
        while chunk := stream.read(1024 * 1024):
            size += len(chunk)
            digest.update(chunk)
    if size != file["file_size"] or digest.hexdigest() != file["md5"].lower():
        raise ValueError("Size or MD5 mismatch. Keep the local file for inspection.")
    final = directory / "media.mp4"
    if local == pending:
        pending.rename(final)
    record = {
        "job_id": receipt["id"], "video_id": request["video_id"],
        "bucket": bucket, "object_key": object_key, "bytes": size, "md5": digest.hexdigest(),
        "verified_at": datetime.now(timezone.utc).isoformat(), "usage": delivery.get("usage"),
    }
    (directory / "verified.json").write_text(json.dumps(record, indent=2), encoding="utf-8")
    print("Verified:", final, "—", size, "bytes; MD5 matches.")


if __name__ == "__main__":
    try:
        main()
    except Exception as error:
        print(str(error), file=sys.stderr)
        sys.exit(1)
저장된 납품을 검증
python verify.py job-001

성공적인 결과

위의 바이트 수는 환상적입니다. 이제는 버킷에서 MP4를 가지고, 검증 된 로컬 복사 및 verified.json는 작업 ID, 비디오 ID, 객체 키, 체크섬 및보고 된 사용 파일을 tying.

- 연혁
Verified: .../job-001/media.mp4 — 1048576 bytes; MD5 matches.

두 번째 다운로드없이 이력서

어떤 일이 있었는지다음 작업
제출은 아웃 또는 작업 ID가 저장되지 않았습니다작업-001를 유지하고 타임 스탬프 및 비디오를 사용하여 History를 확인하십시오. 다른 제출을 강제로 폴더를 삭제하지 마십시오. 새로운 요청이 필요한지 결정하기 전에 원래 작업을 복구합니다.
Pending / 처리10 초를 대기하고, 작업-001로 다시 실행하십시오. 그것은 단지 기존 일을 읽습니다.
작업 실패오류에 대한 job-status.json를 검사합니다. 새 폴더와 접두사에서 새 작업을 시작하기 전에 비디오 또는 저장 구성을 수정합니다.
401 / 403 / 402 / 429키, 권한 또는 균형 확인. 429의 경우, 저장 된 헤더에 Retry-After를 읽고 기다립니다. 스크립트는 자동으로 재발송되지 않습니다.
결과가 실패하거나 서명한 URL가 만료됨다시 기존 결과를 요청하기 위해 job-001에 대한 Rerun 수집.
S3 AccessDenied로컬 AWS 읽기 정체성 또는 양동이 정책을 수정합니다. FlashData 업로드 액세스 및 로컬 읽기 액세스는 별도입니다.
부분 파일, 잘못된 경로, 바이트 수 또는 MD5검사를 위한 저장된 납품 및 파일을 지키십시오. 신선한 S3를 위해 원인을 해결 한 후 읽으십시오. media.mp4.part를 다음 다시 실행 확인하십시오. 제출하지 마십시오.