From 99de5d26c0c61184edcf427739d5021916d58c37 Mon Sep 17 00:00:00 2001 From: Konrad Date: Fri, 27 Sep 2019 18:48:01 +0200 Subject: [PATCH] made it possible to en-/decode enum values to/from json --- HSMensaW_botA.py | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/HSMensaW_botA.py b/HSMensaW_botA.py index bd369fc..4e2c45d 100644 --- a/HSMensaW_botA.py +++ b/HSMensaW_botA.py @@ -58,6 +58,13 @@ datum = None botID = -1 +class EnumEncode(json.JSONEncoder): + def default(self, obj): + if type(obj) is Language: + return {"Language": str(obj.name)} + return json.JSONEncoder.default(self, obj) + + class HSMensaW(telepot.aio.helper.ChatHandler): keyboard = InlineKeyboardMarkup(inline_keyboard=[ [InlineKeyboardButton(text="Deutsch", callback_data=Language.GERMAN.value)], @@ -228,7 +235,7 @@ async def send_message(bot_obj: DelegatorBot, chat_id: int, msg: str, parse_mode def write_config() -> None: with open(config_filename, 'w') as outfile: - json.dump(config, outfile) + json.dump(config, outfile, cls=EnumEncode) async def get_essen(only_today: bool) -> None: @@ -360,6 +367,14 @@ def get_now() -> str: return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") +def as_enum(d): + if "Language" in d: + lang = d["Language"] + return getattr(Language, lang) + else: + return d + + sys.stdout = open("out.log", "a") sys.stderr = open("err.log", "a") message_log = open("msg.log", "a") @@ -372,7 +387,7 @@ translator = Translator() try: with open(config_filename, 'r') as config_file: - config = json.load(config_file) + config = json.load(config_file, object_hook=as_enum) except FileNotFoundError as e: print('Error: config file "{}" not found: {}'.format(config_filename, e)) sys.exit(-1)