Uh oh!
There was an error while loading. Please reload this page.
forked from nhumrich/gdapi-python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgdapi.py
More file actions
Latest commit
executable file
·861 lines (686 loc) · 27 KB
/
Copy pathgdapi.py
File metadata and controls
executable file
·861 lines (686 loc) · 27 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
#!/usr/bin/env python
# PYTHON_ARGCOMPLETE_OK
from __future__ importprint_function
importsix
importre
importrequests
importcollections
importhashlib
importos
importjson
importtime
try:
importargcomplete
exceptImportError:
pass
def_prefix(cmd):
prefix=os.path.basename(cmd.replace('-', '_'))
foriin ['.pyc', '.py', '-cli', '-tool', '-util']:
prefix=prefix.replace(i, '')
returnprefix.upper()
PREFIX=_prefix(__file__)
CACHE_DIR='~/.'+PREFIX.lower()
TIME=notos.environ.get('TIME_API') isNone
LIST='list-'
CREATE='create-'
UPDATE='update-'
DELETE='delete-'
ACTION='action-'
TRIM=True
JSON=False
GET_METHOD='GET'
POST_METHOD='POST'
PUT_METHOD='PUT'
DELETE_METHOD='DELETE'
HEADERS= {'Accept': 'application/json'}
LIST_METHODS= {'__iter__': True, '__len__': True, '__getitem__': True}
defecho(fn):
defwrapped(*args, **kw):
ret=fn(*args, **kw)
print(fn.__name__, repr(ret))
returnret
returnwrapped
deftimed_url(fn):
defwrapped(*args, **kw):
ifTIME:
start=time.time()
ret=fn(*args, **kw)
delta=time.time() -start
print(delta, args[1], fn.__name__)
returnret
else:
returnfn(*args, **kw)
returnwrapped
classRestObject:
def__init__(self):
pass
@staticmethod
def_is_public(k, v):
returnknotin ['links', 'actions', 'id', 'type'] andnotcallable(v)
def__str__(self):
returnself.__repr__()
def_as_table(self):
ifnothasattr(self, 'type'):
returnstr(self.__dict__)
data= [('Type', 'Id', 'Name', 'Value')]
fork, vinsix.iteritems(self):
ifself._is_public(k, v):
ifvisNone:
v='null'
ifvisTrue:
v='true'
ifvisFalse:
v='false'
v=str(v)
ifTRIMandlen(v) >70:
v=v[0:70] +'...'
data.append((self.type, self.id, str(k), v))
returnindent(data, hasHeader=True, prefix='| ', postfix=' |',
wrapfunc=lambdax: str(x))
def_is_list(self):
return'data'inself.__dict__andisinstance(self.data, list)
def__repr__(self):
data= {}
fork, vinsix.iteritems(self.__dict__):
ifself._is_public(k, v):
data[k] =v
returnrepr(data)
def__getattr__(self, k):
ifself._is_list() andkinLIST_METHODS:
returngetattr(self.data, k)
returngetattr(self.__dict__, k)
def__iter__(self):
ifself._is_list():
returniter(self.data)
classSchema(object):
def__init__(self, text, obj):
self.text=text
self.types= {}
fortinobj:
ift.type!='schema':
continue
self.types[t.id] =t
t.creatable=False
try:
ifPOST_METHODint.collectionMethods:
t.creatable=True
except:
pass
t.updatable=False
try:
ifPUT_METHODint.resourceMethods:
t.updatable=True
except:
pass
t.deletable=False
try:
ifDELETE_METHODint.resourceMethods:
t.deletable=True
except:
pass
t.listable=False
try:
ifGET_METHODint.collectionMethods:
t.listable=True
except:
pass
ifnothasattr(t, 'collectionFilters'):
t.collectionFilters= {}
def__str__(self):
returnstr(self.text)
def__repr(self):
returnrepr(self.text)
classApiError(Exception):
def__init__(self, obj):
self.error=obj
try:
msg='{} : {}\n{}'.format(obj.code, obj.message, obj)
super(ApiError, self).__init__(self, msg)
except:
super(ApiError, self).__init__(self, 'API Error')
classClientApiError(Exception):
pass
classClient(object):
def__init__(self, access_key=None, secret_key=None, url=None, cache=False,
cache_time=86400, strict=False, headers=HEADERS, **kw):
self._headers=headers
self._access_key=access_key
self._secret_key=secret_key
self._auth= (self._access_key, self._secret_key)
self._url=url
self._cache=cache
self._cache_time=cache_time
self._strict=strict
self.schema=None
self._session=requests.Session()
ifnotself._cache_time:
self._cache_time=60*60*24# 24 Hours
self._load_schemas()
defvalid(self):
returnself._urlisnotNoneandself.schemaisnotNone
defobject_hook(self, obj):
ifisinstance(obj, list):
return [self.object_hook(x) forxinobj]
ifisinstance(obj, dict):
result=RestObject()
fork, vinsix.iteritems(obj):
setattr(result, k, self.object_hook(v))
forlinkin ['next', 'prev']:
try:
url=getattr(result.pagination, link)
ifurlisnotNone:
setattr(result, link, lambdaurl=url: self._get(url))
exceptAttributeError:
pass
ifhasattr(result, 'type') andisinstance(getattr(result, 'type'),
six.string_types):
ifhasattr(result, 'links'):
forlink_name, linkinsix.iteritems(result.links):
cb=lambda_link=link, **kw: self._get(_link,
data=kw)
ifhasattr(result, link_name):
setattr(result, link_name+'_link', cb)
else:
setattr(result, link_name, cb)
ifhasattr(result, 'actions'):
forlink_name, linkinsix.iteritems(result.actions):
cb=lambda_link_name=link_name, _result=result, \
*args, **kw: self.action(_result, _link_name,
*args, **kw)
ifhasattr(result, link_name):
setattr(result, link_name+'_action', cb)
else:
setattr(result, link_name, cb)
returnresult
returnobj
defobject_pairs_hook(self, pairs):
ret=collections.OrderedDict()
fork, vinpairs:
ret[k] =v
returnself.object_hook(ret)
def_get(self, url, data=None):
returnself._unmarshall(self._get_raw(url, data=data))
def_error(self, text):
raiseApiError(self._unmarshall(text))
@timed_url
def_get_raw(self, url, data=None):
r=self._get_response(url, data)
returnr.text
def_get_response(self, url, data=None):
r=self._session.get(url, auth=self._auth, params=data,
headers=self._headers)
ifr.status_code<200orr.status_code>=300:
self._error(r.text)
returnr
@timed_url
def_post(self, url, data=None):
r=self._session.post(url, auth=self._auth, data=self._marshall(data),
headers=self._headers)
ifr.status_code<200orr.status_code>=300:
self._error(r.text)
returnself._unmarshall(r.text)
@timed_url
def_put(self, url, data=None):
r=self._session.put(url, auth=self._auth, data=self._marshall(data),
headers=self._headers)
ifr.status_code<200orr.status_code>=300:
self._error(r.text)
returnself._unmarshall(r.text)
@timed_url
def_delete(self, url):
r=self._session.delete(url, auth=self._auth, headers=self._headers)
ifr.status_code<200orr.status_code>=300:
self._error(r.text)
returnself._unmarshall(r.text)
def_unmarshall(self, text):
iftextisNoneortext=='':
returntext
obj=json.loads(text, object_hook=self.object_hook,
object_pairs_hook=self.object_pairs_hook)
returnobj
def_marshall(self, obj, indent=None, sort_keys=False):
ifobjisNone:
returnNone
returnjson.dumps(self._to_dict(obj), indent=indent, sort_keys=True)
def_load_schemas(self, force=False):
ifself.schemaandnotforce:
return
schema_text=self._get_cached_schema()
ifforceornotschema_text:
response=self._get_response(self._url)
schema_url=response.headers.get('X-API-Schemas')
ifschema_urlisnotNoneandself._url!=schema_url:
schema_text=self._get_raw(schema_url)
else:
schema_text=response.text
self._cache_schema(schema_text)
obj=self._unmarshall(schema_text)
schema=Schema(schema_text, obj)
iflen(schema.types) >0:
self._bind_methods(schema)
self.schema=schema
defreload_schema(self):
self._load_schemas(force=True)
defby_id(self, type, id, **kw):
id=str(id)
url=self.schema.types[type].links.collection
ifurl.endswith('/'):
url+=id
else:
url='/'.join([url, id])
try:
returnself._get(url, self._to_dict(**kw))
exceptApiErrorase:
ife.error.status==404:
returnNone
else:
raisee
defupdate_by_id(self, type, id, *args, **kw):
url=self.schema.types[type].links.collection
ifurl.endswith('/'):
url=url+id
else:
url='/'.join([url, id])
returnself._put(url, data=self._to_dict(*args, **kw))
defupdate(self, obj, *args, **kw):
url=obj.links.self
returnself._put(url, data=self._to_dict(*args, **kw))
def_validate_list(self, type, **kw):
ifnotself._strict:
return
collection_filters=self.schema.types[type].collectionFilters
forkinkw:
ifhasattr(collection_filters, k):
return
forfilter_name, filter_valueinsix.iteritems(collection_filters):
forminfilter_value.modifiers:
ifk=='_'.join([filter_name, m]):
return
raiseClientApiError(k+' is not searchable field')
deflist(self, type, **kw):
iftypenotinself.schema.types:
raiseClientApiError(type+' is not a valid type')
self._validate_list(type, **kw)
collection_url=self.schema.types[type].links.collection
returnself._get(collection_url, data=self._to_dict(**kw))
defreload(self, obj):
returnself.by_id(obj.type, obj.id)
defcreate(self, type, *args, **kw):
collection_url=self.schema.types[type].links.collection
returnself._post(collection_url, data=self._to_dict(*args, **kw))
defdelete(self, *args):
foriinargs:
ifisinstance(i, RestObject):
returnself._delete(i.links.self)
defaction(self, obj, action_name, *args, **kw):
url=getattr(obj.actions, action_name)
returnself._post(url, data=self._to_dict(*args, **kw))
def_is_list(self, obj):
ifisinstance(obj, list):
returnTrue
ifisinstance(obj, RestObject) and'type'inobj.__dict__and \
obj.type=='collection':
returnTrue
returnFalse
def_to_value(self, value):
ifisinstance(value, dict):
ret= {}
fork, vinsix.iteritems(value):
ret[k] =self._to_value(v)
returnret
ifisinstance(value, list):
ret= []
forvinvalue:
ret.append(self._to_value(v))
returnret
ifisinstance(value, RestObject):
ret= {}
fork, vinvars(value).iteritems():
ifnotk.startswith('_') and \
notisinstance(v, RestObject) andnotcallable(v):
ret[k] =self._to_value(v)
elifnotk.startswith('_') andisinstance(v, RestObject):
ret[k] =self._to_dict(v)
returnret
returnvalue
def_to_dict(self, *args, **kw):
iflen(kw) ==0andlen(args) ==1andself._is_list(args[0]):
ret= []
foriinargs[0]:
ret.append(self._to_dict(i))
returnret
ret= {}
foriinargs:
value=self._to_value(i)
ifisinstance(value, dict):
fork, vinsix.iteritems(value):
ret[k] =v
fork, vinsix.iteritems(kw):
ret[k] =self._to_value(v)
returnret
@staticmethod
def_type_name_variants(name):
ret= [name]
python_name=re.sub(r'([a-z])([A-Z])', r'\1_\2', name)
ifpython_name!=name:
ret.append(python_name.lower())
returnret
def_bind_methods(self, schema):
bindings= [
('list', 'collectionMethods', GET_METHOD, self.list),
('by_id', 'collectionMethods', GET_METHOD, self.by_id),
('update_by_id', 'resourceMethods', PUT_METHOD, self.update_by_id),
('create', 'collectionMethods', POST_METHOD, self.create)
]
fortype_name, typinsix.iteritems(schema.types):
forname_variantinself._type_name_variants(type_name):
formethod_name, type_collection, test_method, minbindings:
# double lambda for lexical binding hack, I'm sure there's
# a better way to do this
cb=lambdatype_name=type_name, method=m: \
lambda*args, **kw: method(type_name, *args, **kw)
iftest_methodingetattr(typ, type_collection, []):
setattr(self, '_'.join([method_name, name_variant]),
cb())
def_get_schema_hash(self):
h=hashlib.new('sha1')
h.update(self._url)
ifself._access_keyisnotNone:
h.update(self._access_key)
returnh.hexdigest()
def_get_cached_schema_file_name(self):
ifnotself._cache:
returnNone
h=self._get_schema_hash()
cachedir=os.path.expanduser(CACHE_DIR)
ifnotcachedir:
returnNone
ifnotos.path.exists(cachedir):
os.mkdir(cachedir)
returnos.path.join(cachedir, 'schema-'+h+'.json')
def_cache_schema(self, text):
cached_schema=self._get_cached_schema_file_name()
ifnotcached_schema:
returnNone
withopen(cached_schema, 'w') asf:
f.write(text)
def_get_cached_schema(self):
ifnotself._cache:
returnNone
cached_schema=self._get_cached_schema_file_name()
ifnotcached_schema:
returnNone
ifos.path.exists(cached_schema):
mod_time=os.path.getmtime(cached_schema)
iftime.time() -mod_time<self._cache_time:
withopen(cached_schema) asf:
data=f.read()
returndata
returnNone
def_print_cli(client, obj):
ifobjisNone:
return
ifJSON:
print(client._marshall(obj, indent=2, sort_keys=True))
elifcallable(getattr(obj, '_as_table')):
print(obj._as_table())
else:
print(obj)
# {{{ http://code.activestate.com/recipes/267662/ (r7)
try:
fromcStringIOimportStringIO
exceptImportError:
fromioimportStringIO
importoperator
defindent(rows, hasHeader=False, headerChar='-', delim=' | ', justify='left',
separateRows=False, prefix='', postfix='', wrapfunc=lambdax: x):
'''Indents a table by column.
- rows: A sequence of sequences of items, one sequence per row.
- hasHeader: True if the first row consists of the columns' names.
- headerChar: Character to be used for the row separator line
(if hasHeader==True or separateRows==True).
- delim: The column delimiter.
- justify: Determines how are data justified in their column.
Valid values are 'left','right' and 'center'.
- separateRows: True if rows are to be separated by a line
of 'headerChar's.
- prefix: A string prepended to each printed row.
- postfix: A string appended to each printed row.
- wrapfunc: A function f(text) for wrapping text; each element in
the table is first wrapped by this function.'''
# closure for breaking logical rows to physical, using wrapfunc
defrowWrapper(row):
newRows= [wrapfunc(item).split('\n') foriteminrow]
return [[substror''forsubstrinitem] foriteminmap(None, *newRows)] # NOQA
# break each logical row into one or more physical ones
logicalRows= [rowWrapper(row) forrowinrows]
# columns of physical rows
columns=map(None, *reduce(operator.add, logicalRows))
# get the maximum of each column by the string length of its items
maxWidths= [max([len(str(item)) foritemincolumn])
forcolumnincolumns]
rowSeparator=headerChar* (len(prefix) +len(postfix) +
sum(maxWidths) +
len(delim)*(len(maxWidths)-1))
# select the appropriate justify method
justify= {'center': str.center, 'right': str.rjust, 'left': str.ljust}[justify.lower()] # NOQA
output=StringIO()
ifseparateRows:
print(rowSeparator, file=output)
forphysicalRowsinlogicalRows:
forrowinphysicalRows:
print(prefix
+delim.join([justify(str(item), width) for (item, width) inzip(row, maxWidths)]) +postfix, # NOQA
file=output)
ifseparateRowsorhasHeader:
print(rowSeparator, file=output)
hasHeader=False
returnoutput.getvalue()
# End {{{ http://code.activestate.com/recipes/267662/ (r7)
def_env_prefix(cmd):
return_prefix(cmd) +'_'
deffrom_env(prefix=PREFIX+'_', factory=Client, **kw):
args=dict((x, None) forxin ['access_key', 'secret_key', 'url', 'cache',
'cache_time', 'strict'])
args.update(kw)
ifnotprefix.endswith('_'):
prefix+='_'
prefix=prefix.upper()
return_from_env(prefix=prefix, factory=factory, **args)
def_from_env(prefix=PREFIX+'_', factory=Client, **kw):
result=dict(kw)
fork, vinsix.iteritems(kw):
ifvisnotNone:
result[k] =v
else:
result[k] =os.environ.get(prefix+k.upper())
ifresult[k] isNone:
delresult[k]
if'cache_time'inresult:
result['cache_time'] =int(result['cache_time'])
if'cache'inresult:
result['cache'] =result['cache'] isTrueorresult['cache'] =='true'
returnfactory(**result)
def_general_args(help=True):
importargparse
parser=argparse.ArgumentParser(add_help=help)
parser.add_argument('--access-key', dest='_access_key')
parser.add_argument('--secret-key', dest='_secret_key')
parser.add_argument('--url', dest='_url')
parser.add_argument('--format', dest='_format', default='table',
choices=['table', 'json'])
parser.add_argument('--cache', dest='_cache', action='store_true',
default=True)
parser.add_argument('--no-cache', dest='_cache', action='store_false')
parser.add_argument('--cache-time', dest='_cache_time', type=int)
parser.add_argument('--strict', dest='_strict', type=bool)
parser.add_argument('--trim', dest='_trim', action='store_true',
default=True)
parser.add_argument('--no-trim', dest='_trim', action='store_false')
returnparser
def_list_args(subparsers, client, type, schema):
help_msg=LIST[0:len(LIST)-1].capitalize() +' '+type
subparser=subparsers.add_parser(LIST+type, help=help_msg)
forname, filterinsix.iteritems(schema.collectionFilters):
subparser.add_argument('--'+name)
forminfilter.modifiers:
ifm!='eq':
subparser.add_argument('--'+name+'_'+m)
returnsubparser
def_map_load(value):
value=value.strip()
iflen(value) ==0:
returnvalue
ifvalue[0] =='{':
returnjson.loads(value)
else:
ret= {}
fork, vin [x.strip().split('=', 1) forxinvalue.split(',')]:
ret[k] =v
returnret
def_generic_args(subparsers, field_key, type, schema,
operation=None, operation_name=None, help=None):
ifoperationisNone:
prefix=operation_name
help_msg=help
else:
prefix=operation+type
help_msg_prefix=operation[0:len(operation)-1].capitalize()
help_msg=help_msg_prefix+' '+type+' resource'
subparser=subparsers.add_parser(prefix, help=help_msg)
ifschemaisnotNone:
forname, fieldinsix.iteritems(schema):
iffield.get(field_key) isTrue:
iffield.get('type').startswith('array'):
subparser.add_argument('--'+name, nargs='*')
eliffield.get('type').startswith('map'):
subparser.add_argument('--'+name, type=_map_load)
else:
subparser.add_argument('--'+name)
returnsubparser
def_full_args(client):
parser=_general_args()
subparsers=parser.add_subparsers(help='Sub-Command Help')
fortype, schemainsix.iteritems(client.schema.types):
ifschema.listable:
subparser=_list_args(subparsers, client, type, schema)
subparser.set_defaults(_action=LIST, _type=type)
ifschema.creatable:
subparser=_generic_args(subparsers, 'create', type,
schema.resourceFields, operation=CREATE)
subparser.set_defaults(_action=CREATE, _type=type)
ifschema.updatable:
subparser=_generic_args(subparsers, 'update', type,
schema.resourceFields, operation=UPDATE)
subparser.add_argument('--id')
subparser.set_defaults(_action=UPDATE, _type=type)
ifschema.deletable:
subparser=_generic_args(subparsers, 'delete', type,
{}, operation=DELETE)
subparser.add_argument('--id')
subparser.set_defaults(_action=DELETE, _type=type)
try:
forname, argsinsix.iteritems(schema.resourceActions):
action_schema=None
try:
action_schema=client.schema.types[args.input]
except (KeyError, AttributeError):
pass
help_msg='Action '+name+' on '+type
resource_fields=None
ifaction_schemaisnotNone:
resource_fields=action_schema.resourceFields
subparser=_generic_args(subparsers, 'create', type,
resource_fields,
operation_name=type+'-'+name,
help=help_msg)
subparser.add_argument('--id')
subparser.set_defaults(_action=ACTION+name, _type=type)
except (KeyError, AttributeError):
pass
if'argcomplete'inglobals():
argcomplete.autocomplete(parser)
returnparser
def_run_cli(client, namespace):
args, command_type, type_name=_extract(namespace, '_action', '_type')
args=_remove_none(args)
try:
ifcommand_type==LIST:
if'id'inargs:
_print_cli(client, client.by_id(type_name, args['id']))
else:
result=client.list(type_name, **args)
ifJSON:
_print_cli(client, result)
else:
foriinresult:
_print_cli(client, i)
ifcommand_type==CREATE:
_print_cli(client, client.create(type_name, **args))
ifcommand_type==DELETE:
obj=client.by_id(type_name, args['id'])
ifobjisNone:
raiseClientApiError('{0} Not Found'.format(args['id']))
client.delete(obj)
_print_cli(client, obj)
ifcommand_type==UPDATE:
_print_cli(client,
client.update_by_id(type_name, args['id'], args))
ifcommand_type.startswith(ACTION):
obj=client.by_id(type_name, args['id'])
ifobjisNone:
raiseClientApiError('{0} Not Found'.format(args['id']))
obj=client.action(obj, command_type[len(ACTION):], **args)
ifobj:
_print_cli(client, obj)
exceptApiErrorase:
importsys
sys.stderr.write('Error : {}\n'.format(e.error))
status=int(e.error.status) -400
ifstatus>0andstatus<255:
sys.exit(status)
else:
sys.exit(1)
def_remove_none(args):
returndict(filter(lambdax: x[1] isnotNone, args.items()))
def_extract(namespace, *args):
values=vars(namespace)
result= [values]
forarginargs:
value=values.get(arg)
result.append(value)
try:
delvalues[arg]
exceptKeyError:
pass
returntuple(result)
def_get_generic_vars(argv):
ret= []
forarginargv:
ifre.match(r'[a-zA-Z]+-[a-zA-Z]', arg):
break
ret.append(arg)
returnret
def_cli_client(argv):
generic_argv=_get_generic_vars(argv)
args, unknown=_general_args(help=False).parse_known_args(generic_argv)
globalTRIM
TRIM=args._trim
globalJSON
ifargs._format=='json':
JSON=True
dict_args= {}
fork, vinvars(args).items():
dict_args[k[1:]] =v
prefix=_env_prefix(argv[0])
return_from_env(prefix, **dict_args)
def_main():
importsys
client=_cli_client(sys.argv)
ifnotclient.valid():
_general_args().print_help()
sys.exit(2)
args=_full_args(client).parse_args()
_run_cli(client, args)
if__name__=='__main__':
_main()