def test_serialize_value(self):
now = datetime.datetime.now()
self.assertEqual(now.isoformat(), fields.serialize_value(now))
unique_id = uuid.uuid4()
self.assertEqual(str(unique_id), fields.serialize_value(unique_id))
self.assertEqual(
{"now": now.isoformat()},
fields.serialize_value({"now": now})
)
self.assertEqual(
"Europe/Paris",
fields.serialize_value(timezone("Europe/Paris"))
)
self.assertEqual(
"en_US",
fields.serialize_value(Locale("en_US"))
)
python类Locale()的实例源码
def cast_locale(obj, locale):
"""
Cast given locale to string. Supports also callbacks that return locales.
:param obj:
Object or class to use as a possible parameter to locale callable
:param locale:
Locale object or string or callable that returns a locale.
"""
if callable(locale):
try:
locale = locale()
except TypeError:
locale = locale(obj)
if isinstance(locale, babel.Locale):
return str(locale)
return locale
def new_lang_view(self):
lang = self.request.POST.get('new_lang', '').strip()
try:
self.request.locale = babel.Locale(*babel.parse_locale(lang))
if not os.path.isdir(os.path.join(self.helper.locale_dir, lang)):
os.mkdir(os.path.join(self.helper.locale_dir, lang))
os.mkdir(os.path.join(self.helper._dir, 'locale', lang, 'LC_MESSAGES'))
# self.pot.save(os.path.join(self.helper.package_dir, 'locale', lang, 'LC_MESSAGES',
# '{0}.po'.format(self.domain)))
# self.pot.save_as_mofile(os.path.join(self.helper.package_dir, 'locale', lang, 'LC_MESSAGES',
# '{0}.mo'.format(self.domain)))
self.request.flash_message.add(message_type='success', body='i18n_new_lang_creation_success', domain='i18n_helper')
return HTTPFound(location=self.request.route_url('i18n_helper.po', lang=lang, domain=self.domain))
else:
self.request.flash_message.add(message_type='danger', body='i18n_new_lang_lang_exist', domain='i18n_helper')
except:
self.request.flash_message.add(message_type='danger', body='i18n_new_lang_creation_error', domain='i18n_helper')
return self.get_view()
def __init__(self, context, request: Request):
self.request = request
self.context = context
_ = request.translate
self.helper = request.registry['i18n_helper']
self.lang = request.matchdict['lang']
self.domain = request.matchdict['domain']
self.locale = babel.Locale(*babel.parse_locale(self.lang))
self.pot_file_path = os.path.join(self.helper.locale_dir, '{0}.pot'.format(self.domain))
self.po_file_path = os.path.join(self.helper.locale_dir, self.lang, 'LC_MESSAGES',
'{0}.po'.format(self.domain))
self.mo_file_path = os.path.join(self.helper.locale_dir, self.lang, 'LC_MESSAGES',
'{0}.mo'.format(self.domain))
if os.path.exists(self.po_file_path):
self.po = polib.pofile(self.po_file_path, encoding='UTF-8')
else:
self.po = polib.POFile(encoding='UTF-8')
self.po.metadata= {'Content-Transfer-Encoding': '8bit',
'Content-Type': 'text/plain; charset=UTF-8',
'Language': self.lang}
def add_localizer(event):
request = event.request
localizer = request.localizer
helper = request.registry['i18n_helper']
collect_msgid = asbool(request.registry.settings.get('i18n_helper.collect_msgid'))
def auto_translate(string, mapping=None, domain=None):
if collect_msgid:
tmp = domain if domain else helper.package_name
if not tmp in helper.pot_msgids:
helper.pot_msgids[tmp] = set()
helper.pot_msgids[tmp].add(string)
return localizer.translate(helper.tsf(string), mapping=mapping, domain=domain)
# request.localizer = localizer
request.translate = auto_translate
request.locale = babel.Locale(*babel.parse_locale(request.localizer.locale_name))
def localized_measures():
print('Localized measurement units')
units = (
'area-square-meter',
'consumption-liter-per-100kilometers',
'pressure-hectopascal',
'duration-century',
'energy-kilowatt-hour',
'volume-pint',
)
for (name, symbol, params) in LOCALES:
locale = Locale(*params)
args = [name]
for unit in units:
unit_name = get_unit_name(unit, locale=locale)
if unit_name is None:
unit_name = 'N/A ({0})'.format(unit)
args.append(unit_name)
print('\nin {0}: {1} - {2} - {3} - {4} - {5} - {6}'.format(*args))
def units_formating():
print('Formating values in units')
values = (
(12.4, 'area-square-meter'),
(7.7, 'consumption-liter-per-100kilometers'),
(1017, 'pressure-hectopascal'),
(9, 'duration-century'),
(11, 'energy-kilowatt-hour'),
(2, 'volume-pint'),
)
for (name, symbol, params) in LOCALES:
locale = Locale(*params)
args = [name]
for (value, unit) in values:
val_long = format_unit(value, unit, 'long', locale=locale)
short_name = get_unit_name(unit, 'short', locale=locale)
args.append('{0} ({1})'.format(val_long, short_name))
print('\nin {0}: {1} - {2} - {3} - {4} - {5} - {6}'.format(*args))
def time_deltas():
print('Periods of time (timedelta)')
deltas = (
datetime.timedelta(minutes=15),
datetime.timedelta(hours=3),
datetime.timedelta(days=8),
datetime.timedelta(weeks=5),
)
for (name, symbol, params) in LOCALES:
locale = Locale(*params)
args = [name]
for delta in deltas:
args.append(format_timedelta(delta, locale=locale))
print('\tbasic {0}: {1} - {2} - {3} - {4}'.format(*args))
args = [name]
for delta in deltas:
args.append(format_timedelta(delta, granularity='day', locale=locale))
print('\tday granularity {0}: {1} - {2} - {3} - {4}'.format(*args))
def test_url_for_with_locale_object(self):
url = '/foo/de/dataset/my_dataset'
generated_url = h.url_for('/dataset/my_dataset',
locale=Locale('de'))
eq_(generated_url, url)
def serialize_value(value):
"""
Utility function to handle the parsing of specific fields.
"""
if isinstance(value, datetime.datetime):
return value.isoformat()
if isinstance(value, datetime.date):
return value.isoformat()
elif isinstance(value, uuid.UUID):
return str(value)
elif isinstance(value, dict):
return serialize_dict(value)
elif isinstance(value, orm.collections.InstrumentedList):
return serialize_orm_arrays(value)
elif isinstance(value, bytes):
return value.decode("utf-8")
elif isinstance(value, str):
return value
elif isinstance(value, int):
return value
elif isinstance(value, Locale):
return str(value)
elif isinstance(value, type(timezone("Europe/Paris"))):
return str(value)
elif isinstance(value, list):
return serialize_list(value)
elif value is None:
return None
elif isinstance(value, object):
if hasattr(value, 'serialize'):
return value.serialize()
else:
return value
else:
return value
def __init__(self, locale='en_GB'):
self.locale = Locale(locale)
def process_bind_param(self, value, dialect):
if isinstance(value, babel.Locale):
return six.text_type(value)
if isinstance(value, six.string_types):
return value
def process_result_value(self, value, dialect):
if value is not None:
return babel.Locale.parse(value)
def _coerce(self, value):
if value is not None and not isinstance(value, babel.Locale):
return babel.Locale.parse(value)
return value
def validate(self, code):
try:
i18n.babel.Locale('en').currencies[code]
except KeyError:
raise ValueError("'{0}' is not valid currency code.".format(code))
def select_lang_view(self):
lang = self.request.POST.get('select_lang', '').strip()
self.request.locale = babel.Locale(*babel.parse_locale(lang))
return HTTPFound(location=self.request.route_url('i18n_helper.po', lang=lang, domain=self.domain))
def list_format():
print('Formating lists')
items = (
'one',
'two',
'three',
'four',
'five'
)
for (name, symbol, params) in LOCALES:
locale = Locale(*params)
result = format_list(items, locale=locale)
print('\tlist in {0} - {1}'.format(name, result))
def format_class():
print('Utility class that holds all formating functionality for single locale')
date = datetime.date(1874, 5, 29)
amount = (284.55, 'CNY')
for (name, symbol, params) in LOCALES:
locale = Locale(*params)
fmt = Format(locale=locale)
args = [name]
args.append(fmt.date(date, format='full'))
args.append(fmt.currency(*amount))
print('\tFormats for {0} - date: {1}, currency: {2}'.format(*args))
def languages():
print('Known languages')
locale = Locale('en', 'US')
for (_, _, params) in LOCALES:
territory = params[1]
official_languages = format_list(get_official_languages(territory), locale=locale)
all_languages = format_list(get_official_languages(territory, regional=True, de_facto=True), locale=locale)
print('\tterritory: {0}'.format(locale.territories[territory]))
print('\t\tofficial: {0}\n\t\tall: {1}'.format(official_languages, all_languages))
def my_birthday():
print('My birthday in different locales')
bday = datetime.date(1971, 5, 4)
for (name, symbol, params) in LOCALES:
locale = Locale(*params)
for fmt in ('full', 'medium', 'short'):
print('\t{0} ({1}): {2}'.format(name, fmt, format_date(bday, fmt, locale)))
def timezone_names():
print('Timezone data')
tznames = ('Europe/Athens', 'US/Alaska', 'Africa/Johannesburg')
for (name, symbol, params) in LOCALES:
locale = Locale(*params)
for tzname in tznames:
tz = get_timezone(tzname)
loc_name = get_timezone_location(tz, locale, False)
city = get_timezone_location(tz, locale, True)
print('\tTZ location for {0}: {1}, city: {2}'.format(tzname, loc_name, city))
def locale_own_data():
print('Locale data (pl - language only):')
locale = Locale('pl')
print('\tDisplay name: {0}'.format(locale.display_name))
print('\tEnglish name: {0}'.format(locale.english_name))
print('Locale data (pl_PL - language and territory):')
locale = Locale('pl', 'PL')
print('\tDisplay name: {0}'.format(locale.display_name))
print('\tEnglish name: {0}'.format(locale.english_name))
def localized_locale_data():
print('Localized locale data')
for (name, symbol, params) in LOCALES:
print('Now switch to {0} ({1})'.format(name, symbol))
locale = Locale(*params)
print('\tLocale display name: {0}'.format(locale.display_name))
print('\tLocale English name: {0}'.format(locale.english_name))
print('\tPoland (localized): {0}'.format(locale.territories['PL']))
print('\tRomanian New Lei (localized): {0}'.format(locale.currencies['RON']))
print('\tRomanian Old Lei (localized): {0}'.format(locale.currencies['ROL']))
print('\t1st weekday (localized): {0}'.format(locale.days['format']['wide'][locale.first_week_day]))
print('\tMay month name (localized): {0}'.format(locale.months['format']['wide'][5]))
def decimal_formating():
print('Formating decimal values')
numbers = (-3.14, 0.12, 2, 9.821, 215.3, 19678.25)
for (name, symbol, params) in LOCALES:
locale = Locale(*params)
args = [name]
for num in numbers:
args.append(format_decimal(num, locale=locale))
print('\tdecimal in {0}: {1} - {2} - {3} - {4} - {5} - {6}'.format(*args))
def __init__(self, context, request: Request):
self.request = request
self.context = context
self.domain = request.matchdict['domain']
_ = request.translate
self.helper = request.registry['i18n_helper']
self.pot = polib.pofile(
os.path.join(self.helper.locale_dir, '{0}.pot'.format(self.domain)),
encoding='UTF-8'
)
# LANG FORM
langs_dir = self.helper.locale_dir
created_langs_choices = []
for lang in os.listdir(langs_dir):
if os.path.isdir(os.path.join(langs_dir, lang)):
lang_locale = babel.Locale(*babel.parse_locale(lang))
created_langs_choices.append(
(lang , '{en_name}/{display_name}'.format(
en_name=lang_locale.english_name,
display_name=lang_locale.display_name )
)
)
available_langs_choices = sorted(locale.locale_alias)
class NewLang(colander.Schema):
new_lang = colander.SchemaNode(colander.String(),
widget=deform.widget.AutocompleteInputWidget(values=available_langs_choices,
min_length=0),
title=_("i18n_new_lang", domain='i18n_helper'))
class SelectLang(colander.Schema):
select_lang = colander.SchemaNode(colander.String(),
widget=deform.widget.SelectWidget(values=created_langs_choices),
title=_("i18n_select_lang", domain='i18n_helper'))
def validator(node, appstruct):
return True
schema = NewLang(validator=validator)
schema = schema.bind(request=self.request)
self.new_lang_form = deform.Form(schema,
use_ajax=False,
action=self.request.route_url('i18n_helper.pot', domain=self.domain))
self.new_lang_form.buttons.append(deform.Button(name='submit', title=_('i18n_new_lang_submit', domain='i18n_helper')))
schema = SelectLang(validator=validator)
schema = schema.bind(request=self.request)
self.select_lang_form = deform.Form(schema,
use_ajax=False,
action=self.request.route_url('i18n_helper.pot', domain=self.domain))
self.select_lang_form.buttons.append(deform.Button(name='submit', title=_('i18n_select_lang_submit', domain='i18n_helper')))
# MSG FORM