Prechádzať zdrojové kódy

Pass the db connection as argument

Foppe Hemminga 6 rokov pred
rodič
commit
cdc6eca917
2 zmenil súbory, kde vykonal 10 pridanie a 10 odobranie
  1. 4 4
      main.py
  2. 6 6
      model.py

+ 4 - 4
main.py

@@ -11,17 +11,17 @@ import database
 
 if __name__ == '__main__':
     db = database.db
-    timestamp_latest = model.get_timestamp_latest()
+    timestamp_latest = model.get_timestamp_latest(db)
     timestamp_stored = model.get_timestamp_stored()
     if timestamp_latest == timestamp_stored:
         """Nothing to do"""
         sys.exit()
     # Update timestamp_stored
     model.put_timestamp_stored(timestamp_latest)
-    timestamp_previous = model.get_timestamp_previous()
+    timestamp_previous = model.get_timestamp_previous(db)
     for stock in stocks.stocks:
-        data_previous = model.get_data(stock.stock_id, timestamp_previous)
-        data_latest = model.get_data(stock.stock_id, timestamp_latest)
+        data_previous = model.get_data(stock.stock_id, timestamp_previous, db)
+        data_latest = model.get_data(stock.stock_id, timestamp_latest, db)
         threshold = stock[3]
         is_drop = model.process_data(data_previous, data_latest, threshold)
         stock_name = stock[0]

+ 6 - 6
model.py

@@ -1,12 +1,12 @@
 import psycopg2.extras
 
 
-def get_timestamp_previous():
+def get_timestamp_previous(this_db):
     """
     Retrieve second to last timestamp from the stocks database
     :return timestamp:
     """
-    cursor = db.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
+    cursor = this_db.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
     query = """SELECT DISTINCT timestamp FROM stocks ORDER BY stocks.timestamp DESC LIMIT 1 OFFSET 1;"""
     cursor.execute(query)
     res = cursor.fetchone()
@@ -15,12 +15,12 @@ def get_timestamp_previous():
     return this_timestamp_previous
 
 
-def get_timestamp_latest():
+def get_timestamp_latest(this_db):
     """
     Retrieve latest timestamp from the stocks database
     :return timestamp:
     """
-    cursor = db.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
+    cursor = this_db.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
     query = """SELECT DISTINCT timestamp FROM stocks ORDER BY stocks.timestamp DESC LIMIT 1;"""
     cursor.execute(query)
     res = cursor.fetchone()
@@ -53,8 +53,8 @@ def put_timestamp_stored(this_timestamp):
         f.write("{}".format(this_timestamp))
 
 
-def get_data(stock_id, this_timestamp):
-    cursor = db.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
+def get_data(stock_id, this_timestamp, this_db):
+    cursor = this_db.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
     query = """SELECT current_price, available_shares FROM stocks WHERE stock_id = %s AND timestamp = %s"""
     cursor.execute(query, (stock_id, this_timestamp))
     this_data = cursor.fetchone()