Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""LICENSE
2Copyright 2020 Hermann Krumrey <hermann@krumreyh.com>
4This file is part of jerrycan.
6jerrycan is free software: you can redistribute it and/or modify
7it under the terms of the GNU General Public License as published by
8the Free Software Foundation, either version 3 of the License, or
9(at your option) any later version.
11jerrycan is distributed in the hope that it will be useful,
12but WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14GNU General Public License for more details.
16You should have received a copy of the GNU General Public License
17along with jerrycan. If not, see <http://www.gnu.org/licenses/>.
18LICENSE"""
20import sys
21import time
22import logging
23import sentry_sdk
24import traceback
25from threading import Thread
26# noinspection PyPackageRequirements
27from telegram.error import TimedOut
28from typing import Callable, Tuple, Dict, Type
29from cheroot.wsgi import Server, PathInfoDispatcher
30from jerrycan.background.telegram import telegram_whoami
31from jerrycan.base import app
32from jerrycan.Config import Config
35def __start_background_tasks(
36 task_definitions: Dict[str, Tuple[int, Callable]]
37):
38 """
39 Starts background tasks for a flask application
40 :param task_definitions: The background tasks, consisting of:
41 - the name of the task
42 - the time to wait before running
43 the task again
44 - a function that takes no arguments that
45 executes the task
46 :return: None
47 """
48 def task_factory(_name: str, _delay: int, _function: Callable) -> Thread:
49 def run_task():
50 while True:
51 try:
52 with app.app_context():
53 _function()
54 except Exception as error:
55 app.logger.error(f"Encountered exception in "
56 f"background task {_name}: {error}\n"
57 f"{traceback.format_exc()}")
58 sentry_sdk.capture_exception(error)
59 time.sleep(_delay)
60 return Thread(target=run_task)
62 tasks = []
63 for name, (delay, function) in task_definitions.items():
64 tasks.append(task_factory(name, delay, function))
66 for thread in tasks:
67 thread.start()
70def start_server(
71 config: Type[Config],
72 task_definitions: Dict[str, Tuple[int, Callable]]
73):
74 """
75 Starts the flask application using a cheroot WSGI server
76 :param config: The configuration to use
77 :param task_definitions: The background tasks, consisting of:
78 - the name of the task
79 - the time to wait before running
80 the task again
81 - a function that takes no arguments that
82 executes the task
83 :return: None
84 """
85 if not config.TELEGRAM_API_KEY == "" \
86 and not config.TESTING \
87 and config.TELEGRAM_WHOAMI: # pragma: no cover
88 try:
89 config.initialize_telegram()
90 Config.TELEGRAM_BOT_CONNECTION.bot.logger.setLevel(logging.WARNING)
91 except TimedOut:
92 print("Could not initialize telegram")
93 sys.exit(1)
94 task_definitions.update({
95 "telegram_bg": (30, telegram_whoami)
96 })
97 __start_background_tasks(task_definitions)
99 app.logger.info("STARTING FLASK")
100 server = Server(
101 ("0.0.0.0", config.HTTP_PORT),
102 PathInfoDispatcher({"/": app})
103 )
105 try:
106 server.start()
107 except KeyboardInterrupt:
108 server.stop()