summaryrefslogtreecommitdiff
path: root/src/couch/utils.py
blob: 1cd21d8155c061684aa15276485fa18fc7490083 (plain)
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# -*- coding: utf-8 -*-
# Based on py-couchdb (https://github.com/histrio/py-couchdb)


import json
import sys


if sys.version_info[0] == 3:
    from urllib.parse import unquote as _unquote
    from urllib.parse import urlunsplit, urlsplit

    string_type = str
    bytes_type = bytes

    from functools import reduce

else:
    from urllib import unquote as _unquote
    from urlparse import urlunsplit, urlsplit

    string_type = unicode  # noqa: F821
    bytes_type = str

URLSPLITTER = '/'


json_encoder = json.JSONEncoder()


def extract_credentials(url):
    """
    Extract authentication (user name and password) credentials from the
    given URL.

    >>> extract_credentials('http://localhost:5984/_config/')
    ('http://localhost:5984/_config/', None)
    >>> extract_credentials('http://joe:secret@localhost:5984/_config/')
    ('http://localhost:5984/_config/', ('joe', 'secret'))
    >>> extract_credentials('http://joe%40example.com:secret@'
    ...                      'localhost:5984/_config/')
    ('http://localhost:5984/_config/', ('joe@example.com', 'secret'))
    """
    parts = urlsplit(url)
    netloc = parts[1]
    if '@' in netloc:
        creds, netloc = netloc.split('@')
        credentials = tuple(_unquote(i) for i in creds.split(':'))
        parts = list(parts)
        parts[1] = netloc
    else:
        credentials = None
    return urlunsplit(parts), credentials


def _join(head, tail):
    parts = [head.rstrip(URLSPLITTER), tail.lstrip(URLSPLITTER)]
    return URLSPLITTER.join(parts)


def urljoin(base, *path):
    """
    Assemble a uri based on a base, any number of path segments, and query
    string parameters.

    >>> urljoin('http://example.org', '_all_dbs')
    'http://example.org/_all_dbs'

    A trailing slash on the uri base is handled gracefully:

    >>> urljoin('http://example.org/', '_all_dbs')
    'http://example.org/_all_dbs'

    And multiple positional arguments become path parts:

    >>> urljoin('http://example.org/', 'foo', 'bar')
    'http://example.org/foo/bar'

    >>> urljoin('http://example.org/', 'foo/bar')
    'http://example.org/foo/bar'

    >>> urljoin('http://example.org/', 'foo', '/bar/')
    'http://example.org/foo/bar/'

    >>> urljoin('http://example.com', 'org.couchdb.user:username')
    'http://example.com/org.couchdb.user:username'
    """
    return reduce(_join, path, base)


def as_json(response):
    if "application/json" in response.headers['content-type']:
        response_src = response.content.decode('utf-8')
        if response.content != b'':
            return json.loads(response_src)
        else:
            return response_src
    return None


def _path_from_name(name, type):
    """
    Expand a 'design/foo' style name to its full path as a list of
    segments.

    >>> _path_from_name("_design/test", '_view')
    ['_design', 'test']
    >>> _path_from_name("design/test", '_view')
    ['_design', 'design', '_view', 'test']
    """
    if name.startswith('_'):
        return name.split('/')
    design, name = name.split('/', 1)
    return ['_design', design, type, name]


def encode_view_options(options):
    """
    Encode any items in the options dict that are sent as a JSON string to a
    view/list function.

    >>> opts = {'key': 'foo', "notkey":"bar"}
    >>> res = encode_view_options(opts)
    >>> res["key"], res["notkey"]
    ('"foo"', 'bar')

    >>> opts = {'startkey': 'foo', "endkey":"bar"}
    >>> res = encode_view_options(opts)
    >>> res['startkey'], res['endkey']
    ('"foo"', '"bar"')
    """
    retval = {}

    for name, value in options.items():
        if name in ('key', 'startkey', 'endkey'):
            value = json_encoder.encode(value)
        retval[name] = value
    return retval


def force_bytes(data, encoding="utf-8"):
    if isinstance(data, string_type):
        data = data.encode(encoding)
    return data


def force_text(data, encoding="utf-8"):
    if isinstance(data, bytes_type):
        data = data.decode(encoding)
    return data