File: country.py

package info (click to toggle)
python-sqlalchemy-utils 0.41.2-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 1,252 kB
  • sloc: python: 13,566; makefile: 141
file content (64 lines) | stat: -rw-r--r-- 1,579 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from sqlalchemy import types

from ..primitives import Country
from .scalar_coercible import ScalarCoercible


class CountryType(ScalarCoercible, types.TypeDecorator):
    """
    Changes :class:`.Country` objects to a string representation on the way in
    and changes them back to :class:`.Country objects on the way out.

    In order to use CountryType you need to install Babel_ first.

    .. _Babel: https://babel.pocoo.org/

    ::


        from sqlalchemy_utils import CountryType, Country


        class User(Base):
            __tablename__ = 'user'
            id = sa.Column(sa.Integer, autoincrement=True)
            name = sa.Column(sa.Unicode(255))
            country = sa.Column(CountryType)


        user = User()
        user.country = Country('FI')
        session.add(user)
        session.commit()

        user.country  # Country('FI')
        user.country.name  # Finland

        print user.country  # Finland


    CountryType is scalar coercible::


        user.country = 'US'
        user.country  # Country('US')
    """
    impl = types.String(2)
    python_type = Country
    cache_ok = True

    def process_bind_param(self, value, dialect):
        if isinstance(value, Country):
            return value.code

        if isinstance(value, str):
            return value

    def process_result_value(self, value, dialect):
        if value is not None:
            return Country(value)

    def _coerce(self, value):
        if value is not None and not isinstance(value, Country):
            return Country(value)
        return value