Rename bfxapi.utils to _utils (and update references).

This commit is contained in:
Davide Casale
2023-06-19 05:02:04 +02:00
parent f1e678e043
commit 9edbd7a415
9 changed files with 7 additions and 7 deletions

View File

View File

@@ -0,0 +1,32 @@
import json
from decimal import Decimal
from typing import List, Dict, Union
JSON = Union[Dict[str, "JSON"], List["JSON"], bool, int, float, str, None]
_CustomJSON = Union[Dict[str, "_CustomJSON"], List["_CustomJSON"], \
bool, int, float, str, Decimal, None]
def _strip(dictionary: Dict) -> Dict:
return { key: value for key, value in dictionary.items() if value is not None }
def _convert_data_to_json(data: _CustomJSON) -> JSON:
if isinstance(data, bool):
return int(data)
if isinstance(data, float):
return format(Decimal(repr(data)), "f")
if isinstance(data, Decimal):
return format(data, "f")
if isinstance(data, list):
return [ _convert_data_to_json(sub_data) for sub_data in data ]
if isinstance(data, dict):
return _strip({ key: _convert_data_to_json(value) for key, value in data.items() })
return data
class JSONEncoder(json.JSONEncoder):
def encode(self, o: _CustomJSON) -> str:
return json.JSONEncoder.encode(self, _convert_data_to_json(o))

51
bfxapi/_utils/logger.py Normal file
View File

@@ -0,0 +1,51 @@
import logging, sys
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
COLOR_SEQ, ITALIC_COLOR_SEQ = "\033[1;%dm", "\033[3;%dm"
COLORS = {
"DEBUG": CYAN,
"INFO": BLUE,
"WARNING": YELLOW,
"ERROR": RED
}
RESET_SEQ = "\033[0m"
class _ColorFormatter(logging.Formatter):
def __init__(self, msg, use_color = True):
logging.Formatter.__init__(self, msg, "%d-%m-%Y %H:%M:%S")
self.use_color = use_color
def format(self, record):
levelname = record.levelname
if self.use_color and levelname in COLORS:
record.name = ITALIC_COLOR_SEQ % (30 + BLACK) + record.name + RESET_SEQ
record.levelname = COLOR_SEQ % (30 + COLORS[levelname]) + levelname + RESET_SEQ
return logging.Formatter.format(self, record)
class ColorLogger(logging.Logger):
FORMAT = "[%(name)s] [%(levelname)s] [%(asctime)s] %(message)s"
def __init__(self, name, level):
logging.Logger.__init__(self, name, level)
colored_formatter = _ColorFormatter(self.FORMAT, use_color=True)
handler = logging.StreamHandler(stream=sys.stderr)
handler.setFormatter(fmt=colored_formatter)
self.addHandler(hdlr=handler)
class FileLogger(logging.Logger):
FORMAT = "[%(name)s] [%(levelname)s] [%(asctime)s] %(message)s"
def __init__(self, name, level, filename):
logging.Logger.__init__(self, name, level)
formatter = logging.Formatter(self.FORMAT)
handler = logging.FileHandler(filename=filename)
handler.setFormatter(fmt=formatter)
self.addHandler(hdlr=handler)