Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import mysql.connector as mariadb
- db = Database(db_hostname='mariamicro.cg7ucsq2kyal.eu-west-2.rds.amazonaws.com',
- db_username='crap_db',
- db_password='BrmDatabase3159',
- db_dataname='CRAP')
- class DBError(Exception):
- """
- Fange exceptions for invalide kommandoer og andre responser som
- ikke er en kode 200 respons.
- """
- def __init__(self, err):
- pass
- class Database(object):
- def __init__(self, db_hostname = None, db_username = None, db_password = None, db_dataname = None)
- self.db_hostname = str(db_hostname) if db_hostname else raise DBError("No hostname given.")
- self.db_username = str(db_username) if db_username else raise DBError("DB username is needed.")
- self.db_password = str(db_password) if db_password else raise DBError("DB password is needed.")
- self.db_dataname = str(db_dataname) if db_dataname else raise DBError("No database name is given.")
- def connect(self):
- try:
- self.db_connection = mariadb.connect(host=self.db_hostname, user=self.db_username, password=self.db_password, database=self.db_dataname)
- except self.db_connection.error as e:
- raise DBError(str(e))
- def append_tx_log(self, line: dict) -> int:
- out = 0
- if self.tx_exists(line) = True:
- print("Line already exists, not appending")
- return 0
- in_date = line['Date Acquired']
- in_nok_amount = line['Cost Basis']
- in_foreign_amount = line['Volume']
- in_foreign_currency = line['Symbol']
- cursor = self.db_connection.cursor()
- try:
- cursor.execute("INSERT INTO Tx_Log
- (Date, NOK_Amount, Foreign_Amount, Foreign_Currency)
- VALUES (%s, %s, %s, %s)",
- (in_date, in_nok_amount, in_foreign_amount, in_foreign_currency))
- except self.db_connection.Error as error:
- print("Error: {}".format(error))
- db_connection.commit()
- out = db_connection.insert_id()
- return out
- def tx_exists(self, line: dict):
- out = True
- in_date = line['Date Acquired']
- in_nok_amount = line['Cost Basis']
- in_foreign_amount = line['Volume']
- in_foreign_currency = line['Symbol']
- cursor = self.db_connection.cursor()
- match = cursor.execute("SELECT ID FROM Tx_Log WHERE
- date=%s AND NOK_Amount=%s
- AND Foreign_Amount=%s AND Foreign_Currency=%s",
- (in_date, in_nok_amount, in_foreign_amount, in_foreign_currency))
- # Check log files for duplicates
- if match.rowcount == 0
- # return false if no match is found
- out = False
- return out
- def close_connection(self)
- self.db_connection.close()
- # Check if the log file contains the transaction
- # by compare_line(dict, logfile). If it returns true,
- # add the line to log file append_log(dict, logfile)
- # and then push line to Fiken. If false, skip the line.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement