开发者

Using Python locale or equivalent in web applications?

Python's locale implementation seems to want to either read the locale from system settings or have it be set via a setlocale call. Neither of these work for me since I'd like to use the capabilities in a web application, where the desired locale is the user's locale.

And there are warnings in the locale docs that make the whole thing scary:

On top of that, some implementation are broken in such a way that frequent locale changes may cause core dumps. This makes the locale somewhat painful to use correctly

And

It is generally a bad idea to call setlocale() in some library routine, since as a side effect it affects the entire program

So, is there a reasonable locale alternative for use in web apps? Is Babel it or are there other alternatives? I'm looking for something that will handle currencies as well as dates and numbers.

[Update] To clarify, I'm most开发者_StackOverflow社区 interested in date, number, and currency formatting for various locales.


locale is no good for any app that needs to support several locales -- it's really badly designed for those apps (basically any server-side app, including web apps). Where feasible, PyICU is a vastly superior solution -- top-quality i18n/L10n support, speed, flexibility (downside: while ICU's docs are good, PyICU's, well, not so much;-). Alas, not always are you allowed to deploy your own extensions...:-(.

In particular, I'm still looking for a solid i18n/L10n solution for App Engine apps -- "translation" per se is the least of issues (you can just switch to the right set of templates), the problem is that there are many other L10n aspects (the ones that ICU supports so well, such as collation rules for example, etc, etc). I guess the already-mentioned Babel is the only sensible place to start from.


Don't use setlocale.

Check how it is done in django. It looks like they use class api of gettext library and do not use the setlocale function I bet there is a reason for this.

They manually store a translation per thread check here how it is implemented (gettext function and _active dictionary).


Your best approach will be to setlocale on the locale that the browser passes you, if you're doing currencies, dates, and numbers. There's a lot of zomgz warnings in the Python documentation for really off-color platforms; most of these can be ignored.

"Frequent locale changes" shouldn't matter, unless I'm missing something.

You're not doing message catalogs or anything fancy, so stick with what Python gives you.


Django's i18n framework works out the shortcomings of setlocale() by not using it. This way the locale is set per request and if you use LocaleMiddleware it can be set to change according to UserAgent Accept-Language setting. See the docs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜