Giter Club home page Giter Club logo

asgi-babel's Introduction

ASGI-Babel

asgi-babel -- Adds internationalization (i18n) support to ASGI applications (Asyncio / Trio / Curio)

Tests Status

PYPI Version

Python Versions

Requirements

  • python >= 3.8

Installation

asgi-babel should be installed using pip: :

pip install asgi-babel

Usage

Common ASGI applications:

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!

As ASGI-Tools Internal middleware

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

Usage with Curio async library

The asgi-babel uses context variable to set current locale. To enable the context variables with curio you have to run Curio with contextvars support:

from curio.task import ContextTask

curio.run(main, taskcls=ContextTask)

Options

The middleware's options with default values:

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,

)

How to extract & compile locales:

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

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

Bug tracker

If you have any suggestions, bug reports or annoyances please report them to the issue tracker at https://github.com/klen/asgi-babel/issues

Contributing

Development of the project happens at: https://github.com/klen/asgi-babel

License

Licensed under a MIT license.

asgi-babel's People

Contributors

klen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

Forkers

frankie567

asgi-babel's Issues

Add support for lazy gettext functions variants

Hello there ๐Ÿ‘‹

When developing web apps, it's a common pattern to put translated strings in modules or class definitions. For example, with WTForms:

class RegistrationForm(Form):
    name = StringField(_('Name'))

At module import, the locale is not yet known, maybe messages are even not loaded. To circumvent this, frameworks usually come with "lazy" variants of functions which are interpolated only when rendering the final template, at a time where the locale is known.

Currently, asgi-babel only provides the "normal" gettext functions. It could be useful to have the lazy variants at hand in this context.

The implementation should be quite straightforward, as Babel conveniently bundles as LazyProxy class. It could look like this:

def gettext_lazy(string: str, domain: str = None, **variables):
    return support.LazyProxy(gettext, string, domain, **variables)

# ... and so on for `pgettext` and `npgettext`

I've tested it in one of my project, and it works well. Do you think it would be a useful addition? If so, I would be happy to propose a PR for this.

Cheers!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.