fastapi-babel icon indicating copy to clipboard operation
fastapi-babel copied to clipboard

default language localization not working

Open ShahidGhetiwalaXerox opened this issue 1 year ago • 1 comments

Hi @Legopapurida ,

I have encountered an issue with the Babel class in library while setting up internationalization for my FastAPI-based application.

Issue Description:

When the default language is set to "en" (English), attempting to get a localized message by sending the Accept-Language header with "en" returns the key itself instead of the localized message. However, when I set the header Accept-Language to "fr" (French) other than the default, I correctly receive the response in French.

babel_configs = BabelConfigs(
    ROOT_DIR=__file__,
    BABEL_DEFAULT_LOCALE="en",
    BABEL_TRANSLATION_DIRECTORY="lang",
)
app.add_middleware(BabelMiddleware, babel_configs=babel_configs)

Furthermore, if I set the default language to "fr" and request localization in "fr," the same issue occurs, where the key itself is returned instead of the localized message.

Code Example:

Here's a snippet of my API call for testing using FastAPI:

from fastapi_babel import _

@api_router.get("/hello")
async def hello():
    return {"message": _("created")}

Debugging Findings: Upon debugging the code, I found the following function in the Babel class:

@property
def gettext(self) -> Callable[[str], str]:
    if self.default_locale != self.locale:
        gt = translation(
            self.domain,
            self.config.BABEL_TRANSLATION_DIRECTORY,
            [self.locale],
        )
        gt.install()
        return gt.gettext
    return gettext

When I removed the condition if self.default_locale != self.locale , the localization worked correctly for the default language.

Could you please confirm if this is a bug or if I am missing something in my configuration?

ShahidGhetiwalaXerox avatar Jul 03 '24 20:07 ShahidGhetiwalaXerox

I will check the problem and resolve this

Legopapurida avatar Jul 17 '24 18:07 Legopapurida

You can not use default locale after any income request so it just ignore every predefined locales

Legopapurida avatar Dec 05 '24 21:12 Legopapurida