From 226a0000b1d99a999a87e66b1fba984b214c9641 Mon Sep 17 00:00:00 2001 From: Ted Henriksson Date: Sat, 14 May 2016 14:20:22 +0200 Subject: [PATCH 01/17] Added ignor for pycharm project files. --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 311a7d5..cd0255d 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ People.db +.idea From fbaf9a333cad58cee1e2cb90e8f789af497a6c62 Mon Sep 17 00:00:00 2001 From: Ted Henriksson Date: Sat, 14 May 2016 15:58:44 +0200 Subject: [PATCH 02/17] Added __pycache__ to git ignore. --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index cd0255d..3c536f7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ People.db .idea +__pycache__ From 9c00b4ec173460962288591a3ff76b0b72edf042 Mon Sep 17 00:00:00 2001 From: Ted Henriksson Date: Mon, 10 Apr 2017 19:59:14 +0200 Subject: [PATCH 03/17] First commit with peewee as a data manager --- models.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 models.py diff --git a/models.py b/models.py new file mode 100644 index 0000000..c214972 --- /dev/null +++ b/models.py @@ -0,0 +1,14 @@ +from peewee import * + +db = SqliteDatabase('People.db', **{}) + +class Person(Model): + nick = TextField(db_column='Nick', null=False) + blipId = IntegerField(db_column='blipId', null=False) + ishere = BooleanField(db_column='isHere', null=False, default=False) + lastlogin = FloatField(db_column='lastLogin', null=False) # FLOAT + totaltime = FloatField(db_column='totalTime', null=True) # FLOAT + + class Meta: + database = db + db_table = 'People' From 61f04f90b9f4a14b3e75693721d40d1b74eae0ae Mon Sep 17 00:00:00 2001 From: Ted Henriksson Date: Mon, 10 Apr 2017 20:06:37 +0200 Subject: [PATCH 04/17] Add missing files from first commit. --- HighScore.py | 1 + blipper.py | 146 +++++++++++++++++++++++++++++++++------------------ setup_db.py | 47 ++++++++++++----- 3 files changed, 129 insertions(+), 65 deletions(-) diff --git a/HighScore.py b/HighScore.py index a432f88..0238600 100644 --- a/HighScore.py +++ b/HighScore.py @@ -1,4 +1,5 @@ #!/usr/bin/python + # -*- coding: utf-8 -*- import sqlite3 as lite diff --git a/blipper.py b/blipper.py index 1f0d9ba..7fed8c4 100644 --- a/blipper.py +++ b/blipper.py @@ -2,57 +2,101 @@ # -*- coding: utf-8 -*- """Simple script for registering members coming and going. """ -import sqlite3 as lite +from peewee import * +from models import Person import time -while True: + +db = SqliteDatabase('People.db', **{}) + + +def login(user): + + + if user.ishere: + user.ishere = False + user. + print("-----------------------------------------------") + print("Goodbye " + user.nick + " your highscore is: " + + user.totaltime) + print("-----------------------------------------------") + else: + pass + + +def createPerson(rfId): + print("-----------------------------------------------") + print('There is no rfidtag named ', rfId, ' creating instance!') + + nick = input('Input your nick: ') + new_member = Person.create(nick=nick) + new_member.lastlogin = time.time() + new_member.blipId = rfId + new_member.ishere = True + new_member.totaltime = 0 + + new_member.save() + print('you now exist and are logged in! dont forget to logout!') + print("-----------------------------------------------") + +if __name__ == '__main__': + + db.connect() + while True: + while True: + try: + temp = input("Blip me! ") + rfId = int(temp) + break + except ValueError: + print("Blip not recognised") + print("") + try: - temp = input("Blip me! ") - rfId = int(temp) - break - except ValueError: - print("Blip not recognised") - print("") - - con = lite.connect('People.db') - with con: - cur = con.cursor() - cur.execute("SELECT * FROM People WHERE blipId = ?", (rfId,)) - data = cur.fetchone() - - if data is None: # there is no user with this ID tag - print("-----------------------------------------------") - print('There is no rfidtag named ', rfId, ' creating instance!') - - nick_temp = input("input your nick: ") - temp = cur.lastrowid - if temp is None: - temp_id = 1 - else: - temp_id = temp + 1 - - cur.execute("INSERT INTO People VALUES (?,?,?,?,?,?);", - (temp_id, rfId, nick_temp, 1, 0, time.time())) - print('you now exist and are logged in! dont forget to logout!') - print("-----------------------------------------------") - else: # there is user with this ID tag - if data[3] is 1: # is logged in => log hen out - time_spent = time.time() - data[5] - new_total_time = time_spent + data[4] - cur.execute("UPDATE People SET totalTime=? WHERE blipId=?", - (new_total_time, rfId)) - cur.execute("UPDATE People SET isHere =? WHERE blipId=?", - (0, rfId)) - print("-----------------------------------------------") - print("Goodbye " + str(data[2]) + " your highscore is: " + - str(new_total_time)) - print("-----------------------------------------------") - - else: # is not logged in => log hen in - cur.execute("UPDATE People SET lastLogin =? WHERE blipId=?", - (time.time(), rfId)) - cur.execute("UPDATE People SET isHere =? WHERE blipId=?", - (1, rfId)) - print("-----------------------------------------------") - print("Welcome " + str(data[2])) - print("-----------------------------------------------") + user = Person.get(Person.blipId == rfId) + login(user) + except Person.DoesNotExist: + createPerson(rfId) + + # con = lite.connect('People.db') + # with con: + # cur = con.cursor() + # cur.execute("SELECT * FROM People WHERE blipId = ?", (rfId,)) + # data = cur.fetchone() + + # if data is None: # there is no user with this ID tag + # print("-----------------------------------------------") + # print('There is no rfidtag named ', rfId, ' creating instance!') + + # nick_temp = input("input your nick: ") + # temp = cur.lastrowid + # if temp is None: + # temp_id = 1 + # else: + # temp_id = temp + 1 + + # cur.execute("INSERT INTO People VALUES (?,?,?,?,?,?);", + # (temp_id, rfId, nick_temp, 1, 0, time.time())) + # print('you now exist and are logged in! dont forget to logout!') + # print("-----------------------------------------------") + # else: # there is user with this ID tag + # if data[3] is 1: # is logged in => log hen out + # time_spent = time.time() - data[5] + # new_total_time = time_spent + data[4] + # cur.execute("UPDATE People SET totalTime=? WHERE blipId=?", + # (new_total_time, rfId)) + # cur.execute("UPDATE People SET isHere =? WHERE blipId=?", + # (0, rfId)) + # print("-----------------------------------------------") + # print("Goodbye " + str(data[2]) + " your highscore is: " + + # str(new_total_time)) + # print("-----------------------------------------------") + + # else: # is not logged in => log hen in + # cur.execute("UPDATE People SET lastLogin =? WHERE blipId=?", + # (time.time(), rfId)) + # cur.execute("UPDATE People SET isHere =? WHERE blipId=?", + # (1, rfId)) + # print("-----------------------------------------------") + # print("Welcome " + str(data[2])) + # print("-----------------------------------------------") diff --git a/setup_db.py b/setup_db.py index f67f3d6..44156b0 100644 --- a/setup_db.py +++ b/setup_db.py @@ -1,24 +1,43 @@ #!/usr/bin/python # -*- coding: utf-8 -*- -"""Dev script to setup a test database. """ +""" Dev script to setup a test database. """ import sqlite3 as lite import time +import argparse +import os -con = lite.connect('People.db') +from models import Person +from peewee import * -with con: +db = SqliteDatabase('People.db', **{}) +db_file = 'People.db' - cur = con.cursor() +if __name__ == '__main__': - cur.execute("DROP TABLE IF EXISTS People") - cur.execute( - "CREATE TABLE People(Id INT, blipId INT, Nick TEXT, isHere INT," + - "totalTime FLOAT, lastLogin FLOAT)" - ) + parser = argparse.ArgumentParser(prog='setup_db', + description='Setup db for the time system') - temp_id = 1 - rfId = 1234 - nick_temp = 'ted' - cur.execute("INSERT INTO People VALUES (?,?,?,?,?,?);", - (temp_id, rfId, nick_temp, 1, 0, time.time())) + parser.add_argument('--remove', help='Remove the old db first.', + action="store_true") + parser.add_argument('action', choices=('dev', 'production'), + help='What type of db to setup.') + + args = parser.parse_args() + + if os.path.isfile(db_file) and args.remove: + os.remove(db_file) + else: # Backup db + os.rename(db_file, db_file + ".bak_" + time.strftime("%Y%m%d-%H:%M")) + + db.connect() + + db.create_tables([Person]) + + if args.action == 'dev': + tester = Person(nick='tester', blipId=1234, ishere = False) + tester.lastlogin = time.time() + tester.totaltime = 0 + tester.save() + + db.close() From 75c7ad89440d2cde6bb68a6ef898ebb5a4bbcda9 Mon Sep 17 00:00:00 2001 From: Ted Henriksson Date: Mon, 10 Apr 2017 20:34:55 +0200 Subject: [PATCH 05/17] Simple fix so that we find the db "dynamically" when executing from cron. --- logout_all.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/logout_all.py b/logout_all.py index 5ba16ed..5b2370b 100755 --- a/logout_all.py +++ b/logout_all.py @@ -1,5 +1,10 @@ import sqlite3 as lite -con = lite.connect('People.db') +import os + +path, _ = os.path.split(os.path.realpath(__file__)) +db_path = os.path.join(path, 'People.db') + +con = lite.connect(db_path) with con: cur = con.cursor() cur.execute("UPDATE People SET isHere = 0") From 476e79f79d2a9bbad38d003d29672fdf90b86fee Mon Sep 17 00:00:00 2001 From: Ted Henriksson Date: Tue, 11 Apr 2017 13:00:39 +0200 Subject: [PATCH 06/17] Uppdated model to have more pythonific variable names --- models.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/models.py b/models.py index c214972..3aa58bc 100644 --- a/models.py +++ b/models.py @@ -2,12 +2,13 @@ db = SqliteDatabase('People.db', **{}) + class Person(Model): nick = TextField(db_column='Nick', null=False) - blipId = IntegerField(db_column='blipId', null=False) - ishere = BooleanField(db_column='isHere', null=False, default=False) - lastlogin = FloatField(db_column='lastLogin', null=False) # FLOAT - totaltime = FloatField(db_column='totalTime', null=True) # FLOAT + blip_id = IntegerField(db_column='blipId', null=False) + is_here = BooleanField(db_column='isHere', null=False, default=False) + last_login = FloatField(db_column='lastLogin', null=False, default=0.0) # FLOAT + total_time = FloatField(db_column='totalTime', null=True, default=0.0) # FLOAT class Meta: database = db From 64f4c8c7555681773ffb0c20bb3505552a5a9f8b Mon Sep 17 00:00:00 2001 From: Ted Henriksson Date: Tue, 11 Apr 2017 13:02:18 +0200 Subject: [PATCH 07/17] updated setup_db.py to handle renamed model. Fixed bug where it tired backingup non-existant People.db --- setup_db.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/setup_db.py b/setup_db.py index 44156b0..5861148 100644 --- a/setup_db.py +++ b/setup_db.py @@ -2,7 +2,6 @@ # -*- coding: utf-8 -*- """ Dev script to setup a test database. """ -import sqlite3 as lite import time import argparse import os @@ -25,17 +24,18 @@ args = parser.parse_args() - if os.path.isfile(db_file) and args.remove: - os.remove(db_file) - else: # Backup db - os.rename(db_file, db_file + ".bak_" + time.strftime("%Y%m%d-%H:%M")) + if os.path.isfile(db_file): + if args.remove: + os.remove(db_file) + else: # Backup db + os.rename(db_file, db_file + ".bak_" + time.strftime("%Y%m%d-%H:%M")) db.connect() db.create_tables([Person]) if args.action == 'dev': - tester = Person(nick='tester', blipId=1234, ishere = False) + tester = Person(nick='tester', blip_id=1234, is_here=False) tester.lastlogin = time.time() tester.totaltime = 0 tester.save() From fa0ccfa29b4a1acb47f08618014876f3260c2a17 Mon Sep 17 00:00:00 2001 From: Ted Henriksson Date: Tue, 11 Apr 2017 13:10:04 +0200 Subject: [PATCH 08/17] Blipper.py converted to peewee, exact same functionallity but better code. --- blipper.py | 99 ++++++++++++++++++------------------------------------ 1 file changed, 33 insertions(+), 66 deletions(-) diff --git a/blipper.py b/blipper.py index 7fed8c4..0ea74cd 100644 --- a/blipper.py +++ b/blipper.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/python3 # -*- coding: utf-8 -*- """Simple script for registering members coming and going. """ @@ -9,34 +9,42 @@ db = SqliteDatabase('People.db', **{}) -def login(user): +def login_logout(person: Person): + if person.is_here: + person.is_here = False + time_spent = time.time() - person.last_login + person.total_time = person.total_time + time_spent + print('-----------------------------------------------') + print('Goodbye ' + person.nick + ' your highscore is: ' + + str(person.total_time)) + print('-----------------------------------------------') + print(person.save()) + else: + person.is_here = True + person.last_login = time.time() - if user.ishere: - user.ishere = False - user. print("-----------------------------------------------") - print("Goodbye " + user.nick + " your highscore is: " + - user.totaltime) + print("Welcome " + person.nick) print("-----------------------------------------------") - else: - pass + person.save() -def createPerson(rfId): - print("-----------------------------------------------") - print('There is no rfidtag named ', rfId, ' creating instance!') + +def create_person(rf_id: int): + print('-----------------------------------------------') + print('There is no rfidtag named ', rf_id, ' creating instance!') nick = input('Input your nick: ') - new_member = Person.create(nick=nick) - new_member.lastlogin = time.time() - new_member.blipId = rfId - new_member.ishere = True - new_member.totaltime = 0 + new_member = Person(nick=nick) + new_member.last_login = time.time() + new_member.blip_id = rf_id + new_member.is_here = True + new_member.total_time = 0 new_member.save() - print('you now exist and are logged in! dont forget to logout!') - print("-----------------------------------------------") + print('you now exist and are logged in! don\'t forget to logout!') + print('-----------------------------------------------') if __name__ == '__main__': @@ -50,53 +58,12 @@ def createPerson(rfId): break except ValueError: print("Blip not recognised") - print("") + + print('') try: - user = Person.get(Person.blipId == rfId) - login(user) + print('Getting ' + str(rfId)) + user = Person.get(Person.blip_id == rfId) + login_logout(user) except Person.DoesNotExist: - createPerson(rfId) - - # con = lite.connect('People.db') - # with con: - # cur = con.cursor() - # cur.execute("SELECT * FROM People WHERE blipId = ?", (rfId,)) - # data = cur.fetchone() - - # if data is None: # there is no user with this ID tag - # print("-----------------------------------------------") - # print('There is no rfidtag named ', rfId, ' creating instance!') - - # nick_temp = input("input your nick: ") - # temp = cur.lastrowid - # if temp is None: - # temp_id = 1 - # else: - # temp_id = temp + 1 - - # cur.execute("INSERT INTO People VALUES (?,?,?,?,?,?);", - # (temp_id, rfId, nick_temp, 1, 0, time.time())) - # print('you now exist and are logged in! dont forget to logout!') - # print("-----------------------------------------------") - # else: # there is user with this ID tag - # if data[3] is 1: # is logged in => log hen out - # time_spent = time.time() - data[5] - # new_total_time = time_spent + data[4] - # cur.execute("UPDATE People SET totalTime=? WHERE blipId=?", - # (new_total_time, rfId)) - # cur.execute("UPDATE People SET isHere =? WHERE blipId=?", - # (0, rfId)) - # print("-----------------------------------------------") - # print("Goodbye " + str(data[2]) + " your highscore is: " + - # str(new_total_time)) - # print("-----------------------------------------------") - - # else: # is not logged in => log hen in - # cur.execute("UPDATE People SET lastLogin =? WHERE blipId=?", - # (time.time(), rfId)) - # cur.execute("UPDATE People SET isHere =? WHERE blipId=?", - # (1, rfId)) - # print("-----------------------------------------------") - # print("Welcome " + str(data[2])) - # print("-----------------------------------------------") + create_person(rfId) From 9a0678c91544e4c4ffc9484be16ba3af2325c669 Mon Sep 17 00:00:00 2001 From: Ted Henriksson Date: Tue, 11 Apr 2017 13:11:09 +0200 Subject: [PATCH 09/17] Highscore.py converted to peewee. --- HighScore.py | 32 ++++++++++++++------------------ 1 file changed, 14 insertions(+), 18 deletions(-) diff --git a/HighScore.py b/HighScore.py index 0238600..bb48f44 100644 --- a/HighScore.py +++ b/HighScore.py @@ -1,32 +1,28 @@ -#!/usr/bin/python +#!/usr/bin/python3 # -*- coding: utf-8 -*- - -import sqlite3 as lite +import itertools +from peewee import * +from models import Person import os import time +db = SqliteDatabase('People.db', **{}) + while True: os.system('clear') - con = lite.connect('People.db') - with con: - cur = con.cursor() - - print("------------ Highscore -----------") - cur.execute("SELECT * FROM People ORDER BY totalTime DESC") - rows = cur.fetchall() + print('{:-^39}'.format('High score')) - for i in range(0, len(rows)): - print(str(i+1) + ": " + str(rows[i][2]).ljust(10) + - " score: " + str(rows[i][4])) + high_score = Person.select().order_by(Person.total_time.desc()) - print("------------- People online ------") + for person, i in zip(high_score, itertools.count(start=1)): + print('{:>2}: {:<14} score: {:>13f}'.format(i, person.nick, person.total_time)) - cur.execute("SELECT * FROM People WHERE isHere = 1") - rows = cur.fetchall() + print('{:-^39}'.format('People online')) - for row in rows: - print(str(row[2]).ljust(10)) + online_persons = Person.select().where(Person.is_here == True) + for person in online_persons: + print(person.nick) time.sleep(15) From c7d73ca6f42387d2271cc8dde9a32ea4684d75c3 Mon Sep 17 00:00:00 2001 From: Ted Henriksson Date: Tue, 11 Apr 2017 13:40:51 +0200 Subject: [PATCH 10/17] Converted to .format strings --- blipper.py | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/blipper.py b/blipper.py index 0ea74cd..d41fa23 100644 --- a/blipper.py +++ b/blipper.py @@ -15,25 +15,25 @@ def login_logout(person: Person): time_spent = time.time() - person.last_login person.total_time = person.total_time + time_spent - print('-----------------------------------------------') - print('Goodbye ' + person.nick + ' your highscore is: ' + - str(person.total_time)) - print('-----------------------------------------------') - print(person.save()) + print('{:-^47}'.format('')) + print('Goodbye {} your highscore is: {:f}'.format(person.nick, person.total_time)) + print('{:-^47}'.format('')) + person.save() + else: person.is_here = True person.last_login = time.time() - print("-----------------------------------------------") - print("Welcome " + person.nick) - print("-----------------------------------------------") + print('{:-^47}'.format('')) + print('Welcome {}'.format(person.nick)) + print('{:-^47}'.format('')) person.save() def create_person(rf_id: int): - print('-----------------------------------------------') - print('There is no rfidtag named ', rf_id, ' creating instance!') + print('{:-^47}'.format('')) + print('There is no rfidtag named {} creating instance!'.format(rf_id)) nick = input('Input your nick: ') new_member = Person(nick=nick) @@ -44,7 +44,7 @@ def create_person(rf_id: int): new_member.save() print('you now exist and are logged in! don\'t forget to logout!') - print('-----------------------------------------------') + print('{:-^47}'.format('')) if __name__ == '__main__': From 4ee93222a3f4cc248bf6d499f662e3b65cc6b6c7 Mon Sep 17 00:00:00 2001 From: Ted Henriksson Date: Tue, 11 Apr 2017 13:42:58 +0200 Subject: [PATCH 11/17] Added short description to Highscore.py --- HighScore.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/HighScore.py b/HighScore.py index bb48f44..d6239f9 100644 --- a/HighScore.py +++ b/HighScore.py @@ -1,6 +1,10 @@ #!/usr/bin/python3 # -*- coding: utf-8 -*- +""" +Simple script to display the current High score and also who is currently logged in. +""" + import itertools from peewee import * from models import Person From 421005c561b329783aef04b69e3df1d48e45ba65 Mon Sep 17 00:00:00 2001 From: Ted Henriksson Date: Tue, 11 Apr 2017 13:44:51 +0200 Subject: [PATCH 12/17] Ignore *pyc and *.swp --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index 3c536f7..dd7261c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ People.db .idea __pycache__ +*.pyc +*.swp From 370014b1343d821964f2c138909c13b15a91c0cb Mon Sep 17 00:00:00 2001 From: Ted Henriksson Date: Tue, 11 Apr 2017 17:51:32 +0200 Subject: [PATCH 13/17] Removed debug print. --- blipper.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/blipper.py b/blipper.py index d41fa23..76478c7 100644 --- a/blipper.py +++ b/blipper.py @@ -18,6 +18,7 @@ def login_logout(person: Person): print('{:-^47}'.format('')) print('Goodbye {} your highscore is: {:f}'.format(person.nick, person.total_time)) print('{:-^47}'.format('')) + person.save() else: @@ -62,7 +63,6 @@ def create_person(rf_id: int): print('') try: - print('Getting ' + str(rfId)) user = Person.get(Person.blip_id == rfId) login_logout(user) except Person.DoesNotExist: From 8272f66634407296351e3448575c6460bdb45579 Mon Sep 17 00:00:00 2001 From: Ted Henriksson Date: Tue, 11 Apr 2017 18:38:33 +0200 Subject: [PATCH 14/17] Cleanup from merge, including deom pep8 fixes. --- HighScore.py | 4 ++-- blipper.py | 28 ++++++++++++++-------------- hasher.py | 7 ++++--- setup_db.py | 8 ++++---- 4 files changed, 24 insertions(+), 23 deletions(-) diff --git a/HighScore.py b/HighScore.py index 5c595a6..67f411a 100755 --- a/HighScore.py +++ b/HighScore.py @@ -30,9 +30,9 @@ for person in online_persons: print(person.nick) - # prata med dorropnare och be dem tana + # If there are people present, turn on the lights and vice versa. try: - if len(rows)>0: + if len(online_persons) > 0: requests.get('http://192.168.42.10:5000/light/on', timeout=0.1) else: requests.get('http://192.168.42.10:5000/light/off', timeout=0.1) diff --git a/blipper.py b/blipper.py index 2fb4327..9c4b22e 100755 --- a/blipper.py +++ b/blipper.py @@ -24,11 +24,11 @@ def login_logout(person: Person): person.save() - requests.put('http://127.0.0.1:5001/', json = {'who': str(data[2]), 'what': "logout"}) try: - requests.get('http://192.168.42.12:5000/',timeout=0.001) - except: - print(" ") + requests.put('http://127.0.0.1:5001/', json={'who': person.nick, 'what': "logout"}, timeout=0.001) + requests.get('http://192.168.42.12:5000/', timeout=0.001) + except TimeoutError: + pass else: person.is_here = True @@ -40,11 +40,11 @@ def login_logout(person: Person): person.save() - requests.put('http://127.0.0.1:5001/', json = {'who': str(data[2]), 'what': "login"}) + requests.put('http://127.0.0.1:5001/', json={'who': person.nick, 'what': "login"}) try: - requests.get('http://192.168.42.12:5000/',timeout=0.001) - except: - print(" ") + requests.get('http://192.168.42.12:5000/', timeout=0.001) + except TimeoutError: + pass def create_person(rf_id: int): @@ -60,11 +60,11 @@ def create_person(rf_id: int): new_member.save() - requests.put('http://127.0.0.1:5001/', json = {'who': nick_temp, 'what': "login"}) - try: - requests.get('http://192.168.42.12:5000/',timeout=0.001) - except: - print(" ") + requests.put('http://127.0.0.1:5001/', json={'who': nick, 'what': "login"}) + try: + requests.get('http://192.168.42.12:5000/', timeout=0.001) + except TimeoutError: + pass print('you now exist and are logged in! don\'t forget to logout!') print('{:-^47}'.format('')) @@ -76,7 +76,7 @@ def create_person(rf_id: int): while True: while True: try: - temp = input("Blip me! ") + temp = getpass.getpass("Blip me! ") rfId = hasher.encode(temp) break except ValueError: diff --git a/hasher.py b/hasher.py index 8f41771..1e66f5a 100644 --- a/hasher.py +++ b/hasher.py @@ -1,6 +1,7 @@ import hashlib -salt = "AhBaik4auv3Seihu" +salt = 'AhBaik4auv3Seihu' -def encode(clearString): - return hashlib.sha512(str.encode(salt + clearString)).hexdigest() + +def encode(clear_string): + return hashlib.sha512(str.encode(salt + clear_string)).hexdigest() diff --git a/setup_db.py b/setup_db.py index 7106c3d..9f080f2 100755 --- a/setup_db.py +++ b/setup_db.py @@ -36,10 +36,10 @@ db.create_tables([Person]) if args.action == 'dev': - rf_id = hasher.encode('1234') - tester = Person(nick='tester', blip_id=1234, is_here=False) - tester.lastlogin = time.time() - tester.totaltime = 0 + rf_id = hasher.encode('1234') + tester = Person(nick='tester', blip_id=rf_id, is_here=False) + tester.last_login = time.time() + tester.total_time = 0 tester.save() db.close() From 2636a8fcb3bf7e695a3339def677f0d5afce09a8 Mon Sep 17 00:00:00 2001 From: Ted Henriksson Date: Thu, 26 Oct 2017 12:25:04 +0200 Subject: [PATCH 15/17] Added verion table to model. --- models.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/models.py b/models.py index 3aa58bc..9fd17cb 100644 --- a/models.py +++ b/models.py @@ -13,3 +13,13 @@ class Person(Model): class Meta: database = db db_table = 'People' + + +class DbVersion(Model): + version = IntegerField(db_column='version', null=False) + date_updated = DateTimeField() + date_released = DateTimeField(null=False) + + class Meta: + database = db + db_table = 'DbVersion' From 9dc0d595c64158f4bd253f5bebe7c51e73c9c712 Mon Sep 17 00:00:00 2001 From: Ted Henriksson Date: Fri, 10 Nov 2017 09:59:24 +0100 Subject: [PATCH 16/17] New db models. --- models.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/models.py b/models.py index 9fd17cb..e72c94e 100644 --- a/models.py +++ b/models.py @@ -5,7 +5,7 @@ class Person(Model): nick = TextField(db_column='Nick', null=False) - blip_id = IntegerField(db_column='blipId', null=False) + blip_id = FixedCharField(db_column='blipId', null=False, max_length=128) is_here = BooleanField(db_column='isHere', null=False, default=False) last_login = FloatField(db_column='lastLogin', null=False, default=0.0) # FLOAT total_time = FloatField(db_column='totalTime', null=True, default=0.0) # FLOAT @@ -23,3 +23,16 @@ class DbVersion(Model): class Meta: database = db db_table = 'DbVersion' + + +class LegacyPerson(Model): + Id = IntegerField(db_column='Id', null=False) + nick = TextField(db_column='Nick', null=False) + blip_id = IntegerField(db_column='blipId', null=False) + is_here = BooleanField(db_column='isHere', null=False, default=False) + last_login = FloatField(db_column='lastLogin', null=False, default=0.0) # FLOAT + total_time = FloatField(db_column='totalTime', null=True, default=0.0) # FLOAT + + class Meta: + database = db + db_table = 'People_legacy' From 12ab1dc23c193afacffb34846723e7d539c8571d Mon Sep 17 00:00:00 2001 From: Ted Henriksson Date: Fri, 10 Nov 2017 09:59:55 +0100 Subject: [PATCH 17/17] Created automated DB conversion from legacy to new orm based DB. --- convert_db.py | 121 ++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 98 insertions(+), 23 deletions(-) diff --git a/convert_db.py b/convert_db.py index 41f4e1b..335f694 100644 --- a/convert_db.py +++ b/convert_db.py @@ -1,26 +1,101 @@ import hasher import sqlite3 as lite +import time +import shutil -con = lite.connect('People.db') -con.row_factory = lite.Row - -salt = b"AhBaik4auv3Seihu" - -with con: - - cur = con.cursor() - - cur.execute("SELECT * FROM People;") - - rows = cur.fetchall() - - hashed = [] - - for row in rows: - #hashedId = hashlib.sha512(salt+str.encode(str(row["blipId"]))).hexdigest() - hashedId = hasher.encode(str(row["blipId"])) - hashedRow = [hashedId, row["blipId"]] - hashed.append(hashedRow) - - cur.executemany("UPDATE People SET blipId =? WHERE blipId =?", hashed) - +from models import Person, LegacyPerson, DbVersion +from peewee import * + +db = SqliteDatabase('People.db', **{}) + + +def convert_from_legacy(): + + # check if Colcum Id exist ( and not id) and also that blippId is not sha512 (should be varchar) + # Create Model update 1 + # move data from People to Updated table, while moving update the ID to a functioning one. + # rename People + # rename Updated table to People + + with lite.connect('People.db') as con: + + con.row_factory = lite.Row + cur = con.cursor() + cur.execute('PRAGMA TABLE_INFO({})'.format('People')) + rows = cur.fetchall() + + # See if we can find old table structure. + old_blip = False + old_id = False + + for row in rows: + if row[1] == 'Id' and row[2] == 'INT': + old_id = True + print(row[1], row[2]) + + if row[1] == 'blipId' and row[2] == 'INT': + old_blip = True + print(row[1], row[2]) + + if old_blip and old_id: + # rename table + cur.execute('Alter table People rename to People_legacy') + + # Transfer data with peewee + db.connect() + db.create_tables([Person]) + for user in LegacyPerson.select(): + hash_blip = hasher.encode(str(user.blip_id)) + Person.create(nick=user.nick, blip_id=hash_blip, is_here=user.is_here, + last_login=user.last_login, total_time=user.total_time) + db.close() + + # Check and remove old table + with lite.connect('People.db') as con: + + con.row_factory = lite.Row + cur = con.cursor() + + cur.execute('select * from People') + rows = cur.fetchall() + + people_len = len(rows) + + cur.execute('SELECT * FROM People_legacy') + rows = cur.fetchall() + + legacy_len = len(rows) + + if people_len == legacy_len: + cur.execute('DROP TABLE People_legacy') + + +def check_db_version_and_apply_fixes(): + + + # Check db version + db.connect() + try: + db.create_tables([DbVersion]) + # if there isnt any DbVersion then this is a legacy db + db_version = 0 + except OperationalError: + # Ok at least a managed version of the DB was installed. + + + + if db__version == 0: + backup_db() + convert_from_legacy() + + # Update db version + +def backup_db(): + time_str = str(time.time()) + db_backup_file = 'People_' + time_str + '.db' + + shutil.copy('People.db', db_backup_file) + + +if __name__ == '__main__': + check_db_version_and_apply_fixes() \ No newline at end of file