瀏覽代碼

Opening the db only once

Foppe Hemminga 6 年之前
父節點
當前提交
8a2035cc77
共有 2 個文件被更改,包括 6 次插入9 次删除
  1. 5 1
      main.py
  2. 1 8
      model.py

+ 5 - 1
main.py

@@ -2,12 +2,15 @@ import model
 import sys
 import stocks
 import view
+import database
+
 
 """
     This is the controller file
 """
 
 if __name__ == '__main__':
+    db = database.db
     timestamp_latest = model.get_timestamp_latest()
     timestamp_stored = model.get_timestamp_stored()
     if timestamp_latest == timestamp_stored:
@@ -28,4 +31,5 @@ if __name__ == '__main__':
             stock_name, timestamp_latest, current_price, quantity)
         print(message)
         if is_drop:
-            view.broadcast(message)
+            view.broadcast(message)
+    db.close()

+ 1 - 8
model.py

@@ -1,4 +1,3 @@
-import database
 import psycopg2.extras
 
 
@@ -7,14 +6,12 @@ def get_timestamp_previous():
     Retrieve second to last timestamp from the stocks database
     :return timestamp:
     """
-    db = database.db
     cursor = 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()
     this_timestamp_previous = res.timestamp
     cursor.close()
-    db.close()
     return this_timestamp_previous
 
 
@@ -23,14 +20,12 @@ def get_timestamp_latest():
     Retrieve latest timestamp from the stocks database
     :return timestamp:
     """
-    db = database.db
     cursor = 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()
     this_timestamp_latest = res.timestamp
     cursor.close()
-    db.close()
     return this_timestamp_latest
 
 
@@ -41,7 +36,7 @@ def get_timestamp_stored():
     """
     with open('timestamp.txt', 'r') as f:
         this_timestamp_stored_string = f.read()
-    if this_timestamp_stored_string.replace('.','',1).isdigit():
+    if this_timestamp_stored_string.replace('.', '', 1).isdigit():
         this_timestamp_stored = int(this_timestamp_stored_string)
     else:
         this_timestamp_stored = 0
@@ -59,13 +54,11 @@ def put_timestamp_stored(this_timestamp):
 
 
 def get_data(stock_id, this_timestamp):
-    db = database.db
     cursor = 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()
     cursor.close()
-    db.close()
     return this_data