def response(httpcode, matsukicode, msg = None, data = None): res = {} # convert enum to int res['http'] = int(httpcode) res['code'] = int(matsukicode) # convert msg if necessary if msg is not None: if isinstance(msg, bytes): res['feedback'] = Convert.binary_to_string(msg) elif isinstance(msg, list): res['feedback'] = Convert.list_to_string(msg) elif isinstance(msg, dict): res['feedback'] = Convert.dict_to_string(msg) else: res['feedback'] = str(msg) # convert data if necessary if data is not None: if isinstance(data, bytes): res['data'] = Convert.binary_to_string(data) elif isinstance(data, list): res['data'] = Convert.list_to_string(data) elif isinstance(data, dict): res['data'] = Convert.dict_to_string(data) else: res['data'] = str(data) # return to caller return res
def _compute_base64(data: bytes): import base64 # To be extra safe in python 3, encode text conditionally before concatenating with pad. if isinstance(data, str): data = data.encode('utf-8') if not isinstance(data, bytes): raise InvalidParamException( "The parameter is neither a string nor byte array type") r = base64.b64encode(data) return Convert.binary_to_string(r)
def encode(self, data: object): """ convert given data into redis token Args: * [data(any)] data can be anything, bytes, int, float or whatever Returns: * [token(bytes)] composed token consisted of data, type, timestamp """ # reset self.reset() if data is None: raise excepts.NullPointerException("data cannot be a null type") # 1. create timestamp self.timestamp = ticker.time_since1970() # 2. assign bytes to self.data if type(data) is bytes: self.dtype = "bytes" self.data = convert.binary_to_string(base64.b64encode(data)) else: # other types self.data = data if type(data) is int: self.dtype = "int" elif type(data) is float: self.dtype = "float" elif type(data) is str: self.dtype = "str" elif type(data) is list: self.dtype = "list" elif type(data) is dict: self.dtype = "dict" else: raise excepts.InvalidParamException( "{} cannot be processed into string nor bytes".format( type(data))) # 3. composing a token dictionary type self.token = { "data": self.data, "type": self.dtype, "timestamp": self.timestamp } # return to caller return convert.dict_to_binary(self.token)
def load_json_file(filename: str): """ Create a blank file or load data from json file @Args: * [filename] (str), filename with path @Returns: *[dict] if load success. None, failed, empty data """ # load json file from given filename raw = fileutil.read_file(filename) if raw: return decode_json(convert.binary_to_string(raw)) else: return {}
def read_file_by_line(file_path: str): """ Read the data line by line of a given file """ # read whole file content data = read_file(file_path) if data is not None and len(data) > 0: str_context = Convert.binary_to_string(data) lines = str_context.split('\n') for line in lines: yield line else: yield ''