# Python SDK 快速入门

安装 Python SDK，用几行代码输出搜索结果。包含同步及 asyncio 示例。

规范链接： https://flashdata.dev/zh/docs/guides/flashdata-python
FlashData 核查于 2026-11-22

- [GitHub](https://github.com/flashdatadev/flashdata-python) — 源码与 SDK 参考
- [获取 API Key](https://flashdata.dev/app/api-keys) — 在控制台创建密钥

<a id="application"></a>

## 发起首次 Python 请求

安装 SDK、设置 API Key，然后执行一次搜索。默认响应为 Python 字典。

- [Python SDK 参考](https://github.com/flashdatadev/flashdata-python/blob/v1.3.0/docs/api-reference.md)
- [PyPI](https://pypi.org/project/flashdata/1.3.0/)

<a id="install"></a>

### 安装 SDK

需要 Python 3.10+。在项目目录运行以下命令。若已有虚拟环境，使用该环境的 python -m pip 安装 flashdata==1.3.0 即可。

#### Linux / macOS

##### 安装

```bash
python3 -m venv .venv
.venv/bin/python -m pip install "flashdata==1.3.0"
```


#### Windows PowerShell

##### 安装

```powershell
py -3 -m venv .venv
.\.venv\Scripts\python.exe -m pip install "flashdata==1.3.0"
```


- [安装 Python](https://www.python.org/downloads/)

<a id="key"></a>

### 认证

创建具有 Google 搜索权限的 API Key，或复用已有授权密钥。使用下方隐藏提示在当前终端设置密钥。

若已设置 FLASHDATA_API_KEY，可跳过输入。示例直接读取该变量，不加载 .env 文件。

#### Bash

##### 隐藏密钥输入 · Bash

```bash
# Bash: paste the key into a hidden prompt, not into this command.
read -r -s -p "FlashData API key: " FLASHDATA_API_KEY
printf '\n'
export FLASHDATA_API_KEY
```


#### PowerShell 7

##### 隐藏密钥输入 · PowerShell

```powershell
# PowerShell 7: paste the key into a hidden prompt.
$flashdataSecureKey = Read-Host "FlashData API key" -AsSecureString
$env:FLASHDATA_API_KEY = [System.Net.NetworkCredential]::new("", $flashdataSecureKey).Password
Remove-Variable flashdataSecureKey
```


- [注册](https://flashdata.dev/signup)
- [打开 API Keys](https://flashdata.dev/app/api-keys)
- [打开 Billing](https://flashdata.dev/app/billing)
- [智能体试用配置](https://flashdata.dev/zh/docs/guides/agent-onboarding/reference.md)

<a id="query"></a>

### 执行搜索

将代码保存为 quickstart.py，使用同一虚拟环境运行。程序发起一次 Google 搜索请求，最多获取五条结果，并输出标题、URL 及消耗的 Credits。

#### quickstart.py

```python
import os
from flashdata import FlashData

with FlashData(api_key=os.environ["FLASHDATA_API_KEY"]) as client:
    response = client.google.search("battery recycling research", num=5)
    if response["status"] != "done":
        raise RuntimeError(response)
    for page in response["results"]:
        for hit in page.get("organic", []):
            print(hit["title"], hit["link"])
    print("Credits used:", response["usage"]["credits"])
```

#### Linux / macOS

##### 运行

```bash
.venv/bin/python quickstart.py
```


#### Windows PowerShell

##### 运行

```powershell
.\.venv\Scripts\python.exe quickstart.py
```



<a id="result"></a>

### 检查结果

脚本检查 status 为 done 后正常退出。预期输出来源标题、URL 和 Credits used。organic 列表为空也属于有效响应；结果随查询变化。

| 字段 | 用途 |
| --- | --- |
| results[].organic[] | Google 搜索结果：title、link 和 snippet。其他数据源使用不同的结果字段。 |
| usage.credits | 此请求的成本。这里最多五条结果属于一次搜索请求。 |

#### 输出示例

```text
Battery recycling research https://example.org/recycling
Credits used: 0.02
```


<a id="common-tasks"></a>

## 尝试其他数据源

每个标签页均为完整脚本。将 quickstart.py 替换为其中一个示例，使用第 3 步的命令运行。每次运行提交一个新请求；密钥需要所示的数据源权限。

### Google 新闻

需要 google_news 权限。输出 results[].news[] 中的文章标题及来源链接。

#### quickstart.py

```python
import os
from flashdata import FlashData

with FlashData(api_key=os.environ["FLASHDATA_API_KEY"]) as client:
    response = client.google.news("battery recycling", num=5)
    if response["status"] != "done":
        raise RuntimeError(response)
    for page in response["results"]:
        for article in page.get("news", []):
            print(article.get("title"), article.get("link"))
```


### YouTube 元数据

需要 youtube_metadata 权限。输出视频标题、频道和时长（秒）。将示例 ID 替换为你想查询的视频 ID。

#### quickstart.py

```python
import os
from flashdata import FlashData

with FlashData(api_key=os.environ["FLASHDATA_API_KEY"]) as client:
    response = client.youtube.metadata("dQw4w9WgXcQ", include_formats=False)
    if response["status"] != "done":
        raise RuntimeError(response)
    for video in response["results"]:
        print(video.get("title"), video.get("channel"))
        print("Seconds:", video.get("duration"))
```


### YouTube 转录

需要 youtube_transcript 权限。输出 results[].fullText 中已有的英文自动转录。视频需有对应轨道；此调用不会生成或翻译字幕。

#### quickstart.py

```python
import os
from flashdata import FlashData

with FlashData(api_key=os.environ["FLASHDATA_API_KEY"]) as client:
    response = client.youtube.transcript("dQw4w9WgXcQ", language="en", auto=True)  # or language=["en", "es"] for multiple tracks
    if response["status"] != "done":
        raise RuntimeError(response)
    for track in response["results"]:
        print(track.get("fullText", ""))
```


- [全部数据源方法及参数](https://github.com/flashdatadev/flashdata-python/blob/v1.3.0/docs/sources/index.md)

<a id="features"></a>

## Python SDK 支持的功能

| 用途 | SDK 入口 |
| --- | --- |
| google / youtube | Google 搜索、新闻、图片、购物、视频和地点；YouTube 发现、元数据、字幕、转录及频道数据。 |
| youtube.download | 提交音频或视频交付任务，将文件写入你的云存储。需要 youtube_download 权限及存储配置；请使用下方完整下载示例。 |
| jobs / bulk | 保存接纳的任务 ID，等待完成并读取结果。较大的视频 ID 数据集可使用 bulk，重启后继续已有任务。 |
| account | 定时任务前读取权限、余额、价格、限额和用量。复用环境变量或密钥存储中的授权密钥。 |
| respond_with / accept | 使用 respond_with="markdown" 在 response["content"] 获取 Markdown，或使用 accept="text/plain" 获取字符串。默认返回 JSON 字典。 |

- [完整 Python 下载示例](https://github.com/flashdatadev/flashdata-python/blob/v1.3.0/examples/youtube_download.py)
- [配置下载存储](https://flashdata.dev/zh/docs/guides/youtube-download-guide/reference.md)
- [Python 响应格式](https://github.com/flashdatadev/flashdata-python/blob/v1.3.0/docs/response-formats.md)

<a id="asyncio"></a>

## 使用 asyncio

将 quickstart.py 替换为此版本，使用相同命令运行。AsyncFlashData 提供相同资源，调用时使用 await。此示例仍等待实时搜索响应；mode="async" 则提交服务端后台任务。

在 Jupyter 或已运行事件循环的应用中，使用 await main() 替代 asyncio.run(main())。在该事件循环内复用客户端。

### quickstart.py

```python
import asyncio
import os
from flashdata import AsyncFlashData

async def main():
    async with AsyncFlashData(api_key=os.environ["FLASHDATA_API_KEY"]) as client:
        response = await client.google.search("battery recycling research", num=5)
        if response["status"] != "done":
            raise RuntimeError(response)
        for page in response["results"]:
            for hit in page.get("organic", []):
                print(hit["title"], hit["link"])
        print("Credits used:", response["usage"]["credits"])

asyncio.run(main())
```

- [异步客户端配置](https://github.com/flashdatadev/flashdata-python/blob/v1.3.0/docs/client.md)

<a id="next"></a>

## 下一步

- [账户检查与结果保存](https://flashdata.dev/zh/docs/guides/sdk-operations/reference.md)
- [后台任务与批量查询](https://github.com/flashdatadev/flashdata-python/blob/v1.3.0/docs/jobs.md)
- [批量数据集](https://github.com/flashdatadev/flashdata-python/blob/v1.3.0/docs/bulk.md)
- [SDK 方法参考](https://github.com/flashdatadev/flashdata-python/blob/v1.3.0/docs/api-reference.md)

<a id="errors"></a>

## 步骤失败时

| 问题 | 解决方式 |
| --- | --- |
| ModuleNotFoundError | 安装与运行使用同一解释器：.venv/bin/python -m pip show flashdata（Windows：.\.venv\Scripts\python.exe -m pip show flashdata）。脚本不要命名为 flashdata.py。 |
| KeyError: FLASHDATA_API_KEY / 401 | 在同一终端设置有效 API Key。此示例不会自动加载 .env 文件。请使用 API Key，而非 MCP OAuth 令牌。 |
| 403 | 为此密钥授予示例所需的数据源权限。 |
| 402 | 在 Billing 检查可用 Credits。试用耗尽后，认领连接以使用账户余额。 |
| 429 / APIError | 检查 error.retry_after 并降低请求频率。SDK 每次仅发送一次请求，不会自动重试。 |
| SubmissionUnknownError | 超时提交可能已被接纳。重发前检查 History；若已保存任务 ID，请复用已有任务。 |
| asyncio.run() / running event loop | 在 Notebook 或已有事件循环中使用 await main()；独立脚本使用 asyncio.run(main())。 |

- [请求历史](https://flashdata.dev/app/jobs)
- [账单](https://flashdata.dev/app/billing)
- [Python 错误与恢复](https://github.com/flashdatadev/flashdata-python/blob/v1.3.0/docs/errors.md)
