streamline logging and commits. fix some bugs

This commit is contained in:
2021-06-02 20:28:30 +02:00
parent 3a189ad8ed
commit 727c7b486c

View File

@@ -3,7 +3,7 @@
#
# timeTrack.py
# by 4nima
# v.0.1
# v.0.2
#
#########################
# simple time tracking with database
@@ -15,6 +15,7 @@ import json
import os
import logging
# Main class
class TimeTrack:
def __init__(self, DATABASE='timetrack.db', CONFIG='timetrack.conf'):
self.DATABASE = DATABASE
@@ -22,48 +23,22 @@ class TimeTrack:
self.USERID = 0
self.USERNAME = ''
self.LOGFILE = 'timetrack.log'
logging.basicConfig(filename=self.LOGFILE,
logging.basicConfig(
filename=self.LOGFILE,
level=logging.DEBUG,
format='%(asctime)s - %(process)d-%(levelname)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
self.load_config()
self.db_setup()
self.set_user()
## Läd oder erstellt das config file
def load_config(self):
if os.path.isfile(self.CONFIG):
logging.info('Config file found')
try:
with open(self.CONFIG) as config_data:
data = json.load(config_data)
except ValueError:
logging.error('Config file has no valid JSON syntax')
print('TimeTrack wird beendet. Fehler in der JSON-Konfig')
quit()
else:
logging.info('Config file loaded successfully')
self.USERID = data['user']
else:
logging.info('Config file not found')
##> ausgabe nicht in einer zeile
config = {
'user' : 1,
'default' : 'interactive'
}
##> logging erweitert falls nicht möglich
with open(self.CONFIG, "w") as outfile:
json.dump(config, outfile)
logging.info('config file successfully created')
self.load_config()
## Prepartation
### Creates a database if none is found
def db_setup(self):
if os.path.isfile(self.DATABASE):
logging.info('DB was found')
logging.info('Database file was found')
else:
logging.info('DB not found, create new')
logging.info('Database file was not found, will create ')
sql = []
sql.append("""
@@ -112,28 +87,66 @@ class TimeTrack:
connect = sqlite3.connect(self.DATABASE)
cursor = connect.cursor()
logging.debug('Create initial database tables')
for SQL in sql:
logging.debug('Run SQL')
try:
cursor.execute(SQL)
except:
logging.error('Fail to execute SQL command')
logging.error('Table could not be created')
logging.debug(SQL)
print('TimeTrack wird beendet: Fehler bei Datanbank Setup')
quit()
else:
logging.info('Success execute SQL command')
logging.debug('Table was created successfully or already exists')
connect.commit
connect.commit()
connect.close()
### Loads or creates a config file
def load_config(self):
if os.path.isfile(self.CONFIG):
logging.info('Config file was found')
try:
with open(self.CONFIG) as config_data:
data = json.load(config_data)
except ValueError:
logging.error('Config file has no valid JSON syntax')
print('TimeTrack wird beendet: Fehler in der JSON-Konfig ({})'.format(self.CONFIG))
quit()
else:
logging.info('Config file was loaded successfully')
self.USERID = data['user']
logging.debug('UserID {} was used'.format(data['user']))
self.set_user()
else:
logging.warning('Config file not found')
config = {
'user' : 1,
'default' : 'interactive'
}
with open(self.CONFIG, "w") as outfile:
json.dump(config, outfile, indent=4, sort_keys=True)
logging.info('Config file created successfully')
#> wenn man keine datei erstellen darf/kann, fällt das skript in einen loop ?
self.load_config()
## user handling
### Creates a user who does not yet exist
def create_user(self, USER=''):
if USER == '':
username = input('Enter your Name: ')
username = input('Benutzername eingaben: ')
logging.debug('Selected username: {}'.format(username))
else:
username = USER
while self.get_users(NAME=username):
print('Name ist schon vergeben')
username = input('Wähle einen anderen Namen: ')
print('Der gewünsche Benutzername ({}) ist schon vergeben'.format(username))
username = input('Wähle einen anderen Benutzernamen: ')
logging.debug('Try again: Selected username: {}'.format(username))
logging.debug('Accepted username: {}'.format(username))
connect = sqlite3.connect(self.DATABASE)
cursor = connect.cursor()
@@ -143,25 +156,26 @@ class TimeTrack:
try:
cursor.execute(sql, [username])
except:
logging.error('Fail to execute SQL command')
logging.error('User could not be saved in database')
logging.debug(sql)
else:
logging.info('Success execute SQL command')
logging.info('User was saved successfully')
connect.commit()
connect.close()
### Outputs existing users from the DB
def get_users(self, UID=0, NAME=''):
if not UID == 0:
logging.info('UID Used')
logging.debug('Get user by ID: {}'.format(UID))
data = UID
sql = "SELECT * FROM users WHERE id = ?"
elif not NAME == '':
logging.info('NAME used')
logging.debug('Get user by username: {}'.format(NAME))
data = NAME
sql = "SELECT * FROM users WHERE name = ?"
sql = "SELECT * FROM users WHERE name LIKE ?"
else:
logging.info('nothing used')
logging.debug('Get all users')
data = ''
sql = "SELECT * FROM users"
@@ -173,12 +187,13 @@ class TimeTrack:
cursor.execute(sql, [data])
else:
cursor.execute(sql)
except:
logging.error('Fail to execute SQL command')
logging.error('Could not get user')
logging.debug(sql)
print('Fehler beim Zugriff auf die Benutzer Datenbank')
return 1
else:
logging.info('Success execute SQL command')
logging.debug('User database read out successfully')
connect.commit()
row = cursor.fetchall()
@@ -188,15 +203,18 @@ class TimeTrack:
connect.close()
return output
### Defines a user for the session
def set_user(self):
data = self.get_users()
if not data:
logging.info("No user found. Create new.")
print("Es wurde kein User gefunden, bitte legen sie einen neuen an.")
logging.info("No user was found")
print("Es wurde kein Benutzer gefunden, bitte legen sie einen neuen an.")
self.create_user()
data = self.get_users(UID=self.USERID)
try:
self.USERNAME = data[0][1]
except IndexError:
logging.error('User ID was not found')
test = TimeTrack()