File: email.py

package info (click to toggle)
python-sqlalchemy-utils 0.41.2-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,252 kB
  • sloc: python: 13,566; makefile: 141
file content (48 lines) | stat: -rw-r--r-- 1,259 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
import sqlalchemy as sa

from ..operators import CaseInsensitiveComparator


class EmailType(sa.types.TypeDecorator):
    """
    Provides a way for storing emails in a lower case.

    Example::


        from sqlalchemy_utils import EmailType


        class User(Base):
            __tablename__ = 'user'
            id = sa.Column(sa.Integer, primary_key=True)
            name = sa.Column(sa.Unicode(255))
            email = sa.Column(EmailType)


        user = User()
        user.email = 'John.Smith@foo.com'
        user.name = 'John Smith'
        session.add(user)
        session.commit()
        # Notice - email in filter() is lowercase.
        user = (session.query(User)
                       .filter(User.email == 'john.smith@foo.com')
                       .one())
        assert user.name == 'John Smith'
    """
    impl = sa.Unicode
    comparator_factory = CaseInsensitiveComparator
    cache_ok = True

    def __init__(self, length=255, *args, **kwargs):
        super().__init__(length=length, *args, **kwargs)

    def process_bind_param(self, value, dialect):
        if value is not None:
            return value.lower()
        return value

    @property
    def python_type(self):
        return self.impl.type.python_type