From 26c4be575a9017b44a26e489db4a21b0324f45f0 Mon Sep 17 00:00:00 2001 From: Boris Date: Fri, 24 Jan 2020 18:04:28 +0300 Subject: [PATCH] added ability to use proxies in Requests --- README.rst | 2 +- python_telegram_logger/handlers.py | 15 +++++++++------ 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/README.rst b/README.rst index 57cea9a..d659ebe 100644 --- a/README.rst +++ b/README.rst @@ -32,7 +32,7 @@ Quick start "class": "python_telegram_logger.Handler", "token": "bot_token", "chat_ids": [123456789, -1234567891011], - + "proxy_url": "https://user:pass@10.10.1.10:3128/" # optional } }, "loggers": { diff --git a/python_telegram_logger/handlers.py b/python_telegram_logger/handlers.py index 4130985..0380fb8 100644 --- a/python_telegram_logger/handlers.py +++ b/python_telegram_logger/handlers.py @@ -22,13 +22,12 @@ class Handler(logging.handlers.QueueHandler): - """ Base handler which instantiate and start queue listener and message dispatcher """ - def __init__(self, token: str, chat_ids: list, format: str=HTML, - disable_notifications: bool=False, disable_preview: bool=False): + def __init__(self, token: str, chat_ids: list, format: str = HTML, + disable_notifications: bool = False, disable_preview: bool = False, proxy_url: str = None): """ :param token: telegram bot API token :param chat_ids: list of intergers with chat ids @@ -44,7 +43,7 @@ def __init__(self, token: str, chat_ids: list, format: str=HTML, except Exception: raise Exception("TelegramLogging. Unknown format '%s'" % format) - self.handler = LogMessageDispatcher(token, chat_ids, disable_notifications, disable_preview) + self.handler = LogMessageDispatcher(token, chat_ids, disable_notifications, disable_preview, proxy_url) self.handler.setFormatter(formatter()) listener = logging.handlers.QueueListener(queue, self.handler) listener.start() @@ -67,7 +66,8 @@ class LogMessageDispatcher(logging.Handler): MAX_MSG_LEN = 4096 API_CALL_INTERVAL = 1 / 30 # 30 calls per second - def __init__(self, token: str, chat_ids: list, disable_notifications: bool=False, disable_preview: bool=False): + def __init__(self, token: str, chat_ids: list, disable_notifications: bool = False, + disable_preview: bool = False, proxy_url: str = None): """ See Handler args """ @@ -76,6 +76,10 @@ def __init__(self, token: str, chat_ids: list, disable_notifications: bool=False self.disable_notifications = disable_notifications self.disable_preview = disable_preview self.session = requests.Session() + + if proxy_url: + self.session.proxies = {'https': proxy_url} + super().__init__() @property @@ -118,7 +122,6 @@ def emit(self, record): disable_web_page_preview=self.disable_preview, disable_notifications=self.disable_notifications ) - response = self.session.get(url, timeout=self.TIMEOUT) if not response.ok: logger.warning("Telegram log dispatching failed with status code '%s'" % response.status_code)