Statistics
| Branch: | Tag: | Revision:

root / kamaki / clients / utils.py @ b335416e

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
def matches(val1, val2, exactMath=True):
35
    """Case Insenstive match"""
36
    if exactMath:
37
        return True if val1.lower() == val2.lower() else False
38
    else:
39
        return True if val1.lower().startswith(val2.lower()) else False
40

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

    
50
def filter_in(d, prefix, exactMatch = False):
51
    """@return a dict that contains only the entries of d that are prefixed with prefix
52
    """
53
    ret = {}
54
    for key, val in d.items():
55
        if matches(key, prefix, exactMath = exactMatch):
56
            ret[key] = val
57
    return ret
58
    
59
def prefix_keys(d, prefix):
60
    """@return a sallow copy of d with all its keys prefixed with prefix
61
    """
62
    ret = {}
63
    for key, val in d.items():
64
        ret[prefix+key] = val
65
    return ret
66

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

    
85
def params4url(params):
86
    """@return a string with all params in the form ?key1=val1&key2=val2&...
87
            e.g. input
88
                {'key1':'val1', 'key2':None, 'key3':'val3'}
89
            will return
90
                ?key1=val1&key2&key3=val3
91
       @param should be a dict.
92
            Use params['somekey']=None for params that will apear without 
93
            a value at the final string
94
    """
95
    assert(type(params) is dict)
96
    result = ''
97
    dlmtr = '?'
98
    for name in params:
99
        result = result + dlmtr + name
100
        result = result + '=' + unicode(params[name]) if params[name] is not None else result
101
        dlmtr = '&'
102
    return result
103

    
104
def list2str(alist, seperator=','):
105
    """@return a string of comma seperated elements of the list"""
106
    ret = ''
107
    slist = sorted(alist)
108
    for item in slist:
109
        if 0 == slist.index(item):
110
            ret = unicode(item)
111
        else:
112
            ret += seperator+unicode(item)
113
    return ret
114

    
115
def dict2file(d, f, depth = 0):
116
    for k, v in d.items():
117
        f.write('%s%s: '%('\t'*depth, k))
118
        if type(v) is dict:
119
            f.write('\n')
120
            dict2file(v, f, depth+1)
121
        elif type(v) is list:
122
            f.write('\n')
123
            list2file(v, f, depth+1)
124
        else:
125
            f.write(' %s\n'%unicode(v))
126

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