Chuyển đến nội dung
VI
Lấy khóa API
Duyệt tài liệu

Ví dụ

Tải video về kho lưu trữ của bạn

Đem một MP4 đến cho anh. Amazon S3 xô, sau đó lấy và xác minh các tập tin với Python hay Bash.

Trên trang này

Trước khi bắt đầu

Dùng quyền người sở hữu youtube_download Cho phép và tín dụng sẵn có. Việc tải về không được bao gồm trong truy cập thử nghiệm tạm thời. Bạn cần một cái có sẵn. Amazon S3 xô và video bạn có quyền tải về.

Chọn Python 3.10+ với yêu cầu và boto3, hoặc Bash có cURL, jq, OpenSSL và AWS CLI v2. Vào Windowssử dụng Git Bash cho Bash phiên bản.

Nhận diệnDùng cho
FLASHDATA_API_KEYGửi công việc và lấy lại vị trí và hồ sơ giao hàng.
FLASHDATA_STORAGE_ACCESS_KEY / FLASHDATA_STORAGE_SECRET_KEYAn S3 tải về danh tính đã được gửi tới FlashData vì đã viết thư cho cái xô và tiền tố được chọn.
Hồ sơ hay vai trò AWS cục bộĐọc các vật thể riêng với boto3 hoặc AWS CLI trong bước 4. Nó cần truy cập S3:

1. Chọn đoạn phim và đích

Tạo một thư mục tải về cá nhân bên ngoài kho chứa của bạn. Lưu request.json có và mở một thiết bị cuối trong thư mục đó. Thay thế storage_url với tên xô và khu vực với khu vực AWS; sử dụng một 11- Băng ghi hình ID.

Công thức này cung cấp video với âm thanh như MP4, ở mức 720p, dưới recipes/clip-001/. Hãy giữ kín xô. Sử dụng một tiền tố mới cho việc tải về riêng để một công việc khác không thể ghi đè lên đường dẫn của đối tượng này.

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. Gửi một công việc tải về

Chọn một phiên bản và lưu văn lệnh bên cạnh request.json Trước khi chạy. Văn bản đọc ba biến môi trường ở trên hoặc hỏi chúng tại dấu nhắc ẩn. Các tác nhân nên cung cấp từ cửa hàng bí mật của họ. Đừng để chìa khóa trong request.json.

Một thư mục công việc mới-001 gửi một yêu cầu đặc biệt. Nó lưu yêu cầu mà không cần tải lên thông tin, nhãn thời gian, HTTP phản hồi và công việc ID. Dùng lại thư mục đó để dừng phục tùng; nó không tạo công việc thứ hai.

Cài đặt trong môi trường Python của bạn
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)
Chạy từ download-vido /
python submit.py job-001

Chờ biên soạn

In thành công được gửi: công việc_... và lưu submission.json. Hóa đơn xác nhận rằng công việc được chấp nhận; nhưng chưa hoàn tất việc giao hàng hoặc tính phí cuối cùng.

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

3. Đợi đến lúc giao hàng và giữ lại hồ sơ

Lưu collect.py bên cạnh submit.py, hoặc collect.sh bên cạnh submit.sh. Chạy với cùng một thư mục công việc-001. Nó kiểm tra công việc đã được cứu một lần. Vì đã chờ đợi hay xử lý, chờ đã 10 giây và lại chạy cùng một mệnh lệnh.

Khi hoàn thành, nó tiết kiệm delivery.json. Có chữ ký chuyển hướng ở đây để lấy lại JSON kỷ lục phát hành, không phải MP4; văn lệnh theo nó mà không chuyển tiếp của bạn FlashData Chìa khóa. Được cứu delivery.json bị tái sử dụng mà không có một API yêu cầu.

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)
Kiểm tra công việc đã lưu
python collect.py job-001

Sao? delivery.json chứa

Kết quả bao gồm file_url, file_size trong byte và md5. sử dụng báo cáo công việc hoàn thành. Giữ nguyên kỷ lục. Tập tin URL Tên S3 đối tượng; nó không làm cho một xô riêng tư được đọc trước công chúng.

job-001/delivery.json trường phỏng đoán
{
  "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. Hãy đọc vật dụng cá nhân và xác minh lại

Lưu văn lệnh xác thực bên cạnh các văn lệnh khác. Dùng nhận diện AWS cục bộ của bạn để đọc các đối tượng. Văn bản kiểm tra rằng giao hàng thuộc về kế hoạch S3 xô, tiền tố và tên tập tin phim, sau đó tải về nó media.mp4.part.

Chỉ có một số lượng byte tương ứng và MD5 sản xuất media.mp4 và verified.json. Đang kiểm tra lại một lần nữa một lần nữa đã có media.mp4 Ở địa phương. Bước này đọc của bạn S3 đối tượng; nó không chịu phục tùng người khác FlashData tải xuống.

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)
Kiểm tra giao hàng đã được cứu
python verify.py job-001

Kết quả thành công

Số lượng byte ở trên là hình ảnh. Bây giờ bạn có MP4 trong xô của bạn, một bản sao đã được kiểm tra, và verified.json Buộc tập tin vào tác vụ của nó ID, video ID, khóa đối tượng, checksum và đã báo cáo sử dụng.

Thiết bị cuối
Verified: .../job-001/media.mp4 — 1048576 bytes; MD5 matches.

Tiếp tục lại mà không tải xuống lần thứ hai

Chuyện gì đã xảy raHành động tiếp theo
Gởi hoặc không có việc làm ID đã được lưuGiữ công việc...001 và kiểm tra History sử dụng nhãn thời gian và video của nó. Không xoá thư mục để ép buộc phục tùng khác. Phục hồi lại công việc cũ trước khi quyết định có cần yêu cầu mới hay không.
Đang đợi/ xử lýKhoan. 10 giây, sau đó chạy lại thu thập với công việc001. Nó chỉ đọc công việc hiện tại.
Việc thất bạiKiểm tra job-status.json cho lỗi này. Sửa video hoặc cấu hình lưu trữ trước khi bắt đầu một công việc mới một cách rõ ràng trong một thư mục và tiền tố mới.
401 / 403 / 402 / 429Kiểm tra chìa khóa, cho phép hoặc số dư. Vì 429Đọc Retry-After trong phần đầu lưu và chờ đợi. Tập lệnh không tự động thử lại việc phục tùng.
Lấy kết quả thất bại hoặc nó được ký. URL hết hạnChạy lại thu thập công việc-001 để yêu cầu lại kết quả đã có.
S3 AccessDeniedSửa đổi danh tính địa phương hoặc chính sách xô. FlashData Tải lên truy cập và truy cập đọc địa phương là riêng biệt.
Tập tin bộ phận, đường dẫn sai, đếm byte hoặc MD5Giữ lại bản ghi giao nhận và tệp đã lưu để kiểm tra. Sau khi xử lý nguyên nhân, di chuyển media.mp4.part sang chỗ khác rồi chạy lại verify để đọc mới từ S3. Không chạy lại submit.