支持ASGI应用程序的国际化(i18n)
项目描述
asgi-babel – 为ASGI应用程序(Asyncio / Trio / Curio)添加国际化(i18n)支持
需求
python >= 3.9
安装
asgi-babel 应使用pip安装
pip install asgi-babel
用法
常见的ASGI应用程序
from asgi_babel import BabelMiddleware, current_locale, gettext
async def my_app(scope, receive, send):
"""Get a current locale."""
locale = current_locale.get().language.encode()
hello_world = gettext('Hello World!').encode()
await send({"type": "http.response.start", "status": 200})
await send({"type": "http.response.body", "body": b"Current locale is %s\n" % locale})
await send({"type": "http.response.body", "body": hello_world})
app = BabelMiddleware(my_app, locales_dirs=['tests/locales'])
# http GET /
#
# Current_locale is en
# Hello World!
# http GET / "accept-language: ft-CH, fr;q-0.9"
#
# Current_locale is fr
# Bonjour le monde!
作为ASGI-Tools 内部中间件
from asgi_tools import App
from asgi_babel import BabelMiddleware, gettext
app = App()
app.middleware(BabelMiddleware.setup(locales_dirs=['tests/locales']))
@app.route('/')
async def index(request):
return gettext('Hello World!')
@app.route('/locale')
async def locale(request):
return current_locale.get().language
与Curio异步库一起使用
asgi-babel 使用上下文变量来设置当前区域设置。要在Curio中启用上下文变量,您必须以支持contextvars的方式运行Curio
from curio.task import ContextTask
curio.run(main, taskcls=ContextTask)
选项
中间件的默认选项
from asgi_babel import BabelMiddleware
app = BabelMiddleware(
# Your ASGI application
app,
# Default locale
default_locale='en',
# A path to find translations
locales_dirs=['locales']
# A function with type: typing.Callable[[asgi_tools.Request], t.Awaitable[t.Optional[str]]]
# which takes a request and default locale and return current locale
locale_selector=asgi_babel.select_locale_by_request,
)
如何提取和编译区域设置
错误追踪器
如果您有任何建议、错误报告或烦恼,请向https://github.com/klen/asgi-babel/issues 的问题跟踪器报告
贡献
项目开发地点:[https://github.com/klen/asgi-babel]
许可协议
遵循MIT许可协议。
项目详细信息
下载文件
下载适合您平台的文件。如果您不确定该选择哪个,请了解有关安装包的更多信息。
源分发
asgi_babel-0.10.0.tar.gz (6.7 kB 查看哈希值)
构建分发
asgi_babel-0.10.0-py3-none-any.whl (5.9 kB 查看哈希值)
关闭
asgi_babel-0.10.0.tar.gz的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 7b049dd34d026428209552753d8b455dd4137a07fb35065d8bf9bddddf9c7ba9 |
|
MD5 | adec8c09ed58d7c11972dad1e5048862 |
|
BLAKE2b-256 | a4cf4b3cb372393c49f5c747ec1f76be8f0fcdd26c344a94436657cd343b32ca |
关闭
asgi_babel-0.10.0-py3-none-any.whl的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | bed95420df1770b99ed9b476b8b6b576d46072d5b2b3208f0882e7cf1b0d020e |
|
MD5 | 38122d0fd525e11b1918ea10e0e6f048 |
|
BLAKE2b-256 | 1d4de9556900606350dabf3d3f63b44c0d6079db721cc38832a84f799ab30b5a |