Blame view

MLTD/src/ReportTimeDB.py 1.48 KB
0d8c0f816   Thanasis Naskos   initial commit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
  # -*- coding: utf-8 -*-
  import psycopg2.extras
  from datetime import datetime
  
  
  def check_db_status(time_db_cursor, time_db_dbname):
  
      # if the db is not found, then try to create it
      # try:
      #     time_db_cursor.execute("create database " + time_db_dbname);
      # except Exception as e:
      #     print("Database possibly exists: " + e)
  
      try:
          sql = """CREATE TABLE IF NOT EXISTS mltd(
             uuid serial PRIMARY KEY,
             asset_id VARCHAR (100) NOT NULL,
             probability REAL NOT NULL,
             timeframe VARCHAR (355) NOT NULL,
             created_on TIMESTAMP NOT NULL
          );"""
          time_db_cursor.execute(sql);
      except Exception as e:
          print("Table can't be created: " + e)
          return False
      return True
  
  
  def connect(
      time_db_host, time_db_port, time_db_dbname, time_db_username, time_db_password, ssl
  ):
      conn = psycopg2.connect(
          dbname=time_db_dbname,
          user=time_db_username,
          password=time_db_password,
          host=time_db_host,
      )
      cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
      check_db_status(cursor, time_db_dbname)
      cursor.close()
      conn.commit()
      return conn
  
  
  def report(conn, asset_id, risk, timeframe):
      sql = """INSERT INTO mltd(asset_id,probability,timeframe,created_on)
                   VALUES(%s,%s,%s,%s);"""
      cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
      cursor.execute(sql, (asset_id, risk, timeframe, datetime.now()))
      conn.commit()