awesome-asgi
awesome-asgi copied to clipboard
Add ASGI-Babel
Checklist
- [x] This project is explicitly related to ASGI.
- [x] The new list entry contains a project name, URL and description.
What is this project?
ASGI-Babel - Adds internationalization (i18n) support to ASGI applications (asyncio / trio)
Do you know about other similar projects?
Yes If so, how is this one different?
No one internationalization tool is here
Anyone who agrees with this pull request can add a 👍.
Thanks, this one is quite exciting! I don't think there are equivalent tools like this one yet. I was personally eager to look into ASGI i18n some time ago to power French/English articles on my blog. :-)
Are there some examples of using this package in the wild yet?
@florimondmanca you able to find a little reference in the ASGI-Babel readme.
First, you need to extract messages from your python/templates/etc files using pybabel
(http://babel.pocoo.org/en/latest/messages.html, http://babel.pocoo.org/en/latest/cmdline.html) and compile them. I'm not including any code for extracting/compiling because babel can do it and I don't think we need it inside the middleware.
After you have to add the middleware into your ASGI application (Im using asgi_tools.ResponseHTML
here for simplicity, you are able to use starlette.HTMLResponse
, etc or return ASGI messages manually):
from asgi_babel import BabelMiddleware, gettext
from asgi_tools import ResponseHTML
async def app(scope, send, receive):
message = gettext('A string to translate')
response = ResponseHTML(message)
await response(scope, send, receive)
app = BabelMIddleware(app, locales_dirs=['path/to/your/locales'])
That's it. By default, BabelMiddleware parses a request's accept-language
header and load the current user locale babel.Locale
into asgi_babel.current_locale
context variable. You are able to customize the method to get the current locale (from lang
cookie for example, or from query string/path, etc). The middleware provides the methods to translate text: gettext, ngettext, pgettext, npgettext
which are bound to the current locale. Also you can use the current locale to get user's timezones, first day of week, number formats, currencies and etc.
@florimondmanca also you are able to check a simple example here: https://github.com/klen/asgi-babel/blob/develop/example/init.py
Makefile contains instructions on how I extract the messages: https://github.com/klen/asgi-babel/blob/develop/Makefile#L67
In real life, you can use templates (jinja/etc) and extract locale messages from them. You will need to install asgi-babel
callables to your jinja2 env and use i18n inside the templates after.