forked from softlayer/softlayer-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
91 lines (71 loc) · 2.49 KB
/
utils.py
File metadata and controls
91 lines (71 loc) · 2.49 KB
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
"""
SoftLayer.utils
~~~~~~~~~~~~~~~
Utility function/classes
:copyright: (c) 2013, SoftLayer Technologies, Inc. All rights reserved.
:license: BSD, see LICENSE for more details.
"""
KNOWN_OPERATIONS = ['<=', '>=', '<', '>', '~', '*=', '^=', '$=', '_=', '!~']
class NestedDict(dict):
def __getitem__(self, key):
if key in self:
return self.get(key)
return self.setdefault(key, NestedDict())
def to_dict(self):
d = {}
for k, v in self.items():
if isinstance(v, NestedDict):
d[k] = v.to_dict()
else:
d[k] = v
return d
def query_filter(query):
""" Translate a query-style string to a 'filter'. Query can be the
following formats:
Case Insensitive
'value' Exact value match
'value*' Begins with value
'*value' Ends with value
'*value*' Contains value
Case Sensitive
'~ value' Exact value match
'> value' Greater than value
'< value' Less than value
'>= value' Greater than or equal to value
'<= value' Less than or equal to value
:param string query: query string
"""
if isinstance(query, basestring):
query = query.strip()
for op in KNOWN_OPERATIONS:
if query.startswith(op):
query = "%s %s" % (op, query[len(op):].strip())
return {'operation': query}
if query.startswith('*') and query.endswith('*'):
query = "~ %s" % query.strip('*')
elif query.startswith('*'):
query = "$= %s" % query.strip('*')
elif query.endswith('*'):
query = "^= %s" % query.strip('*')
else:
query = "_= %s" % query
return {'operation': query}
class IdentifierMixin:
""" This mixin provides an interface to provide multiple methods for
converting an 'indentifier' to an id """
resolvers = []
def resolve_ids(self, identifier):
""" Takes a string and tries to resolve to a list of matching ids. What
exactly 'identifier' can be depends on the resolvers
:param string identifier: identifying string
"""
# Before doing anything, let's see if this is an integer
try:
return [int(identifier)]
except ValueError:
pass # It was worth a shot
for resolver in self.resolvers:
ids = resolver(identifier)
if ids:
return ids
return []