本地化
运行示例前,将 <APPBASE_ENDPOINT_WITH_V1> 替换为目标环境的 API 地址,并核对项目及凭据属于同一环境。
这是什么 / 何时用
Locale 服务提供两类能力:当前请求方的地理与语言环境识别(基于客户端 IP 与 X-Appwrite-Locale 请求头返回国家代码、大洲、欧盟成员状态与默认货币),以及平台内置的标准化国际化静态字典清单(国家与地区、欧盟成员国、国际电话区号、大洲、ISO 4217 货币、ISO 639-1 语言及 ISO 3166-1 三位字母代码)。
在跨国或多语种企业智能应用(如演示项目 enterprise-ai-hub-210)中,前端与服务端可通过 Locale 服务统一渲染国家/电话区号下拉框、货币符号格式化、多语言切换器,并在智能体会话初始化前注入用户所在的区域与语言偏好,避免在多端重复维护静态字典。
前置
客户端初始化与认证:
Server SDK(Node.js / Java / Python / Go):通过
setEndpoint('https://appbuild-sit.oceanbase.com/v1')、setProject('enterprise-ai-hub-210')、setKey('<APPBASE_API_KEY>')初始化,API Key 需具备locale.readscope。Client / Web SDK:通过
setEndpoint、setProject初始化并装载用户 Session(或匿名会话),无需 API Key。Console SDK:支持管理面 Session 或短期 JWT 调用。
显示语言覆盖:调用
client.setLocale('zh-CN')(或en-US、ja-JP)可在请求中携带X-Appwrite-Locale头,使返回的国家名称、大洲名称按指定语言本地化。
使用骨架
初始化
Client与Locale服务:装载项目 ID 与鉴权凭据,按需调用setLocale('zh-CN')指定返回字典的显示语种。获取当前调用方 Locale(
locale.get()):读取调用方 IP 解析出的ip、countryCode、country、continentCode、continent、eu与currency。拉取静态字典清单:按业务表单需求调用
listCountries()、listCountriesEU()、listCountriesPhones()、listContinents()、listCurrencies()、listLanguages()或listCodes(),并在服务端进程内或前端本地存储按版本做 TTL 缓存。
关键参数与返回
方法全集与对应 REST 端点
| SDK 方法(Node / Web / Java) | Python 方法 | Go 方法 | REST 端点 | 返回模型 | 说明 |
|---|---|---|---|---|---|
get() | get() | Get() | GET /v1/locale | Locale | 根据请求来源 IP 与 X-Appwrite-Locale 返回当前用户地理与货币信息。 |
listCodes() | list_codes() | ListCodes() | GET /v1/locale/codes | LocaleCodeList | 获取 ISO 639-1 语言代码清单(total + localeCodes[])。 |
listContinents() | list_continents() | ListContinents() | GET /v1/locale/continents | ContinentList | 获取全球七大洲名称与双字母代码清单(total + continents[])。 |
listCountries() | list_countries() | ListCountries() | GET /v1/locale/countries | CountryList | 获取全球国家/地区名称与 ISO 3166-1 Alpha-2 代码清单(total + countries[])。 |
listCountriesEU() | list_countries_eu() | ListCountriesEU() | GET /v1/locale/countries/eu | CountryList | 获取欧盟(EU)成员国列表(total + countries[])。 |
listCountriesPhones() | list_countries_phones() | ListCountriesPhones() | GET /v1/locale/countries/phones | PhoneList | 获取各国国际电话拨号前缀清单(total + phones[])。 |
listCurrencies() | list_currencies() | ListCurrencies() | GET /v1/locale/currencies | CurrencyList | 获取 ISO 4217 货币符号、名称、小数精度与代码清单(total + currencies[])。 |
listLanguages() | list_languages() | ListLanguages() | GET /v1/locale/languages | LanguageList | 获取语言代码、英文名与本地母语名称(nativeName)清单(total + languages[])。 |
核心返回字段说明
| 模型 | 字段 | 类型 | 说明 |
|---|---|---|---|
Locale | ip | string | 请求客户端 IP 地址(若经过反向代理,取受信任的转发头)。 |
Locale | countryCode | string | ISO 3166-1 两位国家代码(如 CN、US;内网 IP 解析不到时为 --)。 |
Locale | country | string | 本地化后的国家名称(如 中国)。 |
Locale | continentCode | string | 两位大洲代码(如 AS、EU、NA)。 |
Locale | continent | string | 本地化后的大洲名称(如 亚洲)。 |
Locale | eu | boolean | 该国家是否属于欧盟成员国。 |
Locale | currency | string | ISO 4217 三位货币代码(如 CNY、USD、EUR)。 |
Country / Continent | name / code | string | 本地化名称与两位标准代码。 |
Phone | code / countryCode / countryName | string | 电话区号(如 +86)、国家代码(CN)与国家名称。 |
Currency | symbol / name / symbolNative / decimalDigits / rounding / code / namePlural | string / number | 货币展示符号(¥)、名称、小数位数(如 2)与三位代码(CNY)。 |
Language | name / code / nativeName | string | 语言名称、ISO 639-1 代码(如 zh)与母语自称(中文)。 |
错误与边界
内网或代理环境下的
locale.get()回退值:在本地容器、私网环境或未透传真实客户端 IP 的反向代理后调用locale.get(),GeoIP 库无法命中公网网段,countryCode、continentCode等字段会返回未知标识--(HTTP 状态码仍为200),业务代码须将其视为未识别区域并回退到项目默认地区。权限与 Scope 缺失(
401 general_unauthorized_scope):使用项目 API Key 调用但未勾选locale.readscope 时返回401;使用 Web SDK 时若未配置合法项目 ID 则返回404 project_not_found。静态字典缓存策略:
listCountries、listCurrencies等接口无分页参数,单次返回全量静态集合(通常数千字节)。生产环境应在应用启动或前端 Store 初始化时拉取一次并缓存(建议 TTL 24 小时),避免在每次高频请求中重复拉取触发429限流。
SDK 类别差异
| SDK 类别 | 支持范围 | 鉴权方式 | 典型场景 |
|---|---|---|---|
| Server SDK(Node.js / Java / Python / Go) | 全量 8 个方法 | 项目 API Key(locale.read) | 服务端多语种字典预热、账单货币精度校验、手机区号归属校验 |
| Client / Web SDK(Web) | 全量 8 个方法 | 用户 Session(或公开访问) | 注册页国际区号选择、前端语言切换器、客户端区域自动识别 |
| Console SDK(Node.js / Java / Python / Go) | 全量 8 个方法 | 管理面 Session / 短期 JWT | 控制台表单与区域选择组件 |
各语言调用示例
客户端与服务端均可用;Web 页签走用户 Session,受数据面权限约束。
- Node.js(Server)
- Web(用户 Session)
- Java
- Python
- Go
- REST(curl)
import { Client, Locale, AgentbaseException } from 'agentbase-node-sdk';
const client = new Client()
.setEndpoint(process.env.APPBASE_ENDPOINT ?? '<APPBASE_ENDPOINT_WITH_V1>')
.setProject(process.env.APPBASE_PROJECT_ID ?? '<APPBASE_PROJECT_ID>')
.setKey(process.env.APPBASE_API_KEY!)
.setLocale('zh-CN'); // 指定返回的国家与大洲名称使用简体中文
{
const prepareRequest = client.prepareRequest.bind(client);
client.prepareRequest = (...args) => {
const request = prepareRequest(...args);
request.options.redirect = 'error';
return request;
};
}
const locale = new Locale(client);
try {
// 1. 获取当前请求方的区域与货币信息
const current = await locale.get();
console.log(`当前区域: ${current.country} (${current.countryCode}), 货币: ${current.currency}`);
// 2. 获取国家列表、国际电话区号与货币字典
const countries = await locale.listCountries();
const phones = await locale.listCountriesPhones();
const currencies = await locale.listCurrencies();
const languages = await locale.listLanguages();
console.log(`国家数: ${countries.total}, 区号数: ${phones.total}, 货币数: ${currencies.total}, 语言数: ${languages.total}`);
} catch (err) {
if (err instanceof AgentbaseException) {
console.error(`Locale 调用失败 [${err.code} ${err.type}]: ${err.message}`);
}
throw err;
}import { Client, Locale } from 'agentbase-web-sdk';
const client = new Client()
.setEndpoint('<APPBASE_ENDPOINT_WITH_V1>')
.setProject('<APPBASE_PROJECT_ID>')
.setLocale('zh-CN');
const locale = new Locale(client);
const userLocale = await locale.get();
const countries = await locale.listCountries();
const phones = await locale.listCountriesPhones();
console.log('识别用户国家:', userLocale.countryCode, '可选区号数:', phones.total);import io.agentbase.Client;
import io.agentbase.services.Locale;
import io.agentbase.exceptions.AppBaseException;
Client client = new Client()
.setEndpoint("<APPBASE_ENDPOINT_WITH_V1>")
.setProject("<APPBASE_PROJECT_ID>")
.setKey(System.getenv("APPBASE_API_KEY"))
.setLocale("zh-CN");
client.setHttpClient(new okhttp3.OkHttpClient.Builder()
.followRedirects(false).followSslRedirects(false).build());
Locale locale = new Locale(client);
try {
var current = locale.get(); // 当前用户 Locale
var countries = locale.listCountries(); // 静态清单:listContinents / listCountriesEU / listCountriesPhones / listCurrencies / listLanguages / listCodes
var currencies = locale.listCurrencies();
System.out.println("Country=" + current.getCountry() + ", totalCountries=" + countries.getTotal() + ", totalCurrencies=" + currencies.getTotal());
} catch (AppBaseException e) {
System.err.println("HTTP " + e.getCode() + " type=" + e.getType() + ": " + e.getMessage());
}Python Server SDK 2.12.0 的默认请求可能在跳转时转发项目 API Key,暂不提供本段的 SDK 调用代码。使用本节的 REST 页签。
package main
import (
"errors"
"net/http"
"fmt"
"os"
"agentbase-go-sdk/agentbase"
)
func main() {
cl := agentbase.NewClient(
agentbase.WithEndpoint("<APPBASE_ENDPOINT_WITH_V1>"),
agentbase.WithProject("<APPBASE_PROJECT_ID>"),
agentbase.WithKey(os.Getenv("APPBASE_API_KEY")),
agentbase.WithLocale("zh-CN"),
)
cl.Client.CheckRedirect = func(_ *http.Request, _ []*http.Request) error {
return errors.New("refuse redirects")
}
locale := agentbase.NewLocale(cl)
loc, err := locale.Get()
if err == nil {
fmt.Println("当前国家:", loc.Country, loc.Currency)
}
countries, _ := locale.ListCountries() // 另有 ListContinents / ListCountriesEU / ListCountriesPhones / ListCurrencies / ListLanguages / ListCodes
fmt.Println("国家总数:", countries.Total)
}(
set +x
set -e -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
# 1. 获取当前请求者 Locale(带 X-Appwrite-Locale: zh-CN 返回中文国家与大洲名)
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --header @- -fsS "$APPBASE_ENDPOINT/locale" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Locale: zh-CN"
# 2. 获取国家、国际电话区号、货币与语言静态清单
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --header @- -fsS "$APPBASE_ENDPOINT/locale/countries" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Locale: zh-CN"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --header @- -fsS "$APPBASE_ENDPOINT/locale/countries/phones" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --header @- -fsS "$APPBASE_ENDPOINT/locale/currencies" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID"
)示例指引
JavaScript / TypeScript 全量示例:../examples/javascript.md
Python 全量示例:../examples/python.md
Java 全量示例:../examples/java.md
Go 全量示例:../examples/go.md