Skip to content

Commit 4331096

Browse files
authored
Merge pull request #4 from 777Samael/feature/databases
Feature/databases
2 parents 9f98060 + 4ca6b3f commit 4331096

File tree

17 files changed

+652
-0
lines changed

17 files changed

+652
-0
lines changed

MusicBrowser/backwards.txt

Whitespace-only changes.

MusicBrowser/jukebox.py

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
import sqlite3
2+
import tkinter
3+
4+
class Scrollbox(tkinter.Listbox):
5+
6+
def __init__(self, window, **kwargs):
7+
super().__init__(window, **kwargs)
8+
9+
self.scrollbar = tkinter.Scrollbar(window, orient=tkinter.VERTICAL, command=self.yview)
10+
11+
def grid(self, row, column, sticky='nsw', rowspan=1, columnspan=1, **kwargs):
12+
super().grid(row=row, column=column, sticky=sticky, rowspan=rowspan, columnspan=columnspan, **kwargs)
13+
self.scrollbar.grid(row=row, column=column, sticky='nse', rowspan=rowspan)
14+
self['yscrollcommand'] = self.scrollbar.set
15+
16+
17+
class DataListBox(Scrollbox):
18+
19+
def __init__(self, window, connection, table, field, sort_order=(), **kwargs):
20+
super().__init__(window, **kwargs)
21+
22+
self.linked_box = None
23+
self.link_field = None
24+
self.link_value = None
25+
26+
self.cursor = connection.cursor()
27+
self.table = table
28+
self.field = field
29+
30+
self.bind('<<ListboxSelect>>', self.on_select)
31+
32+
self.sql_select = f"SELECT {self.field}, _id FROM {self.table}"
33+
if sort_order:
34+
self.sql_sort = " ORDER BY " + ','.join(sort_order)
35+
else:
36+
self.sql_sort = f" ORDER BY {self.field}"
37+
38+
def clear(self):
39+
self.delete(0, tkinter.END)
40+
41+
def link(self, widget, link_field):
42+
self.linked_box = widget
43+
widget.link_field = link_field
44+
45+
def requery(self, link_value=None):
46+
self.link_value = link_value # store the id, so we know the "master" record we're populated from
47+
if link_value and self.link_field:
48+
sql = f"{self.sql_select} WHERE {self.link_field} = ?{self.sql_sort}"
49+
# sql = f"{self.sql_select} WHERE _id = ?{self.sql_sort}"
50+
self.cursor.execute(sql, (link_value,))
51+
else:
52+
self.cursor.execute(self.sql_select + self.sql_sort)
53+
54+
# clear the listbox contents before re-loading
55+
self.clear()
56+
for value in self.cursor:
57+
self.insert(tkinter.END, value[0])
58+
59+
if self.linked_box:
60+
self.linked_box.clear()
61+
62+
def on_select(self, event):
63+
if self.linked_box:
64+
index = self.curselection()[0]
65+
value = self.get(index),
66+
67+
# get the ID from the database row
68+
# Make sure we're getting the correct one, by including the link_value if appropriate
69+
if self.link_value:
70+
value = value[0], self.link_value
71+
sql_where = f" WHERE {self.field} = ? AND {self.link_field} = ?"
72+
else:
73+
sql_where = f" WHERE {self.field} = ?"
74+
75+
# get the artist ID from the database row
76+
link_id = self.cursor.execute(f"{self.sql_select} {sql_where}", value).fetchone()[1]
77+
self.linked_box.requery(link_id)
78+
79+
80+
if __name__ == '__main__':
81+
conn = sqlite3.connect('music.sqlite')
82+
83+
mainWindow = tkinter.Tk()
84+
mainWindow.title('Music DB Browser')
85+
mainWindow.geometry('1024x768')
86+
87+
mainWindow.columnconfigure(0, weight=2)
88+
mainWindow.columnconfigure(1, weight=2)
89+
mainWindow.columnconfigure(2, weight=2)
90+
mainWindow.columnconfigure(3, weight=1) # spacer column on right
91+
92+
mainWindow.rowconfigure(0, weight=1)
93+
mainWindow.rowconfigure(1, weight=5)
94+
mainWindow.rowconfigure(2, weight=5)
95+
mainWindow.rowconfigure(3, weight=1)
96+
97+
# ===== labels =====
98+
tkinter.Label(mainWindow, text="Artists").grid(row=0, column=0)
99+
tkinter.Label(mainWindow, text="Albums").grid(row=0, column=1)
100+
tkinter.Label(mainWindow, text="Songs").grid(row=0, column=2)
101+
102+
# ===== Artists Listbox =====
103+
artistList = DataListBox(mainWindow, conn, "artists", "name")
104+
artistList.grid(row=1, column=0, sticky='nsew', rowspan=2, padx=(30, 0))
105+
artistList.config(border=2, relief='sunken')
106+
107+
artistList.requery()
108+
109+
# ===== Albums Listbox =====
110+
albumLV = tkinter.Variable(mainWindow)
111+
albumLV.set(("Choose an artist",))
112+
albumList = DataListBox(mainWindow, conn, "albums", "name", sort_order=("name",))
113+
albumList.grid(row=1, column=1, sticky='nsew', padx=(30, 0))
114+
albumList.config(border=2, relief='sunken')
115+
116+
artistList.link(albumList, "artist")
117+
118+
# ===== Songs Listbox =====
119+
songLV = tkinter.Variable(mainWindow)
120+
songLV.set(("Choose an album",))
121+
songList = DataListBox(mainWindow, conn, "songs", "title", ("track", "title"))
122+
songList.grid(row=1, column=2, sticky='nsew', padx=(30, 0))
123+
songList.config(border=2, relief='sunken')
124+
125+
albumList.link(songList, "album")
126+
127+
# ===== Main loop =====
128+
mainWindow.mainloop()
129+
print("closing database connection")
130+
conn.close()

MusicBrowser/jukebox_old.py

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
import sqlite3
2+
import tkinter
3+
4+
conn = sqlite3.connect('music.sqlite')
5+
6+
7+
class Scrollbox(tkinter.Listbox):
8+
9+
def __init__(self, window, **kwargs):
10+
super().__init__(window, **kwargs)
11+
12+
self.scrollbar = tkinter.Scrollbar(window, orient=tkinter.VERTICAL, command=self.yview)
13+
14+
def grid(self, row, column, sticky='nsw', rowspan=1, columnspan=1, **kwargs):
15+
super().grid(row=row, column=column, sticky=sticky, rowspan=rowspan, columnspan=columnspan, **kwargs)
16+
self.scrollbar.grid(row=row, column=column, sticky='nse', rowspan=rowspan)
17+
self['yscrollcommand'] = self.scrollbar.set
18+
19+
20+
class DataListBox(Scrollbox):
21+
22+
def __init__(self, window, connection, table, field, sort_order=(), **kwargs):
23+
super().__init__(window, **kwargs)
24+
25+
self.cursor = connection.cursor()
26+
self.table = table
27+
self.field = field
28+
29+
self.sql_select = f"SELECT {self.field}, _id FROM {self.table}"
30+
if sort_order:
31+
self.sql_sort = " ORDER BY " + ','.join(sort_order)
32+
else:
33+
self.sql_sort = f" ORDER BY {self.field}"
34+
35+
def clear(self):
36+
self.delete(0, tkinter.END)
37+
38+
def requery(self):
39+
print(self.sql_select + self.sql_sort) # TODO delete this line
40+
self.cursor.execute(self.sql_select + self.sql_sort)
41+
42+
# clear the listbox contents before re-loading
43+
self.clear()
44+
for value in self.cursor:
45+
self.insert(tkinter.END, value[0])
46+
47+
48+
def get_albums(event):
49+
lb = event.widget
50+
index = lb.curselection()[0]
51+
artist_name = lb.get(index),
52+
53+
# get the artist ID from the database row
54+
artist_id = conn.execute("SELECT _id FROM artists WHERE name = ?", artist_name).fetchone()
55+
alist = []
56+
for row in conn.execute("SELECT name FROM albums WHERE artist = ? ORDER BY name", artist_id):
57+
alist.append(row[0])
58+
albumLV.set(tuple(alist))
59+
songLV.set(("Choose an album",))
60+
61+
62+
def get_songs(event):
63+
lb = event.widget
64+
index = int(lb.curselection()[0])
65+
album_name = lb.get(index),
66+
67+
# get album ID from the database row
68+
album_id = conn.execute("SELECT _id FROM albums WHERE name = ?", album_name).fetchone()
69+
alist = []
70+
for x in conn.execute("SELECT title FROM songs WHERE album = ? ORDER BY track", album_id):
71+
alist.append(x[0])
72+
songLV.set(tuple(alist))
73+
74+
75+
mainWindow = tkinter.Tk()
76+
mainWindow.title('Music DB Browser')
77+
mainWindow.geometry('1024x768')
78+
79+
mainWindow.columnconfigure(0, weight=2)
80+
mainWindow.columnconfigure(1, weight=2)
81+
mainWindow.columnconfigure(2, weight=2)
82+
mainWindow.columnconfigure(3, weight=1) # spacer column on right
83+
84+
mainWindow.rowconfigure(0, weight=1)
85+
mainWindow.rowconfigure(1, weight=5)
86+
mainWindow.rowconfigure(2, weight=5)
87+
mainWindow.rowconfigure(3, weight=1)
88+
89+
# ===== labels =====
90+
tkinter.Label(mainWindow, text="Artists").grid(row=0, column=0)
91+
tkinter.Label(mainWindow, text="Albums").grid(row=0, column=1)
92+
tkinter.Label(mainWindow, text="Songs").grid(row=0, column=2)
93+
94+
# ===== Artists Listbox =====
95+
artistList = Scrollbox(mainWindow)
96+
artistList.grid(row=1, column=0, sticky='nsew', rowspan=2, padx=(30, 0))
97+
artistList.config(border=2, relief='sunken')
98+
99+
for artist in conn.execute("SELECT name FROM artists ORDER BY name"):
100+
artistList.insert(tkinter.END, artist[0])
101+
102+
artistList.bind('<<ListboxSelect>>', get_albums)
103+
104+
# artistScroll = tkinter.Scrollbar(mainWindow, orient=tkinter.VERTICAL, command=artistList.yview)
105+
# artistScroll.grid(row=1, column=0, sticky='nse', rowspan=2)
106+
# artistList['yscrollcommand'] = artistScroll.set
107+
108+
# ===== Albums Listbox =====
109+
albumLV = tkinter.Variable(mainWindow)
110+
albumLV.set(("Choose an artist",))
111+
albumList = Scrollbox(mainWindow, listvariable=albumLV)
112+
albumList.grid(row=1, column=1, sticky='nsew', padx=(30, 0))
113+
albumList.config(border=2, relief='sunken')
114+
115+
albumList.bind('<<ListboxSelect>>', get_songs)
116+
117+
# ===== Songs Listbox =====
118+
songLV = tkinter.Variable(mainWindow)
119+
songLV.set(("Choose an album",))
120+
songList = Scrollbox(mainWindow, listvariable=songLV)
121+
songList.grid(row=1, column=2, sticky='nsew', padx=(30, 0))
122+
songList.config(border=2, relief='sunken')
123+
124+
# ===== Main loop =====
125+
# testList = range(0, 100)
126+
# albumLV.set(tuple(testList))
127+
128+
mainWindow.mainloop()
129+
print("closing database connection")
130+
conn.close()

MusicBrowser/music.sqlite

186 KB
Binary file not shown.

MusicBrowser/start_args.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
def avarage(*args):
2+
print(type(args))
3+
print(f"args is : {args}")
4+
print("*args is : ", *args)
5+
mean = 0
6+
for arg in args:
7+
mean += arg
8+
return mean / len(args)
9+
10+
11+
def build_tuple(*args):
12+
return args
13+
14+
15+
print(avarage(1, 2, 3, 4))
16+
17+
message_tuple = build_tuple("hello", "planet", "earth", "take", "me", "to", "your", "leader")
18+
print(type(message_tuple))
19+
print(message_tuple)
20+
21+
number_tuple = build_tuple(1, 2, 3, 4, 5, 6)
22+
print(type(number_tuple))
23+
print(number_tuple)

MusicBrowser/start_kwargs.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# def print_backwards(*args, file=None):
2+
# for word in args[::-1]:
3+
# print(word[::-1], end=' ', file=file)
4+
# def print_backwards(*args, end=' ', **kwargs):
5+
# print(kwargs)
6+
# for word in args[::-1]:
7+
# print(word[::-1], end=' ', **kwargs)
8+
def print_backwards(*args, **kwargs):
9+
end_character = kwargs.pop('end', '\n')
10+
sep_character = kwargs.pop('sep', ' ')
11+
for word in args[:0:-1]: # change the range
12+
print(word[::-1], end=sep_character, **kwargs)
13+
print(args[0][::-1], end=end_character, **kwargs) # print first word separately
14+
# print(end=end_character)
15+
16+
17+
def backwards_print(*args, **kwargs):
18+
sep_character = kwargs.pop('sep', ' ')
19+
print(sep_character.join(word[::-1] for word in args[::-1]), **kwargs)
20+
21+
22+
with open("backwards.txt", 'w') as backwards:
23+
print_backwards("hello", "planet", "earth", "take", "me", "to", "your", "leader", end='\n')
24+
print("Another String")
25+
26+
print("hello", "planet", "earth", "take", "me", "to", "your", "leader", end='', sep='\n**\n')
27+
print_backwards("hello", "planet", "earth", "take", "me", "to", "your", "leader", end='', sep='\n**\n')
28+
print('='*10)

RollingBack/accounts.sqlite

20 KB
Binary file not shown.

RollingBack/checkdb.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import sqlite3
2+
import pytz
3+
4+
db = sqlite3.connect("accounts.sqlite", detect_types=sqlite3.PARSE_DECLTYPES)
5+
6+
for row in db.execute("SELECT * FROM history"):
7+
utc_time = row[0]
8+
local_time = pytz.utc.localize(utc_time).astimezone()
9+
print(f"{utc_time},\t {local_time}")
10+
11+
db.close()

RollingBack/checkdb1.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import sqlite3
2+
3+
db = sqlite3.connect("accounts.sqlite", detect_types=sqlite3.PARSE_DECLTYPES)
4+
5+
# for row in db.execute("SELECT strftime('%Y-%m-%d %H:%M:%f', history.time, 'localtime') as localtime, history.account,"
6+
# "history.amount FROM history ORDER BY history.time"):
7+
for row in db.execute("SELECT * FROM localhistory"):
8+
print(row)
9+
10+
db.close()

RollingBack/rollback2.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
from decimal import *
2+
3+
4+
class Account(object):
5+
_qb = Decimal('0.00') # class constant, accessible without creating an instance.
6+
7+
def __init__(self, name: str, opening_balance: float = 0.0):
8+
self.name = name
9+
self._balance = Decimal(opening_balance).quantize(Account._qb)
10+
print("Account created for {}. ".format(self.name), end='')
11+
self.show_balance()
12+
13+
def deposit(self, amount: float) -> Decimal:
14+
decimal_amount = Decimal(amount).quantize(Account._qb)
15+
if decimal_amount > Account._qb:
16+
self._balance = self._balance + decimal_amount
17+
print("{} deposited".format(decimal_amount))
18+
return self._balance
19+
20+
def withdraw(self, amount: float) -> Decimal:
21+
decimal_amount = Decimal(amount).quantize(Account._qb)
22+
if Account._qb < decimal_amount <= self._balance:
23+
self._balance = self._balance - decimal_amount
24+
print("{} withdrawn".format(decimal_amount))
25+
return decimal_amount
26+
else:
27+
print("The amount must be greater than zero and no more than your account balance")
28+
return Account._qb
29+
30+
def show_balance(self):
31+
print("Balance on account {} is {}".format(self.name, self._balance))
32+
33+
34+
if __name__ == '__main__':
35+
tim = Account("Tim")
36+
tim.deposit(10.1)
37+
tim.deposit(0.1)
38+
tim.deposit(0.1)
39+
tim.withdraw(0.3)
40+
tim.withdraw(0)
41+
tim.show_balance()
42+
43+
print("=" * 80)
44+
x = tim.withdraw(900)
45+
print(x)

0 commit comments

Comments
 (0)