Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/sqlalchemy_utils/types/country.py: 63%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

19 statements  

1from sqlalchemy import types 

2 

3from ..primitives import Country 

4from .scalar_coercible import ScalarCoercible 

5 

6 

7class CountryType(ScalarCoercible, types.TypeDecorator): 

8 """ 

9 Changes :class:`.Country` objects to a string representation on the way in 

10 and changes them back to :class:`.Country` objects on the way out. 

11 

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

13 

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

15 

16 :: 

17 

18 

19 from sqlalchemy_utils import CountryType, Country 

20 

21 

22 class User(Base): 

23 __tablename__ = 'user' 

24 id = sa.Column(sa.Integer, autoincrement=True) 

25 name = sa.Column(sa.Unicode(255)) 

26 country = sa.Column(CountryType) 

27 

28 

29 user = User() 

30 user.country = Country('FI') 

31 session.add(user) 

32 session.commit() 

33 

34 user.country # Country('FI') 

35 user.country.name # Finland 

36 

37 print user.country # Finland 

38 

39 

40 CountryType is scalar coercible:: 

41 

42 

43 user.country = 'US' 

44 user.country # Country('US') 

45 """ 

46 

47 impl = types.String(2) 

48 python_type = Country 

49 cache_ok = True 

50 

51 def process_bind_param(self, value, dialect): 

52 if isinstance(value, Country): 

53 return value.code 

54 

55 if isinstance(value, str): 

56 return value 

57 

58 def process_result_value(self, value, dialect): 

59 if value is not None: 

60 return Country(value) 

61 

62 def _coerce(self, value): 

63 if value is not None and not isinstance(value, Country): 

64 return Country(value) 

65 return value