-
Notifications
You must be signed in to change notification settings - Fork 46
/
main.py
executable file
·162 lines (135 loc) · 5.35 KB
/
main.py
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
#!/usr/bin/env python
from shutil import copyfile
from datetime import datetime
from importlib import reload
import fetch, time, os, re, sqlite3
__author__ = "Caio Brandao"
__copyright__ = "Copyright 2019+, Caio Brandao"
__license__ = "MIT"
__version__ = "0.0"
__maintainer__ = "Caio Brandao"
__email__ = "[email protected]"
# Create back-up file under /db/backup
def backup_db(file):
#today = datetime.today().strftime('%Y%m%d%H')
new_file = db_file['db_backup'].format(
input('Enter back-up file name:\n'))
fetch.print_('Please wait while the database file is backed-up ...')
copyfile(db_file['path'], new_file)
return '\n~ Back-up file saved\t{}'.format(new_file)
# Change variable for .sqlite file name based on user input
def change_name(old_name):
msg = 'Existing database files in directory \'db/\': {}\n'
msg += 'Enter new name for .sqlite file (current = \'{}\'):\n'
fname = lambda x: re.sub('.sqlite', '', x)
files = [fname(f) for f in os.listdir('db/') if '.sqlite' in f]
return input(msg.format(files, old_name))
# Print options menu
def print_menu(names):
gap = 22
dash = '='
banner = ' Welcome to msTables '
file = '\'{}.sqlite\''.format(db_file['name'])
menu = {
'0' : 'Change database file name (current name = {})'.format(file),
'1' : 'Create database tables and import latest symbols',
'2' : 'Download Morningstar data into database',
'3' : 'Erase all records from database tables',
'4' : 'Delete all database tables',
'5' : 'Erase all downloaded history from \'Fetched_urls\' table',
#'X' : 'Parse (FOR TESTING PURPOSES)',
'6' : 'Create a database back-up file'
}
print(dash * (len(banner) + gap * 2))
print('{}{}{}'.format(dash * gap, banner, dash * gap))
print('\nAvailable actions:\n')
for k, v in menu.items():
print(k, '-', v)
print('\n' + dash * (len(banner) + gap * 2))
return menu
# Print command line menu for user input
def main(file):
while True:
# Print menu and capture user selection
ops = print_menu(file)
while True:
try:
inp0 = input('Enter action no.:\n').strip()
break
except KeyboardInterrupt:
print('\nGoodbye!')
exit()
if inp0 not in ops.keys(): break
reload(fetch) #Comment out after development
start = time.time()
inp = int(inp0)
ans = 'y'
# Ask user to confirm selection if input > 2
if inp > 2:
msg = '\nAre you sure you would like to {}? (Y/n):\n'
ans = input(msg.format(ops[inp0].upper())).lower()
# Call function according to user input
if ans == 'y':
print()
try:
# Change db file name
if inp == 0:
db_file['name'] = change_name(db_file['name'])
start = time.time()
db_file['path'] = db_file['npath'].format(db_file['name'])
msg = ('~ Database file \'{}\' selected'
.format(db_file['name']))
# Create database tables
elif inp == 1:
msg = fetch.create_tables(db_file['path'])
# Download data from urls listed in api.json
elif inp == 2:
start = fetch.fetch(db_file['path'])
msg = '\n~ Database updated successfully'
# Erase records from all tables
elif inp == 3:
msg = fetch.erase_tables(db_file['path'])
# Delete all tables
elif inp == 4:
msg = fetch.delete_tables(db_file['path'])
# Delete Fetched_urls table records
elif inp == 5:
msg = fetch.del_fetch_history(db_file['path'])
# Back-up database file
elif inp == int(list(ops.keys())[-1]):
msg = backup_db(db_file)
# TESTING
elif inp == 99:
fetch.parse.parse(db_file['path'])
msg = 'FINISHED'
# except sqlite3.OperationalError as S:
# msg = '### Error message - {}'.format(S) + \
# '\n### Scroll up for more details. If table does not ' + \
# 'exist, make sure to execute action 1 before choosing' + \
# ' other actions.'
# pass
# except KeyboardInterrupt:
# print('\nGoodbye!')
# exit()
except Exception as e:
print('\a')
#print('\n\n### Error @ main.py:\n {}\n'.format(e))
raise
# Print output message
#os.system('clear')
print(msg)
# Calculate and print execution time
end = time.time()
print('\n~ Execution Time\t{:.2f} sec\n'.format(end - start))
else:
os.system('clear')
# Define database (db) file and menu text variables
db_file = dict()
db_file['npath'] = 'db/{}.sqlite'
db_file['name'] = 'mstables'
db_file['path'] = db_file['npath'].format(db_file['name'])
db_file['db_backup'] = 'db/backup/{}.sqlite'
if __name__ == '__main__':
os.system('clear')
main(db_file)
print('Goodbye!\n\n')