# General Translation Python SDKs: 检测请求的区域设置
URL: https://generaltranslation.com/zh/docs/python/guides/detecting-locale.mdx
Docs index: https://generaltranslation.com/llms.txt
Description: 如何在 General Translation for Python 中自动确定每个请求的区域设置，或使用你自己的逻辑来确定。

每次调用 [`t`](/docs/python/reference/functions/t) 都会按当前请求的区域设置进行翻译。[`initialize_gt`](/docs/python/reference/functions/initialize-gt) 会为你注册区域设置检测；你可以使用默认方式，也可以提供自己的回调函数。

## 使用默认检测 [#default]

默认情况下，SDK 会读取 `Accept-Language` 标头，解析其质量值，并从你配置的区域设置中选出最匹配的一项，找不到时则回退到默认区域设置。Flask 会在 `before_request` 钩子中执行此操作；FastAPI 则通过 HTTP 中间件执行。无需额外设置。

你可以在请求处理过程中的任何位置通过 [`get_locale`](/docs/python/reference/functions/get-locale) 读取解析后的区域设置。

```python
from gt_flask import get_locale  # 或：from gt_fastapi import get_locale

get_locale()
```

## 提供自定义检测 [#custom]

如果要遵循显式指定的选择 (例如查询参数、cookie 或路径前缀) ，请向 [`initialize_gt`](/docs/python/reference/functions/initialize-gt) 传入一个 [`get_locale`](/docs/python/reference/functions/get-locale) callback。自定义 callback 会完全取代 `Accept-Language` 检测；提供后将不再调用 `Accept-Language` 检测。

<Tabs items={['Flask', 'FastAPI']}>
  <Tab value="Flask">
    ```python
    def detect_locale(request):
        return request.args.get("lang") or request.cookies.get("locale") or "en"

    initialize_gt(app, default_locale="en", locales=["es", "fr"], get_locale=detect_locale)
    ```
  </Tab>

  <Tab value="FastAPI">
    ```python
    def detect_locale(request):
        return request.query_params.get("lang") or request.cookies.get("locale") or "en"

    initialize_gt(app, default_locale="en", locales=["es", "fr"], get_locale=detect_locale)
    ```
  </Tab>
</Tabs>

你返回的值会按原样存储在该请求中。如果 callback 返回的是假值 (例如 `None`) ，则区域设置会解析为已配置的默认区域设置 (而不是 `Accept-Language`) ，因此如果你希望有不同的行为，请显式返回后备内容。

*注意：与内置的 `Accept-Language` 检测不同，自定义 callback 的返回值不会再根据你配置的 `locales` 进行验证。请返回受支持的区域设置，或自行处理不受支持的值。*

## Next steps

- /docs/python/guides/translating-strings
- /docs/python/guides/configuring
- /docs/python/guides/declaring-variables
- /docs/python/guides/storing-translations

## Sitemap

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