Przeglądaj źródła

Improve database session handeling

JoostSijm 5 lat temu
rodzic
commit
0e8f082340
3 zmienionych plików z 10 dodań i 5 usunięć
  1. 1 0
      app/__init__.py
  2. 8 3
      app/__main__.py
  3. 1 2
      app/database.py

+ 1 - 0
app/__init__.py

@@ -16,6 +16,7 @@ load_dotenv()
 # database
 engine = create_engine(os.environ["DATABASE_URI"])
 Session = sessionmaker(bind=engine)
+session = Session()
 
 # scheduler
 scheduler = BackgroundScheduler()

+ 8 - 3
app/__main__.py

@@ -4,7 +4,7 @@ from datetime import datetime, timedelta
 import random
 import time
 
-from app import scheduler, LOGGER
+from app import scheduler, LOGGER, session
 from app.api import download_resources, refill
 from app.database import save_resources
 from app.app import need_refill, max_refill_seconds, print_resources
@@ -59,5 +59,10 @@ if __name__ == '__main__':
     add_check_resources(2788, 4003, 0, True, '0,15,30,45')
     add_check_resources(2788, 4003, 11, True, '0')
 
-    while True:
-        time.sleep(100)
+    try:
+        while True:
+            time.sleep(100)
+    except KeyboardInterrupt:
+        LOGGER.info('Exiting application')
+        session.close()
+        exit()

+ 1 - 2
app/database.py

@@ -1,12 +1,11 @@
 """Main application"""
 
-from app import Session
+from app import session
 from app.models import ResourceTrack, ResourceStat
 
 
 def save_resources(state_id, regions, resource_id):
     """Save resources to database"""
-    session = Session()
     resource_track = ResourceTrack()
     resource_track.state_id = state_id
     resource_track.resource_type = resource_id