Prechádzať zdrojové kódy

Make model save to database

Eren Yilmaz 6 rokov pred
rodič
commit
29669999d8
4 zmenil súbory, kde vykonal 88 pridanie a 50 odobranie
  1. 9 6
      client.py
  2. 11 13
      client_controller.py
  3. 64 30
      model.py
  4. 4 1
      server.py

+ 9 - 6
client.py

@@ -8,12 +8,11 @@ from util import debug
 
 def fake_loading_bar(msg,delay=0.100):
     if len(msg) >= 32:
-        raise AssertionError('Loading bar label too larger')
-    msg += ':'
-    msg += ' ' * (32 - len(msg))
+        raise AssertionError('Loading bar label too large')
+    msg += ': '
     print(msg, end='')
     sys.stdout.flush()
-    for _ in range(50):
+    for _ in range(78 - len(msg)):
         if not debug:
             time.sleep(delay)
         print('#', end='')
@@ -51,6 +50,9 @@ To display an overview of available commands type \'help\'.
 ''')
 
 
+allowed_commands = ['login', 'register', 'help']
+
+
 def one_command():
     cmd = input('*> ')
     cmds = cmd.split(';')
@@ -64,6 +66,8 @@ def one_command():
                 method_to_call(*cmd[1:])
             except TypeError:
                 print('Invalid command syntax.')
+            except Exception:
+                print('An error occured while executing a command.')
 
 
 if __name__ == '__main__':
@@ -71,5 +75,4 @@ if __name__ == '__main__':
     welcome()
 
     while True:
-        one_command()
-allowed_commands = ['login', 'register', 'help']
+        one_command()

+ 11 - 13
client_controller.py

@@ -48,24 +48,22 @@ def register(username, password=None):
             password = input('Password: ')
 
     response = client_request('register', {"username": username, "password": password})
-    success = 'session_id' in response
-    if success:
-        connection.session_id = response['session_id']
-        print('Registration successful.')
-    else:
-        if 'error_message' in response:
-            print('Registration failed with message:', response['error_message'])
-        else:
-            print('Registration failed.')
 
+    if 'error_message' in response:
+        print('Registration failed with message:', response['error_message'])
 
+
+# noinspection PyShadowingBuiltins
 def help():
     print('Allowed commands:')
     for cmd in allowed_commands:
         this_module = sys.modules[__name__]
-        method = getattr(this_module, cmd[0])
+        method = getattr(this_module, cmd)
         params = inspect.signature(method).parameters
         num_args = len(params)
-        print(cmd, 'takes the following', num_args, 'arguments:')
-        for p in params:
-            print(' ', p) # TODO print default value
+        if num_args > 0:
+            print('`' + cmd + '`', 'takes the following', num_args, 'arguments:')
+            for p in params:
+                print(' -', p)  # TODO print default value
+        else:
+            print('`' + cmd + '`', 'takes no arguments')

+ 64 - 30
model.py

@@ -1,19 +1,44 @@
+import re
 import sqlite3 as db
 import sys
 import uuid
 
 from game import money_amount
+from util import debug
 
 connection = None
 cursor = None
+db_name = None
 
 
-def connect():
+def query_save_name():
+    global db_name
+    if debug:
+        db_name = 'test.db'
+        return
+    while True:
+        save_name = input('Name of the savegame: ')
+        if re.match(r"[A-Za-z0-9.-]{0,50}", save_name):
+            db_name = save_name + '.db'
+            return
+
+
+def connect(reconnect=False):
     global connection
     global cursor
+    global db_name
+    if reconnect:
+        # connection.commit()
+        # connection.close()
+        cursor = None
+        connection = None
+        db_name = None
+
     if connection is None or cursor is None:
+        query_save_name()
+
         try:
-            connection = db.connect('boerse.db')
+            connection = db.connect(db_name)
 
             cursor = connection.cursor()
 
@@ -31,7 +56,7 @@ def setup():
 
     print('Database setup...')
 
-    replace = True
+    replace = False
 
     if replace:
         print('  Dropping old tables...')
@@ -39,6 +64,7 @@ def setup():
         cursor.execute("DROP TABLE IF EXISTS ownables")
         cursor.execute("DROP TABLE IF EXISTS ownership")
         cursor.execute("DROP TABLE IF EXISTS sessions")
+        cursor.execute("DROP TABLE IF EXISTS transactions")
 
     print('  Creating tables...')
     cursor.execute('''
@@ -68,35 +94,43 @@ def setup():
                     FOREIGN KEY (user_id) REFERENCES users(rowid)
                 )
                 ''')
-
-    print('  Adding initial data...')
-    cursor.execute('''
-                INSERT INTO users
-                (username, password)
-                VALUES ("bank", "")
-                ''')
-    cursor.execute('''
-                SELECT rowid 
-                FROM users
-                WHERE username = "bank"
-                ''')
-    bank_id = cursor.fetchone()[0]
     cursor.execute('''
-                INSERT INTO ownables
-                (name, total_amount)
-                VALUES ("Kollar", ?)
-                ''', (money_amount,))
-    cursor.execute('''
-                SELECT rowid 
-                FROM users
-                WHERE username = "bank"
+                CREATE TABLE IF NOT EXISTS sessions(
+                    user_id INTEGER NOT NULL,
+                    session_id STRING NOT NULL,
+                    FOREIGN KEY (user_id) REFERENCES users(rowid)
+                )
                 ''')
-    kollar_id = cursor.fetchone()[0]
-    cursor.execute('''
-                INSERT INTO ownership
-                (user_id, stock_id, amount)
-                VALUES (?, ?, ?)
-                ''', (bank_id, kollar_id, money_amount))
+
+    if replace:
+        print('  Adding initial data...')
+        cursor.execute('''
+                    INSERT INTO users
+                    (username, password)
+                    VALUES ("bank", "")
+                    ''')
+        cursor.execute('''
+                    SELECT rowid 
+                    FROM users
+                    WHERE username = "bank"
+                    ''')
+        bank_id = cursor.fetchone()[0]
+        cursor.execute('''
+                    INSERT INTO ownables
+                    (name, total_amount)
+                    VALUES ("Kollar", ?)
+                    ''', (money_amount,))
+        cursor.execute('''
+                    SELECT rowid 
+                    FROM users
+                    WHERE username = "bank"
+                    ''')
+        kollar_id = cursor.fetchone()[0]
+        cursor.execute('''
+                    INSERT INTO ownership
+                    (user_id, stock_id, amount)
+                    VALUES (?, ?, ?)
+                    ''', (bank_id, kollar_id, money_amount))
 
 
 def login(username, password):

+ 4 - 1
server.py

@@ -23,8 +23,11 @@ if __name__ == '__main__':
         response.content_type = 'application/json'
         method_to_call = getattr(server_controller, path)
         try:
-            return method_to_call()
+            resp = method_to_call()
+            model.connection.commit()
+            return resp
         except sqlite3.IntegrityError:
             return server_controller.bad_request('action violates database constraints')
 
     run(host='localhost', port=connection.port, debug=debug)
+    model.db.connection.disconnect()