Statistics
| Branch: | Tag: | Revision:

root / kamaki / clients / utils.py @ 3dabe5d2

History | View | Annotate | Download (4.5 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
    if exactMath:
38
        return True if val1.lower() == val2.lower() else False
39
    else:
40
        return True if val1.lower().startswith(val2.lower()) else False
41

    
42

    
43
def filter_out(d, prefix, exactMatch=False):
44
    """@return a dict that contains the entries of d
45
        that are NOT prefixed with prefic
46
    """
47
    ret = {}
48
    for key, val in d.items():
49
        if not matches(key, prefix, exactMath=exactMatch):
50
            ret[key] = val
51
    return ret
52

    
53

    
54
def filter_in(d, prefix, exactMatch=False):
55
    """@return a dict that contains only the entries of d
56
        that are prefixed with prefix
57
    """
58
    ret = {}
59
    for key, val in d.items():
60
        if matches(key, prefix, exactMath=exactMatch):
61
            ret[key] = val
62
    return ret
63

    
64

    
65
def prefix_keys(d, prefix):
66
    """@return a sallow copy of d with all its keys prefixed with prefix
67
    """
68
    ret = {}
69
    for key, val in d.items():
70
        ret[prefix + key] = val
71
    return ret
72

    
73

    
74
def path4url(*args):
75
    """@return a string with all args in the form /arg1/arg2/...
76
       @param args must be strings
77
    """
78
    path = ''
79
    for arg in args:
80
        suffix = unicode(arg)
81
        try:
82
            while suffix[0] == '/':
83
                suffix = suffix[1:]
84
        except IndexError:
85
            continue
86
        if len(path) > 0 and path[-1] == '/':
87
            path += suffix
88
        else:
89
            path += '/' + suffix
90
    return path
91

    
92

    
93
def params4url(params):
94
    """@return a string with all params in the form ?key1=val1&key2=val2&...
95
            e.g. input
96
                {'key1':'val1', 'key2':None, 'key3':'val3'}
97
            will return
98
                ?key1=val1&key2&key3=val3
99
       @param should be a dict.
100
            Use params['somekey']=None for params that will apear without
101
            a value at the final string
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
    ret = ''
116
    slist = sorted(alist)
117
    for item in slist:
118
        if 0 == slist.index(item):
119
            ret = unicode(item)
120
        else:
121
            ret += seperator + unicode(item)
122
    return ret
123

    
124

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

    
137

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