2 """This module includes utility functions.""" 11 from functools
import wraps
12 from errno
import EACCES, EPERM, ENOENT
14 LOGGER = logging.getLogger(__name__)
18 """Utility function to obtain a ith batch of data from list 21 _list: list to choose batch from 22 batch_index: batch index 23 batch_size: size of batch to select 26 batch (sub list of _list) of size batch_size 28 start = batch_index * batch_size
29 end = min(batch_index * batch_size + batch_size, len(_list))
30 return _list[start:end]
34 """Encode content into using base64 encoding 37 _data (str): input data to encode 42 return base64.b64encode(_data.encode(encoding=
"utf-8"))
46 """Decode base64 encoded content to string 49 _encode : bytes-like object 54 return base64.b64decode(_encode).decode(encoding=
"utf-8")
58 """Utility function to print pretty json string 61 _obj: python dictionary 62 **kwargs: optional keywords arguments 64 pretty: for pretty printing 66 prints formatted json string 69 pretty = kwargs.get(
"pretty",
False)
72 return json.dumps(_obj, indent=4, sort_keys=
True,
73 separators=(
',',
':'))
75 return json.dumps(_obj)
79 """Cleanup list values 82 _values: list of values 85 list of normalized list 87 assert type(_values) == list
90 if hasattr(val,
'strip'):
92 sanitized_values.append(val)
93 return sanitized_values
97 """Sanitize dictionary values 100 records_dict: dictionary values 103 list of stripped, sanitized dictionary 105 for k
in records_dict.keys():
107 if hasattr(v,
'strip'):
114 """Cleanup list values 117 _collection: list of dictionary values 120 list of stripped, sanitized list of dictionary values 122 assert type(_collection) == list
123 if len(_collection) > 0:
124 assert type(_collection[0]) == dict
126 for records_dict
in _collection:
132 """Generate and return MDX new_id hash 136 _key: key to append with _cu 139 SHA1 encoded hexdigest code 141 assert _key
is not None 142 assert type(_key) == str
143 message =
"{}{}".format(_cu, _key)
144 return hashlib.sha1(bytes(message, encoding=
'utf-8')).hexdigest()
148 """Generate and return authentication hash code 155 SHA1 encoded hexdigest code 157 assert _secret_key
is not None 158 assert type(_secret_key) == str
159 message =
"".join([_action, _cu, _secret_key])
160 return hashlib.sha1(bytes(message, encoding=
'utf-8')).hexdigest()
164 """Display error messages for FileNotFound/Permission Denied errors. 167 _e: error message object 168 _file_or_script: script/file that caused error 171 Formatted PermissionError/FileNotFoundError error message 175 if _e.errno == EPERM
or _e.errno == EACCES:
176 error_msg =
"PermissionError - error({}): {} for: {}\t".format(
177 _e.errno, _e.strerror, _file__or_script)
179 elif _e.errno == ENOENT:
180 error_msg =
"FileNotFoundError - error({}): {} as:{}\t".format(
181 _e.errno, _e.strerror, _file__or_script)
187 """decorator to handle all file operation exceptions""" 188 @wraps(original_file_handler)
189 def wrapper(*args, **kwargs):
191 return original_file_handler(*args, **kwargs)
192 except (IOError, NameError)
as e:
194 LOGGER.error(error_msg)
195 raise SystemExit(error_msg)
196 except Exception
as e:
201 error_msg = sys.exc_info()[1].args[0]
202 LOGGER.error(error_msg)
203 raise SystemExit(error_msg)
208 """Get or Pop an element from a dictionary 211 _k: key to get or pop 212 _dict: dictionary to get or pop an element from 214 default: default value to return 215 pop: do we `get` or `pop` from the dict 218 value associated with key in a dictionary 221 ValueError, TypeError if the invalid castto is encountered 223 default = kwargs.get(
"default",
None)
224 pop = kwargs.get(
"pop",
False)
227 val = _dict.pop(_k, default)
229 val = _dict.get(_k, default)
231 if val
in [
None,
'']
and default
not in [
None,
'']:
234 if hasattr(val,
'strip'):
241 """Log progress information to be used in progressbar in Monitor 244 _progress_dict: dictionary that contains completed and total stat 246 LOGGER.info(
"[PROGRESS] Tables imported: {}/{}".format(
247 _progress_dict[
"completed"], _progress_dict[
"total"]))
251 """Simple css parser to convert css attributes to python dict. 254 _content (str): main css content 257 cssdict (dict): parsed python dictionary 259 Alternative advanced css parsing using tinycss 260 **implementation starts** 262 parser = tinycss.make_parser() 263 stylesheet = parser.parse_stylesheet(_content) 265 for rule in stylesheet.rules: 266 this_rule = rule.selector.as_css() 267 cssdict[this_rule] = {} 269 for css_attr in rule.declarations: 271 cssdict[this_rule][css_attr.name] = css_attr.value.as_css() 272 print (css_attr.name, css_attr.value.as_css()) 273 print(stylesheet.errors) 275 **implementation ends** 279 inside_comment_block =
False 282 reading_values =
False 287 running_css_rule =
"" 290 running_css_attrs_dict = {}
293 for line
in _content.splitlines():
299 assert running_css_rule !=
"" 301 cssdict[running_css_rule] = running_css_attrs_dict
303 running_css_rule =
"" 304 running_css_attrs_dict = {}
305 reading_values =
False 310 k_v = line.split(
":", 2)
314 v =
":".join(k_v[1:]).strip()[:-1]
316 running_css_attrs_dict[k] = v
319 if "/* **" in line
and "** */" in line:
323 inside_comment_block =
True 327 inside_comment_block =
False 332 if inside_comment_block
is False:
335 running_css_rule = line.split(
"{")[0].strip()
336 assert running_css_attrs_dict == {}
338 reading_values =
True def log_progress(_progress_dict)
def format_error_permission(_e, _file__or_script)
def get_valid_json(_obj, **kwargs)
def decode_base64(_encode)
def custom_css_parser(_content)
def sanitize_insert_collection(_collection)
def generate_hash(_action, _cu, _secret_key)
def get_ith_batch(_list, batch_index, batch_size)
def get_strip_value_dict(_k, _dict, **kwargs)
def sanitize_dict(records_dict)
def file_exc_decorator(original_file_handler)
def sanitize_insert_values(_values)
def generate_mdx_hash(_cu, _key)