49 lines
1.2 KiB
Python
49 lines
1.2 KiB
Python
import os
|
|
from typing import Callable
|
|
from rethinkdb import RethinkDB
|
|
from .Condition import Condition
|
|
|
|
RDB_HOST = os.environ.get('RETHINKDB_URL')
|
|
RDB_PORT = os.environ.get('RETHINKDB_PORT')
|
|
DB_NAME = "finfree"
|
|
TABLE_NAME = 'conditions'
|
|
|
|
r = RethinkDB()
|
|
connection = None
|
|
|
|
def get_connection():
|
|
global connection
|
|
|
|
if connection is None or not connection.is_open():
|
|
connection = r.connect(RDB_HOST, RDB_PORT, db=DB_NAME)
|
|
|
|
return connection
|
|
|
|
def getRethinkDB():
|
|
return r
|
|
|
|
def fetch_conditions() -> list[Condition]:
|
|
try:
|
|
cursor = r.table(TABLE_NAME).run(get_connection())
|
|
return [Condition(**doc) for doc in cursor]
|
|
except Exception as e:
|
|
print(f"Error fetching symbols: {e}")
|
|
return []
|
|
|
|
conditions: list[Condition] = list()
|
|
|
|
class DbConnector:
|
|
def watch_conditions(callback: Callable[[Condition], None]):
|
|
global conditions
|
|
|
|
conditions = fetch_conditions()
|
|
|
|
for cond in conditions:
|
|
callback(cond)
|
|
|
|
feed = r.table(TABLE_NAME).changes().run(get_connection())
|
|
for change in feed:
|
|
if change['new_val'] and not change['old_val']: # New symbol added
|
|
cond: Condition = change['new_val']
|
|
callback(cond)
|