Internationalization
Internationalization
Core features
The SDK provides a complete internationalization solution. It reads multilingual configuration from .ini files and uses the request lang parameter to translate response messages and validation errors automatically, so your app can be deployed globally.
Overview
- Flexible configuration:
.inilanguage files, loaded dynamically - Automatic translation: the framework resolves the language for you
- Parameterized messages: placeholder substitution for dynamic content
- Form validation integration: consistent error messages with the form system
- Fast: built-in caching keeps translation cheap
Quick Start
Directory Layout
The project root must contain an i18n/ directory with the language files:
project/
├── main.py
├── i18n/
│ ├── zh-CN.ini # Simplified Chinese
│ ├── en.ini # English
│ ├── zh-TW.ini # Traditional Chinese (optional)
│ └── ja.ini # Japanese (optional)
└── requirements.txtInitialization
# main.py - basic middleware example
import asyncio
from simplejrpc.app import ServerApplication
from simplejrpc.response import jsonify
from simplejrpc import RPCMiddleware
# Create the app instance
app = ServerApplication(socket_path="app.socket", i18n_dir="./i18n")
@app.route(name="hello")
async def hello(name: str = "World"):
"""Simple greeting endpoint"""
return jsonify(
data=f"Hello, {name}!",
msg="请求处理成功"
)
if __name__ == "__main__":
asyncio.run(app.run())Important
Pass the i18n directory when the service is initialized and make sure the path exists.
Every request must include the lang parameter; the framework uses it to set the current language. If lang is missing, the default language from initialization is used.
The framework defaults to en.
Language Files
Basic Translations
Create language files with translation key/value pairs:
zh-CN.ini
# Basic status messages
STATUS_OK = 操作成功
STATUS_FAILED = 操作失败
STATUS_UNAUTHORIZED = 未授权访问
# Business related
USER_NOT_FOUND = 用户不存在
INVALID_PASSWORD = 密码错误
TEST_I18N = 测试en.ini
# Basic status messages
STATUS_OK = Operation successful
STATUS_FAILED = Operation failed
STATUS_UNAUTHORIZED = Unauthorized access
# Business related
USER_NOT_FOUND = User not found
INVALID_PASSWORD = Invalid password
TEST_I18N = TestUsing Basic Translations
from simplejrpc.i18n import T as i18n
# Basic translation, used inside business logic
print(i18n.translate("TEST_I18N")) # Output: 测试
print(i18n.translate("STATUS_OK")) # Output: 操作成功
print(i18n.translate("USER_NOT_FOUND")) # Output: 用户不存在Parameterized Translations
Placeholder Configuration
Use {} placeholders for dynamic content:
zh-CN.ini
# Single parameter
WELCOME_USER = 欢迎,{}!
TEST_PARAM = 测试{}
# Multiple parameters
USER_LOGIN_SUCCESS = 用户 {} 于 {} 成功登录
FILE_UPLOAD_INFO = 文件 {} 上传成功,大小:{} KB
VALIDATION_RANGE = 值必须在 {} 到 {} 之间en.ini
# Single parameter
WELCOME_USER = Welcome, {}!
TEST_PARAM = Test {}
# Multiple parameters
USER_LOGIN_SUCCESS = User {} logged in successfully at {}
FILE_UPLOAD_INFO = File {} uploaded successfully, size: {} KB
VALIDATION_RANGE = Value must be between {} and {}Using Parameterized Translations
from simplejrpc.i18n import T as i18n
# Single parameter
print(i18n.translate_ctx("WELCOME_USER", "张三"))
# Output: 欢迎,张三!
print(i18n.translate_ctx("TEST_PARAM", "国际化"))
# Output: 测试国际化
# Multiple parameters
print(i18n.translate_ctx("USER_LOGIN_SUCCESS", "admin", "2024-01-15 10:30:00"))
# Output: 用户 admin 于 2024-01-15 10:30:00 成功登录
print(i18n.translate_ctx("VALIDATION_RANGE", "1", "100"))
# Output: 值必须在 1 到 100 之间Supported Languages
Standard Language Codes
| Code | Language | Region / Notes | File | Recommended use |
|---|---|---|---|---|
en | English | International | en.ini | Default fallback |
zh-CN | Simplified Chinese | Mainland China | zh-CN.ini | China market |
zh-TW | Traditional Chinese | Taiwan, Hong Kong, Macau | zh-TW.ini | Greater China markets |
ja | Japanese | Japan | ja.ini | Japan market |
ru | Russian | Russia | ru.ini | Russian-speaking regions |
Best Practices
Naming Conventions
# Recommended naming
# 1. Use upper case and underscores
STATUS_OK = 操作成功
ERROR_UNAUTHORIZED = 未授权访问
USER_NOT_FOUND = 用户不存在
# 2. Group keys by feature
# User
USER_LOGIN_SUCCESS = 登录成功
USER_LOGOUT_SUCCESS = 退出成功
USER_PROFILE_UPDATED = 个人资料已更新
# Order
ORDER_CREATED = 订单创建成功
ORDER_CANCELLED = 订单已取消
ORDER_PAYMENT_PENDING = 订单待支付
# 3. Use semantic prefixes
MSG_WELCOME = 欢迎使用
ERR_INVALID_INPUT = 输入无效
WARN_DATA_LOSS = 数据可能丢失
INFO_PROCESSING = 正在处理Keeping Files in Sync
- Check key parity: every language file should contain the same keys.
- Verify completeness: check for missing translations regularly.
- Version control: commit language files with the code.
- Automated tests: add tests that exercise translation.
Examples
Example 1: Internationalized Endpoints
Create endpoints that support multiple languages:
# main.py
import asyncio
from simplejrpc.app import ServerApplication
from simplejrpc.response import jsonify
from simplejrpc.i18n import T as i18n
app = ServerApplication(socket_path="app.socket",i18n_dir="i18n")
@app.route(name="hello")
async def hello(lang):
"""Multilingual greeting endpoint"""
greeting_msg = i18n.translate_ctx("GREETING_MESSAGE", "World")
return jsonify(
data=greeting_msg,
msg=i18n.translate("STATUS_OK")
)
@app.route(name="user_info")
async def get_user_info(lang, user_id: int):
"""Get user information"""
# Mock user data
user_data = {
"id": user_id,
"name": "张三",
"status": "active"
}
success_msg = i18n.translate_ctx("USER_INFO_SUCCESS", user_data["name"])
return jsonify(
data=user_data,
msg=success_msg
)
if __name__ == "__main__":
asyncio.run(app.run())Language files:
# zh-CN.ini
STATUS_OK = 操作成功
GREETING_MESSAGE = 你好,{}!
USER_INFO_SUCCESS = 成功获取用户 {} 的信息# en.ini
STATUS_OK = Operation successful
GREETING_MESSAGE = Hello, {}!
USER_INFO_SUCCESS = Successfully retrieved information for user {}Sample response (Chinese):
{
"jsonrpc": "2.0",
"result": {
"code": 200,
"meta": {"endpoint": null, "close": 1},
"data": "你好,World!",
"msg": "操作成功"
},
"id": 1
}Example 2: Internationalized Errors
Raise errors with localized messages:
# main.py
import asyncio
import os
from simplejrpc.app import ServerApplication
from simplejrpc.response import jsonify
from simplejrpc.i18n import T as i18n
from simplejrpc.exceptions import RPCException
app = ServerApplication(socket_path="app.socket",i18n_dir="i18n")
@app.route(name="get_config_info")
async def get_config_info(lang):
"""Get configuration information"""
try:
config_path = "config.ini"
if not os.path.exists(config_path):
raise FileNotFoundError(i18n.translate("CONFIG_FILE_NOT_FOUND"))
with open(config_path, "r", encoding="utf-8") as f:
data = f.read()
except FileNotFoundError as e:
# RPCException must be the framework exception, otherwise it will not be caught
raise RPCException(i18n.translate("CONFIG_FILE_NOT_FOUND"))
return jsonify(
data={"config": data},
msg=i18n.translate("CONFIG_READ_SUCCESS")
)
if __name__ == "__main__":
asyncio.run(app.run())Error message configuration:
# zh-CN.ini
CONFIG_FILE_NOT_FOUND = 配置文件不存在Sample error response:
{
"jsonrpc": "2.0",
"result": {
"code": 400,
"meta": {"endpoint": null, "close": 1},
"data": null,
"msg": "配置文件不存在"
},
"id": 1
}Example 3: Internationalized Form Validation
In simplejrpc 2.1.7+, TextMessage gives you precise control over form validation messages:
Basic usage:
# main.py
import asyncio
from simplejrpc import TextMessage
from simplejrpc.app import ServerApplication
from simplejrpc.response import jsonify
from simplejrpc.i18n import GI18n, T as i18n
from simplejrpc import (
BaseForm,
RequireValidator,
StringField
)
# Initialize i18n
app = ServerApplication(socket_path="app.socket",i18n_dir="i18n")
class UserRegistrationForm(BaseForm):
"""User registration form"""
username = StringField(
validators=[RequireValidator(
TextMessage("PARAMETER_CANNOT_BE_EMPTY")
)]
)
email = StringField(
validators=[RequireValidator(
TextMessage("PARAMETER_CANNOT_BE_EMPTY")
)]
)
role = StringField(
validators=[RequireValidator(
TextMessage("PARAMETER_CANNOT_BE_EMPTY")
)]
)
@app.route(name="user_register", form=UserRegistrationForm)
async def user_register(lang, username, email, role):
"""User registration endpoint"""
# Mock registration logic
user_data = {
"id": 12345,
"username": username,
"email": email,
"role": role
}
return jsonify(
data=user_data,
msg=i18n.translate_ctx("USER_REGISTER_SUCCESS", username)
)
if __name__ == "__main__":
asyncio.run(app.run())Language files:
# zh-CN.ini
PARAMETER_CANNOT_BE_EMPTY = "参数不能为空"# en.ini
PARAMETER_CANNOT_BE_EMPTY = "Parameters cannot be empty"Sample validation failure:
{
"jsonrpc": "2.0",
"result": {
"code": 400,
"meta": {"endpoint": null, "close": 1},
"data": null,
"msg": "参数不能为空"
},
"id": 1
}Important
- Do not call
i18n.translate()directly inside validators; it can fail when the context has not been initialized. - Use
TextMessage; it is safer and more reliable. - Make sure every language file contains the same keys.
Automatic i18n Loading
ServerApplication can find the i18n directory automatically, and you can also point to it explicitly:
from simplejrpc.app import ServerApplication
# Option 1: pass the directory explicitly
app = ServerApplication(
socket_path="app.socket",
i18n_dir="i18n" # i18n directory
)
# Option 2: omit it and let the framework search
app = ServerApplication(
socket_path="app.socket"
# The framework looks for an i18n directory in the project root
)