Anbarryprojects / fastapi-babel

FastAPI babel support pybable tools like translation of text, formatting of dates, times and numbers, and time zones.
MIT License
49 stars 15 forks source link

default language localization not working #43

Open ShahidGhetiwalaXerox opened 2 months ago

ShahidGhetiwalaXerox commented 2 months ago

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?

Legopapurida commented 1 month ago

I will check the problem and resolve this