跳转到主要内容

支持ASGI应用程序的国际化(i18n)

项目描述

asgi-babel – 为ASGI应用程序(Asyncio / Trio / Curio)添加国际化(i18n)支持

Tests Status PYPI Version Python Versions

需求

  • 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,

)

如何提取和编译区域设置

http://babel.pocoo.org/en/latest/messages.html

http://babel.pocoo.org/en/latest/cmdline.html

错误追踪器

如果您有任何建议、错误报告或烦恼,请向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 查看哈希值)

上传时间: Python 3

由以下组织支持