Source code for pyramid_localize.models

# Copyright (c) 2013-2014 by pyramid_localize authors and contributors <see AUTHORS file>
# This module is part of pyramid_localize and is released under
# the MIT License (MIT):
"""Language model."""
import gettext

from sqlalchemy import Column
from sqlalchemy import Sequence
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import Unicode
from sqlalchemy import DateTime
from sqlalchemy import func
from sqlalchemy import event
from pyramid.compat import PY3, text_type
from pyramid_basemodel import Base
import pycountry

[docs]class Language(Base): """Language table model definition.""" __tablename__ = 'languages' id = Column(Integer, Sequence(__tablename__ + '_sq'), primary_key=True) updated_at = Column(DateTime,,, nullable=False) name = Column(Unicode(45), nullable=False) native_name = Column(Unicode(45), nullable=False) language_code = Column(String(2), unique=True, nullable=False) # ISO 639-1 (Alpha2) def __unicode__(self): # pragma: no cover """Language to unicode conversion.""" return def __str__(self): # pragma: no cover """Language to string conversion.""" return'utf8')
[docs]@event.listens_for(Language, 'before_insert') def before_language_insert(_, __, language): """Set name and native_name before creation.""" # Check language code try: lang_data = pycountry.languages.get(alpha_2=language.language_code) except KeyError: # Language code not recognized, set defaults = text_type('UNKNOWN') language.native_name = text_type('UNKNOWN') return # Set name and native_name = text_type( if language.language_code == text_type('en'): # English does not have a translation file language.native_name = text_type( else: lang_locale = gettext.translation( 'iso639_3', pycountry.LOCALES_DIR, languages=[language.language_code] ) localize = lang_locale.gettext if PY3: language.native_name = text_type(localize( else: language.native_name = text_type(localize(, 'utf-8')