Created
July 2, 2021 01:40
-
-
Save thewisenerd/b8a7c724359fe1dac8854196d6be6703 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from azure.cli.core import get_default_cli | |
import json | |
import hashlib | |
import os | |
import codecs | |
import datetime | |
CACHE_DIR = None | |
def __cache_dir(): | |
global CACHE_DIR | |
if CACHE_DIR is not None: | |
return CACHE_DIR | |
cache_dir = os.path.abspath('.') + os.path.sep + 'cache' | |
os.makedirs(cache_dir, exist_ok=True) | |
CACHE_DIR = cache_dir | |
return CACHE_DIR | |
def __az_cli(args): | |
cli = get_default_cli() | |
cli.invoke(args) | |
if cli.result.result: | |
return cli.result.result | |
elif cli.result.error: | |
raise cli.result.error | |
return True | |
def __log_invocation(data): | |
with codecs.open(__cache_dir() + os.path.sep + 'log', 'a', 'ascii') as f: | |
json.dump(data, f) | |
f.write('\n') | |
def az_cli(method, args, use_cache=True): | |
data = {} | |
hash = hashlib.md5(json.dumps(args).encode('utf-8')).hexdigest() | |
now = datetime.datetime.now().isoformat() | |
data['date'] = now | |
data['args'] = args | |
data['hash'] = hash | |
cache_file = None | |
if method == 'GET': | |
cache_file = __cache_dir() + os.path.sep + hash + '.json' | |
has_file = False | |
try: | |
os.stat(cache_file) | |
has_file = True | |
except FileNotFoundError as e: | |
pass | |
if has_file and use_cache: | |
with open(cache_file) as f: | |
ret = json.load(f) | |
output = ret['output'] | |
data['output'] = output | |
data['cached'] = True | |
__log_invocation(data) | |
return output | |
data['pre_flight'] = True | |
__log_invocation(data) | |
del data['pre_flight'] | |
try: | |
output = __az_cli(args) | |
data['output'] = output | |
except Error as e: | |
data['error'] = f'{e}' | |
finally: | |
__log_invocation(data) | |
if cache_file is not None: | |
with open(cache_file, 'w') as f: | |
json.dump(data, f) | |
return output | |
def az_read(args, **kwargs): | |
return az_cli('GET', args, **kwargs) | |
def az_write(args, **kwargs): | |
return az_cli('POST', args, **kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment