@@ -37,6 +37,7 @@ def check_api_available() -> bool:
37
37
return requests .get (f"{ NEWS_DB_API_URL } /healthcheck" ).ok
38
38
except (ConnectionError , ConnectionRefusedError ) as con_err :
39
39
logging .error (con_err )
40
+ return False
40
41
41
42
42
43
def send_news_to_telegram (message ):
@@ -73,23 +74,47 @@ def send_news_to_telegram(message):
73
74
logging .error (err )
74
75
75
76
77
+ def ask_entities () -> int :
78
+ """
79
+ Ask API request to discover how much entities in db
80
+ Return int instead of str
81
+ :return:
82
+ """
83
+ return int (requests .get (f"{ NEWS_DB_API_URL } /entities" ).text )
84
+
85
+
76
86
if __name__ == "__main__" :
77
87
while True :
78
88
if check_api_available ():
79
- time .sleep (1 )
80
89
current_time = datetime .now ().strftime ("%H:%M" )
81
90
if TIME_TO_SEND_START < current_time < TIME_TO_SEND_END :
82
91
logging .info ("Time to send news has come !" )
83
- data_from_db = requests . get ( NEWS_DB_API_URL ). json ()
84
- if len ( data_from_db ) == 0 :
85
- logging . warning ( "Database is empty !" )
92
+ if ask_entities () == 0 :
93
+ logging . warning ( "Database is empty ! Take a break for 30 min." )
94
+ time . sleep ( 1800 )
86
95
else :
87
- for news in data_from_db :
88
- send_news_to_telegram (news )
89
- time .sleep (SENDING_INTERVAL )
90
- else :
91
- logging .warning ("All news was sent !" )
96
+ try :
97
+ data_from_db = requests .get (f"{ NEWS_DB_API_URL } /news" ).json ()
98
+ for news in data_from_db :
99
+ send_news_to_telegram (news )
100
+ time .sleep (SENDING_INTERVAL )
101
+ else :
102
+ logging .warning (
103
+ f"All news was sent ! Going to purge ! Entities in db for now { ask_entities ()} ."
104
+ )
105
+ try :
106
+ response = requests .get (f"{ NEWS_DB_API_URL } /purge" )
107
+ except Exception as exception :
108
+ logging .error (f"Exception while purging: { exception } ." )
109
+ else :
110
+ logging .info (
111
+ f"Database was purged successfully ! Entities in db for now { ask_entities ()} ."
112
+ )
113
+ except Exception as exception :
114
+ logging .error (f"Exception while getting news: { exception } " )
92
115
else :
93
116
logging .info ("Still waiting to send." )
117
+ time .sleep (5 )
94
118
else :
95
119
logging .error ("API is not available !" )
120
+ time .sleep (5 )
0 commit comments