# Realtime và mộtsync

Hãy thu thập kết quả, hoặc nộp một công việc và lấy sau. Chọn cách ứng dụng hay tác nhân của bạn chờ làm việc.

Tài liệu tham khảo chính điển: https://flashdata.dev/vi/docs/reference/realtime-and-async
Xem lại: 2026-11-04 by FlashData

<a id="choose"></a>

## Chọn chế độ yêu cầu

Google Search và YouTube Data hỗ trợ cả hai chế độ. YouTube Download yêu cầu một định kỳ, Batch hay Bulk; nó không hỗ trợ thời gian thực. Các thông số về nguồn vẫn như cũ khi chuyển từ thời gian thực sang một định kỳ.

| Phương thức | Dùng khi | Những gì bạn nhận được |
| --- | --- | --- |
| Realtime | Kết quả tìm kiếm là cần thiết trong sự tương tác hiện tại. | Cơ thể kết quả cũng như vậy. HTTP Trả lời đi. |
| Async | Công việc nên tiếp tục sau khi tiến trình của bạn bị ngắt kết nối, hoặc bạn đang tải về các phương tiện truyền thông. | Một công việc ID ngay lập tức; lấy trạng thái và kết quả riêng lẻ. |

### Yêu cầu xe đạp cứu sinh

```text
Realtime  POST data.flashdata.dev/v1/queries/realtime Kết quả _BAR_
Async     POST data.flashdata.dev/v1/queries          Công việc teppi82 ID
          GET  api.flashdata.dev/v2/jobs/{id}         Trạng thái cấu hình
          GET  api.flashdata.dev/v2/jobs/{id}/results Kết quả _BAR_
```

- [Phục vụ nhiều thư viện?](https://flashdata.dev/vi/docs/reference/batch-and-bulk/reference.md)

<a id="submit"></a>

## Gửi một yêu cầu

Đặt FLASHDATA_API_KEY thành một phím cho phép google_search. Chọn thời gian thực hoặc một định kỳ; mỗi bộ trình bày chạy một bộ lọc tìm kiếm có thể tính. Giữ văn lệnh, biên nhận và kết quả trong cùng một thư mục làm việc mới.

Python ví dụ dùng Python 3.10+ và yêu cầu. Mỗi tập lệnh chạy độc lập và đọc tập tin đã lưu từ những bước trước đó. Hạt cURL Nhu cầu thay thế Bash, cURL 7.76+ và jq.

### Python_· cài đặt một lần

```bash
python3 -m pip install requests
```

- [API Name](https://flashdata.dev/vi/docs/guides/headers-and-authentication/reference.md)
- [Google Search Tham số](https://flashdata.dev/vi/docs/sources/google_search/reference.md)

<a id="realtime"></a>

### Realtime: nhận được kết quả ngay bây giờ

POST /v1/queries/realtime trở lại status: done Và một danh sách kết quả. Đọc result.json; không cần phải bỏ phiếu.

#### Python

Lưu dạng realtime.py chạy python3 realtime.py.

##### realtime.py

```python
import json
import os
from pathlib import Path

import requests

response = requests.post(
    "https://data.flashdata.dev/v1/queries/realtime",
    headers={"X-API-Key": os.environ["FLASHDATA_API_KEY"]},
    json={"source": "google_search", "query": "battery recycling research", "params": {"num": 5}},
    timeout=120, allow_redirects=False,
)
response.raise_for_status()
result = response.json()
Path("result.json").write_text(json.dumps(result, indent=2), encoding="utf-8")
print(json.dumps(result, indent=2))
```


#### cURL / Bash

##### Lấy kết quả rồi. cURL / Bash

```bash
curl --fail-with-body --silent --show-error \
  'https://data.flashdata.dev/v1/queries/realtime' \
  --header "X-API-Key: ${FLASHDATA_API_KEY:?Set FLASHDATA_API_KEY}" \
  --header 'Content-Type: application/json' \
  --data '{"source":"google_search","query":"battery recycling research","params":{"num":5}}' \
  --output result.json &&
jq '{source, status, results, usage}' result.json
```



<a id="async"></a>

### Async: lưu biên nhận việc làm

POST /v1/queries gửi hóa đơn công việc đang chờ, không phải kết quả tìm kiếm. Lưu submission.json và tiếp tục với trạng thái và kết quả yêu cầu bên dưới.

#### Python

Lưu dạng submit_async.py chạy python3 submit_async.py.

##### submit_async.py

```python
import json
import os
from pathlib import Path

import requests

response = requests.post(
    "https://data.flashdata.dev/v1/queries",
    headers={"X-API-Key": os.environ["FLASHDATA_API_KEY"]},
    json={"source": "google_search", "query": "battery recycling research", "params": {"num": 5}},
    timeout=30, allow_redirects=False,
)
response.raise_for_status()
result = response.json()
Path("submission.json").write_text(json.dumps(result, indent=2), encoding="utf-8")
print(json.dumps(result, indent=2))
```

##### Name

```json
{
  "id": "job_EXAMPLE",
  "source": "google_search",
  "status": "pending"
}
```


#### cURL / Bash

##### Gửi và lưu công việc ID · cURL / Bash

```bash
curl --fail-with-body --silent --show-error \
  'https://data.flashdata.dev/v1/queries' \
  --header "X-API-Key: ${FLASHDATA_API_KEY:?Set FLASHDATA_API_KEY}" \
  --header 'Content-Type: application/json' \
  --data '{"source":"google_search","query":"battery recycling research","params":{"num":5}}' \
  --output submission.json &&
jq '{id, source, status, links}' submission.json
```

##### Name

```json
{
  "id": "job_EXAMPLE",
  "source": "google_search",
  "status": "pending"
}
```



<a id="status"></a>

## Kiểm tra một công việc đặc biệt

Đọc job.status sử dụng ID in submission.json. Chờ đợi hoặc xử lý, chờ đợi cho Retry-After hoãn lại trước khi kiểm tra lại; Python In ra và cURL tiết kiệm nó trong status-headers.txt. Dùng ngược lại nếu không có gợi ý trả lại. Một yêu cầu trạng thái thành công không có nghĩa là công việc đã hoàn tất.

| job.status | Hành động tiếp theo |
| --- | --- |
| pending / processing | Đợi đã, rồi kiểm tra lại công việc cũ. ID Một lần nữa. |
| completed | Lấy lại kết quả đã được lưu. |
| failed | Đọc job.error. Sửa chữa nguyên nhân trước khi gửi công việc mới. |

### Python

Lưu dạng job_status.py chạy python3 job_status.py.

#### job_status.py

```python
import json
import os
from pathlib import Path

import requests

job_id = json.loads(Path("submission.json").read_text(encoding="utf-8"))["id"]
response = requests.get(
    f"https://api.flashdata.dev/v2/jobs/{job_id}",
    headers={"X-API-Key": os.environ["FLASHDATA_API_KEY"]},
    timeout=30, allow_redirects=False,
)
response.raise_for_status()
Path("job.json").write_text(json.dumps(response.json(), indent=2), encoding="utf-8")
print(json.dumps(response.json()["job"], indent=2))
print("Retry-After:", response.headers.get("Retry-After", "not provided"))
```


### cURL / Bash

#### Đọc trạng thái · cURL / Bash

```bash
JOB_ID=$(jq -er '.id' submission.json)
curl --fail-with-body --silent --show-error \
  "https://api.flashdata.dev/v2/jobs/$JOB_ID" \
  --header "X-API-Key: ${FLASHDATA_API_KEY:?Set FLASHDATA_API_KEY}" \
  --dump-header status-headers.txt --output job.json &&
jq '.job | {id, source, status, error}' job.json
```



<a id="results"></a>

## Lấy kết quả hoàn tất

Chạy cái này sau job.status hoàn tất. Đáp ứng kết quả mặc định là 302: Địa điểm chỉ tới kho đã ký URL. Hai yêu cầu bên dưới giữ lại của bạn API phím trên FlashData và lưu bản gốc JSON phải result.json. Vì YouTube DownloadCái này JSON Mô tả phương tiện truyền thông được chuyển đến kho của bạn; nó không phải là video hay tập tin âm thanh.

### Python

Lưu dạng job_result.py chạy python3 job_result.py.

#### job_result.py

```python
import json
import os
from pathlib import Path

import requests

receipt = json.loads(Path("submission.json").read_text(encoding="utf-8"))
job_id = receipt["id"]
response = requests.get(
    f"https://api.flashdata.dev/v2/jobs/{job_id}/results",
    headers={"X-API-Key": os.environ["FLASHDATA_API_KEY"]},
    timeout=30, allow_redirects=False,
)
response.raise_for_status()
if response.status_code != 302:
    raise RuntimeError(f"Expected a result redirect, got {response.status_code}")
url = response.headers["Location"]
if not url.startswith("https://"):
    raise ValueError("Expected an HTTPS storage URL")

# A separate request: no FlashData key is sent to storage.
result = requests.get(url, timeout=120)
result.raise_for_status()
data = result.json()  # Requests automatically decodes Content-Encoding: gzip.
Path("result.json").write_text(json.dumps(data, indent=2), encoding="utf-8")
print(json.dumps(data, indent=2))
```


### cURL / Bash

#### Lấy bản gốc JSON · cURL / Bash

```bash
JOB_ID=$(jq -er '.id' submission.json)
RESULT_URL=$(curl --fail-with-body --silent --show-error \
  "https://api.flashdata.dev/v2/jobs/$JOB_ID/results" \
  --header "X-API-Key: ${FLASHDATA_API_KEY:?Set FLASHDATA_API_KEY}" \
  --output /dev/null --write-out '%{redirect_url}') &&
curl --fail-with-body --silent --show-error --compressed --proto '=https' \
  "${RESULT_URL:?Expected a signed result URL}" --output result.json &&
jq '{source, status, results, usage}' result.json
```


- [JSON, văn bản và Markdown Định dạng](https://flashdata.dev/vi/docs/guides/response-formats/reference.md#completed-results)
- [Thiết lập kho lưu](https://flashdata.dev/vi/docs/guides/youtube-download-guide/reference.md)

<a id="recovery"></a>

## Xử lý sự chậm trễ và thất bại

| Tình trạng | Cách xử lý |
| --- | --- |
| Đã quá giờ | A POST Có lẽ đã được chấp nhận rồi. Kiểm tra biên lai đã lưu và lịch sử tài khoản trước khi phục hồi; các PSTs lặp đi lặp lại có thể tạo công việc thanh toán mới. |
| 409 · result_not_ready | Tiếp tục thăm dò tình hình. Đừng tạo ra một công việc khác. |
| 422 · result_not_ready | Công việc thất bại. Đọc job.error trước khi thử lại. |
| 429 | Danh dự Retry-After hay retry_after; giảm mức độ phục tùng khi năng lượng chờ đợi là đầy đủ. |
| 410 · result_expired | Kết quả đã được lưu 24 hàng giờ sau khi hoàn thành. Dùng bản sao lưu của anh đi. |

- [Lỗi và mã trạng thái](https://flashdata.dev/vi/docs/errors/reference.md)
- [CLI, phiếu và webok đi qua](https://flashdata.dev/vi/docs/guides/async-batch/reference.md)
