# General Translation Python SDKs: 将翻译存储在本地
URL: https://generaltranslation.com/zh/docs/python/guides/storing-translations.mdx
Docs index: https://generaltranslation.com/llms.txt
Description: 如何在 Python 中从本地文件而非 CDN 加载 General Translation 翻译。

默认情况下，Python SDK 会从 General Translation CDN 加载翻译。或者，你也可以生成翻译文件，将其随应用一同发布，并通过 `load_translations` 回调函数加载。这样可以消除对运行时 CDN 的依赖，但代价是每次更新翻译都需要重新部署。

## 配置本地输出路径 [#configure]

在 `gt.config.json` 中，使用 `[locale]` 占位符，将 `gt` 文件的输出路径设置为项目中的某个路径。

```json title="gt.config.json"
{
  "defaultLocale": "en",
  "locales": ["es", "fr"],
  "files": { "gt": { "output": "translations/[locale].json" } }
}
```

## 生成文件 [#generate]

运行 [CLI](/docs/cli/quickstart) 来翻译内容，并为每个区域设置生成一个文件。

```bash
gt translate
```

## 在初始化时加载翻译 [#load]

向 [`initialize_gt`](/docs/python/reference/functions/initialize-gt) 传入 `load_translations` 回调函数，该函数会读取指定区域设置对应的文件，并返回一个 dict。

```python
import json
from pathlib import Path

def load_translations(locale: str) -> dict[str, str]:
    path = Path("translations") / f"{locale}.json"
    return json.loads(path.read_text()) if path.exists() else {}

initialize_gt(
    app,
    default_locale="en",
    locales=["es", "fr"],
    load_translations=load_translations,
)
```

启用本地加载器后，翻译会从磁盘读取，不会发起 CDN 请求。若要切换回通过 CDN 提供，请移除 `load_translations` 并设置 `project_id` (参见[配置 Python SDK](/docs/python/guides/configuring#delivery)) 。

## Next steps

- /docs/python/guides/configuring
- /docs/python/guides/translating-strings
- /docs/python/guides/detecting-locale
- /docs/python/guides/declaring-variables

## Sitemap

See the full [sitemap](https://generaltranslation.com/sitemap.md) for all pages.
