File: url.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 (68 lines) | stat: -rw-r--r-- 1,525 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
65
66
67
68
from sqlalchemy import types

from .scalar_coercible import ScalarCoercible

furl = None
try:
    from furl import furl
except ImportError:
    pass


class URLType(ScalarCoercible, types.TypeDecorator):
    """
    URLType stores furl_ objects into database.

    .. _furl: https://github.com/gruns/furl

    ::

        from sqlalchemy_utils import URLType
        from furl import furl


        class User(Base):
            __tablename__ = 'user'

            id = sa.Column(sa.Integer, primary_key=True)
            website = sa.Column(URLType)


        user = User(website='www.example.com')

        # website is coerced to furl object, hence all nice furl operations
        # come available
        user.website.args['some_argument'] = '12'

        print user.website
        # www.example.com?some_argument=12
    """

    impl = types.UnicodeText
    cache_ok = True

    def process_bind_param(self, value, dialect):
        if furl is not None and isinstance(value, furl):
            return str(value)

        if isinstance(value, str):
            return value

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

        if value is not None:
            return furl(value)

    def _coerce(self, value):
        if furl is None:
            return value

        if value is not None and not isinstance(value, furl):
            return furl(value)
        return value

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