Files
python-ceilometerclient/ceilometerclient/v2/options.py
Angus Salkeld 987f1ec20a Add resources and meters to the v2 shell
This also moves the build_url function to a common file.

Change-Id: Ia94f9fa37c83fc756a395a918ad254111951f67b
Signed-off-by: Angus Salkeld <asalkeld@redhat.com>
2013-02-27 20:26:56 +11:00

84 lines
2.5 KiB
Python

#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import re
import urllib
def build_url(path, q):
'''
This converts from a list of dict's to what the rest api needs
so from:
"[{field=this,op=le,value=34},{field=that,op=eq,value=foo}]"
to:
"?q.field=this&q.op=le&q.value=34&
q.field=that&q.op=eq&q.value=foo"
'''
if q:
query_params = {'q.field': [],
'q.value': [],
'q.op': []}
for query in q:
for name in ['field', 'op', 'value']:
query_params['q.%s' % name].append(query.get(name, ''))
path += "?" + urllib.urlencode(query_params, doseq=True)
return path
def cli_to_array(cli_query):
'''
This converts from the cli list of queries to what is required
by the python api.
so from:
"this<=34;that=foo"
to
"[{field=this,op=le,value=34},{field=that,op=eq,value=foo}]"
'''
if cli_query is None:
return None
op_lookup = {'!=': 'ne',
'>=': 'ge',
'<=': 'le',
'>': 'gt',
'<': 'lt',
'=': 'eq'}
def split_by_op(string):
# two character split (<=,!=)
fragments = re.findall(r'(\w+)([><!]=)([^ -,\t\n\r\f\v]+)', string)
if len(fragments) == 0:
#single char split (<,=)
fragments = re.findall(r'(\w+)([><=])([^ -,\t\n\r\f\v]+)', string)
return fragments
opts = []
queries = cli_query.split(';')
for q in queries:
frag = split_by_op(q)
if len(frag) > 1:
raise ValueError('incorrect seperator %s in query "%s"' %
('(should be ";")', q))
if len(frag) == 0:
raise ValueError('invalid query %s' % q)
query = frag[0]
opt = {}
opt['field'] = query[0]
opt['op'] = op_lookup[query[1]]
opt['value'] = query[2]
opts.append(opt)
return opts