Statistics
| Branch: | Tag: | Revision:

root / kamaki / clients / utils.py @ 4067cdaf

History | View | Annotate | Download (4.2 kB)

1
# Copyright 2011-2012 GRNET S.A. All rights reserved.
2
#
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
#
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
#
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
#
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
#
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

    
34

    
35
def matches(val1, val2, exactMath=True):
36
    """Case Insenstive match"""
37

    
38
    if exactMath:
39
        return True if val1.lower() == val2.lower() else False
40
    else:
41
        return True if val1.lower().startswith(val2.lower()) else False
42

    
43

    
44
def filter_out(d, prefix, exactMatch=False):
45
    """@return a dict that contains the entries of d
46
        that are NOT prefixed with prefic
47
    """
48

    
49
    ret = {}
50
    for key, val in d.items():
51
        if not matches(key, prefix, exactMath=exactMatch):
52
            ret[key] = val
53
    return ret
54

    
55

    
56
def filter_in(d, prefix, exactMatch=False):
57
    """@return a dict that contains only the entries of d
58
        that are prefixed with prefix
59
    """
60

    
61
    ret = {}
62
    for key, val in d.items():
63
        if matches(key, prefix, exactMath=exactMatch):
64
            ret[key] = val
65
    return ret
66

    
67

    
68
def prefix_keys(d, prefix):
69
    """@return a sallow copy of d with all its keys prefixed with prefix
70
    """
71

    
72
    ret = {}
73
    for key, val in d.items():
74
        ret[prefix + key] = val
75
    return ret
76

    
77

    
78
def path4url(*args):
79
    """@return a string with all args in the form /arg1/arg2/...
80
       @param args must be strings
81
    """
82

    
83
    path = ''
84
    for arg in args:
85
        suffix = unicode(arg)
86
        try:
87
            while suffix[0] == '/':
88
                suffix = suffix[1:]
89
        except IndexError:
90
            continue
91
        if len(path) > 0 and path[-1] == '/':
92
            path += suffix
93
        else:
94
            path += '/' + suffix
95
    return path
96

    
97

    
98
def params4url(params):
99
    """@return a string with all params in the form ?key1=val1&key2=val2&...
100
       @param should be a dict.
101
    """
102

    
103
    assert(type(params) is dict)
104
    result = ''
105
    dlmtr = '?'
106
    for name in params:
107
        result = result + dlmtr + name
108
        result += '=%s' % params[name] if params[name] else result
109
        dlmtr = '&'
110
    return result
111

    
112

    
113
def list2str(alist, seperator=','):
114
    """@return a string of comma seperated elements of the list"""
115

    
116
    ret = ''
117
    slist = sorted(alist)
118
    for item in slist:
119
        if 0 == slist.index(item):
120
            ret = unicode(item)
121
        else:
122
            ret += seperator + unicode(item)
123
    return ret
124

    
125

    
126
def dict2file(d, f, depth=0):
127
    for k, v in d.items():
128
        f.write('%s%s: ' % ('\t' * depth, k))
129
        if type(v) is dict:
130
            f.write('\n')
131
            dict2file(v, f, depth + 1)
132
        elif type(v) is list:
133
            f.write('\n')
134
            list2file(v, f, depth + 1)
135
        else:
136
            f.write(' %s\n' % unicode(v))
137

    
138

    
139
def list2file(l, f, depth=1):
140
    for item in l:
141
        if type(item) is dict:
142
            dict2file(item, f, depth + 1)
143
        elif type(item) is list:
144
            list2file(item, f, depth + 1)
145
        else:
146
            f.write('%s%s\n' % ('\t' * depth, unicode(item)))