Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
models file I created for the CS50 finance project
from cs50 import SQL
import sqlite3
class users_db:
def __init__(self, conn):
self.id = ''
self.conn = conn
self.c = conn.cursor()
def register(self, username, hash):
row = self.c.execute('INSERT INTO users (username, hash, cash) VALUES (?, ?, 10000)', (username, hash))
self.conn.commit()
return self.c.lastrowid
def set_id(self, id):
self.id = id
def get_balance(self):
self.c.execute('SELECT cash FROM users WHERE id=?', (self.id,))
return self.c.fetchone()
def update_balance(self, new_balance):
self.c.execute('UPDATE users SET cash=? WHERE id=?', (new_balance,self.id))
self.conn.commit()
def update_password(self, hash):
self.c.execute('UPDATE users SET hash=? WHERE id=?', (hash, self.id))
self.conn.commit()
class transactions_db:
def __init__(self, user_id, conn):
self.id = user_id
self.conn = conn
self.c = conn.cursor()
def get_history(self):
self.c.execute('SELECT * FROM transactions where user_id=?', (self.id))
results = []
for data in self.c.fetchall():
col = {}
col['type'] = data[1]
col['symbol'] = data[2]
col['price'] = data[3]
col['shares'] = data[4]
col['date_time'] = data[5]
results.append(col)
return results
def insert(self, row):
self.c.execute('INSERT INTO transactions VALUES (?,?,?,?,?,?)', (self.id,) + row)
self.conn.commit()
class portfolio_db:
def __init__(self, user_id, conn):
self.id = user_id
self.conn = conn
self.c = conn.cursor()
def get_holdings(self):
self.c.execute('SELECT symbol, shares FROM portfolio WHERE user_id=?', (self.id,))
results = []
for data in self.c.fetchall():
col = {}
col['symbol'] = data[0]
col['shares'] = data[1]
results.append(col)
return results
def get_number_of_shares(self, symbol):
self.c.execute('SELECT shares FROM portfolio WHERE user_id=? AND symbol=?', (self.id, symbol))
return self.c.fetchone()
def update_shares(self, shares, symbol):
self.c.execute('UPDATE portfolio SET shares=? WHERE symbol=? AND user_id=?', (shares, symbol, self.id))
self.conn.commit()
def insert_shares(self, shares, symbol):
self.c.execute('INSERT INTO portfolio VALUES (?,?,?)', (self.id, symbol, shares))
self.conn.commit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment