Переглянути джерело

Improve session handeling to prevent issues

JoostSijm 5 роки тому
батько
коміт
11357f7a1c
4 змінених файлів з 4 додано та 8 видалено
  1. 0 1
      app/__init__.py
  2. 1 2
      app/__main__.py
  3. 0 3
      app/api.py
  4. 3 2
      app/database.py

+ 0 - 1
app/__init__.py

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

+ 1 - 2
app/__main__.py

@@ -4,7 +4,7 @@ from datetime import datetime, timedelta
 import random
 import time
 
-from app import scheduler, LOGGER, session
+from app import scheduler, LOGGER
 from app.api import download_resources, refill
 from app.database import save_resources
 from app.app import need_refill, max_refill_seconds, print_resources
@@ -64,5 +64,4 @@ if __name__ == '__main__':
             time.sleep(100)
     except KeyboardInterrupt:
         LOGGER.info('Exiting application')
-        session.close()
         exit()

+ 0 - 3
app/api.py

@@ -24,13 +24,11 @@ def download_resources(state_id, resource_id):
     )
     return parse_resources(response.text)
 
-
 def read_resources():
     """Read resource file"""
     with open('resources.html') as file:
         return parse_resources(file)
 
-
 def parse_resources(html):
     """Read the resources left"""
     soup = BeautifulSoup(html, 'html.parser')
@@ -50,7 +48,6 @@ def parse_resources(html):
         }
     return regions
 
-
 def refill(state_id, capital_id, resource_id):
     """Main function"""
     # Check location

+ 3 - 2
app/database.py

@@ -1,16 +1,16 @@
 """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
     session.add(resource_track)
-    session.commit()
 
     for region_id, region in regions.items():
         resource_stat = ResourceStat()
@@ -21,3 +21,4 @@ def save_resources(state_id, regions, resource_id):
         resource_stat.limit_left = region['limit_left']
         session.add(resource_stat)
     session.commit()
+    session.close()