File: url.py

package info (click to toggle)
python-sqlalchemy-utils 0.30.12-2~bpo8%2B1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 1,056 kB
  • sloc: python: 10,350; makefile: 160
file content (67 lines) | stat: -rw-r--r-- 1,539 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
furl = None
try:
    from furl import furl
except ImportError:
    pass
import six
from sqlalchemy import types

from .scalar_coercible import ScalarCoercible


class URLType(types.TypeDecorator, ScalarCoercible):
    """
    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=u'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

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

        if isinstance(value, six.string_types):
            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