def update(self, username = None, password = None) : if username and username != self.username : Database.updateUsername(self.username, username) self.username = username if password and password != self.password : Database.updatePassword(self.username, password) self.password = password
def create_tsne(): database = Database(os.environ[DATABASE_URL], os.environ[DATABASE_REPLICA_SET], os.environ[DATABASE_PORT], os.environ[DATABASE_NAME]) request_validator = UserRequest(database) request_errors = analyse_request_errors(request_validator, request.json[PARENT_FILENAME_NAME], request.json[TSNE_FILENAME_NAME], request.json[LABEL_NAME]) if request_errors is not None: return request_errors database_url_input = Database.collection_database_url( os.environ[DATABASE_URL], os.environ[DATABASE_NAME], request.json[PARENT_FILENAME_NAME], os.environ[DATABASE_REPLICA_SET], ) thread_pool.submit(tsne_async_processing, database_url_input, request.json[LABEL_NAME], request.json[TSNE_FILENAME_NAME]) return ( jsonify({ MESSAGE_RESULT: MICROSERVICE_URI_GET + request.json[TSNE_FILENAME_NAME] }), HTTP_STATUS_CODE_SUCCESS_CREATED, )
def setup_method(self): """ Creates a dummy database for tests """ # Creates database Database.TEST_MODE = True Database.on() self.cursor = Database.CURSOR # Create tables self.params = models.Params(autoload=False) self.products = models.Products() self.groceries = models.Groceries() self.params.create_table() self.products.create_table() self.groceries.create_table() # Insert dummy data self.default_barcode = '123456789ABCD' self.default_name = 'Lorem Ipsum' self.default_pic = 'PIC' self.params.add_item('foo', 'bar') self.products.add_item(self.default_barcode, self.default_name, self.default_pic) self.groceries.add_item(self.default_barcode, 1)
def setup_method(self): """ Setup method : - Sets database to test mode and populates it - Launches Flask in test mode """ # Database Database.TEST_MODE = True Database.on() # Create test database models.Params(autoload=False).create_table() models.Products().create_table() models.Groceries().create_table() # Params : user config self.password_raw = 'abcdefg' self.password_sha1 = bytearray(self.password_raw, encoding='utf-8') self.password_sha1 = hashlib.sha1(self.password_sha1).hexdigest() params = models.Params() params.add_item('user_password', self.password_sha1) params.add_item('lang', 'en') # Products : 1 sample item self.default_barcode = '1234567890123' self.default_name = 'Lorem Ipsum' models.Products().add_item(self.default_barcode, self.default_name, True) # Groceries : 1 sample item models.Groceries().add_item(self.default_barcode, 1)
def main(): global ssn, folder runbool = True while runbool: mkdir() ssn = None print("Program started") while not ssnreceived(): print('waiting for ssn') rec = Recorder(ssn,folder) rec.run() stop = None while stop is None: stop = input('Enter something to stop the recording') print(' ') if str(stop.strip()) == 'stop': runbool = False time.sleep(0.2) print(stop) if rec is not None: rec.stop() filename = ssn if os.path.isfile(folder + filename + '.wav'): db = Database(folder, ssn, filename) db.upload() db.adduser() db.addfile() db.addfiletouser() else: print('Not added to database')
def login(): """ Landing page. Launches and handles login form if needed. """ # Database access + loads basic info Database.on() params = models.Params() lang = utils.Lang(params.lang) Database.off() # Prepare template data data = {'lang': lang.__dict__, 'body_class': 'login', 'error': False} # If the user is already logged : go to "grocery_list" if 'is_logged' in session and session['is_logged']: return redirect(url_for('groceries')) # Handle post data if request.form and 'password' in request.form: password = request.form['password'] password = bytearray(password, encoding='utf-8') password = hashlib.sha1(password).hexdigest() # Right password if password == params.user_password: session['is_logged'] = True return redirect(url_for('groceries')) # Wrong password else: data['error'] = True return render_template('login.html', **data)
def create_model(): database_url = os.environ[DATABASE_URL] database_replica_set = os.environ[DATABASE_REPLICA_SET] database_name = os.environ[DATABASE_NAME] train_filename = request.json[TRAINING_FILENAME] test_filename = request.json[TEST_FILENAME] classifiers_name = request.json[CLASSIFIERS_NAME] database = Database( database_url, database_replica_set, os.environ[DATABASE_PORT], database_name, ) request_validator = UserRequest(database) request_errors = analyse_request_errors( request_validator, train_filename, test_filename, classifiers_name) if request_errors is not None: return request_errors database_url_training = Database.collection_database_url( database_url, database_name, train_filename, database_replica_set, ) database_url_test = Database.collection_database_url( database_url, database_name, test_filename, database_replica_set, ) metadata_creator = Metadata(database, train_filename, test_filename) model_builder = Model(database, metadata_creator, database_url_training, database_url_test) model_builder.build( request.json[MODELING_CODE_NAME], classifiers_name ) return ( jsonify({ MESSAGE_RESULT: create_prediction_files_uri( classifiers_name, test_filename)}), HTTP_STATUS_CODE_SUCCESS_CREATED, )
def open_investigation(self): """Open investigation data""" db = Database() investigation_ids = db.retrieve_investigation_ids() if not investigation_ids: messagebox.showinfo("No saved investigations", "Please save an investigation before loading data") db.close_connection() if investigation_ids: # clear investigation id self.investigation_id_tracker = "" self.open = OpenTool() self.open.title('Open investigation') self.open.geometry('+%d+%d' % (root.winfo_x() + 20, root.winfo_y() + 20)) if sys.platform == "win32": self.open.iconbitmap(self.icon) self.open.resizable(width=False, height=False) self.open.protocol('WM_DELETE_WINDOW', self.open.quit_open) # set focus on window self.open.grab_set() self.open.focus() # start mainloop self.open.mainloop()
class SaveTool(tk.Toplevel): """Opens a window to store investigation data""" def __init__(self, master=None, investigation_id=None, data=None, *args, **kwargs): """Initializes Toplevel object and builds interface""" super().__init__(master, *args, **kwargs) # initialize variables self.investigation_id = investigation_id self.data = data # initialize database self.db_handler = Database() # hide window in background during drawing and load, to prevent flickering and glitches during frame load self.withdraw() # build and draw the window self.build() # unhide the Toplevel window immediately after draw and load self.after(0, self.deiconify) def build(self): """Initializes and builds application widgets""" # create input labelframe labelframe_1 = tk.LabelFrame(self, fg='brown') labelframe_1.pack(side="top", expand='yes', fill='both', padx=2, pady=2, anchor="n") # create explanation label self.label = tk.Label(labelframe_1, text='Save As...') self.label.pack(expand=True, fill='x', side="left", padx=2, pady=2) # create data input entry widget self.entry = tk.Entry(labelframe_1) self.entry.pack(expand=True, fill='x', side="left", padx=2, pady=2) # create save button self.save_button = tk.Button(labelframe_1, text="Save", command=self.save_data) self.save_button.pack(expand=False, side="left", padx=2, pady=2, anchor="e") # create cancel button self.cancel_button = tk.Button(labelframe_1, text="Cancel", command=self.quit_save) self.cancel_button.pack(expand=False, side="left", padx=2, pady=2, anchor="e") self.entry.insert(0, self.investigation_id) def save_data(self): """Stores investigation data within database""" if self.data: try: self.db_handler.store_investigation(self.entry.get(), self.data) messagebox.showinfo("Success", "Successfully saved investigation") self.quit_save() except Exception: messagebox.showerror("Error saving data", "Failed to save data!") self.quit_save() else: messagebox.showinfo("No data", "There is no data to save") def quit_save(self): """Quits the save window""" self.db_handler.close_connection() self.destroy()
def __init__(self): """ Constructor :rtype: GroceriesTable """ # Is the database connexion initialized ? if not Database.is_ready(): Database.on()
def add(username, info) : course = Course( info.get("name"), _formatDate(info.get("date")), _formatTime(info.get("time_start"), info.get("time_end")), info.get("role") ) Database.storeCourse(username, course)
def __init__(self, master=None, *args, **kwargs): """Initializes Toplevel object and builds interface""" super().__init__(master, *args, **kwargs) self.db_handler = Database() # hide window in background during drawing and load, to prevent flickering and glitches during frame load self.withdraw() # build and draw the window self.build() # unhide the Toplevel window immediately after draw and load self.after(0, self.deiconify)
def __init__(self, master=None, *args, **kwargs): """Initializes Toplevel object and builds credit interface.""" super().__init__(master, *args, **kwargs) self.db_handler = Database() # hide window in background during drawing and load, to prevent flickering and glitches as per # https://stackoverflow.com/questions/48492273/preloading-windows-to-avoid-tkinter-visual-glitches-during-frame-load self.withdraw() # build and draw the window self.build() # unhide the Toplevel window immediately after draw and load self.after(0, self.deiconify)
def api_products_edit(barcode, name): """ API method : Add/Edit/Delete items from the products database. If an item doesn't exist, it will be created. Outputs JSON. :param barcode: An unknown product barcode :param name: The new product's name JSON format : - {"status": ..., "barcode" ..., "name": ...} Possible return status : - ADDED (200) / ADD ERROR (400) - EDITED (200) / EDIT ERROR (400) """ # AJAX Auth check if not ('is_logged' in session and session['is_logged']): return render_template('json.html', json="{}"), 401 # Remove unwanted chars to_escape = ['"', "<", ">", "&", "'"] for char in to_escape: barcode = barcode.replace(char, '') name = name.replace(char, '') # Output data = {"status": "", "barcode": barcode, "name": name} # Database access Database.on() products_db = models.Products() # Try to get the entry in the grocery list exists = products_db.get_item(barcode) status_code = 200 # If it doesn't exist : add it if not exists: try: products_db.add_item(barcode, name, False) data['status'] = 'ADDED' except Exception as trace: data['status'] = 'ADD ERROR' status_code = 400 # If it exists : edit it else: try: products_db.edit_item(barcode, name, exists['pic']) data['status'] = 'EDITED' except Exception as trace: data['status'] = 'EDIT ERROR' status_code = 400 # Database : off and outputs data Database.off() return render_template('json.html', json=json.dumps(data)), status_code
def api_lang(): """ Returns JSON of the lang file """ # Database access + loads basic info Database.on() lang = utils.Lang(models.Params().lang) lang = lang.__dict__ Database.off() # Return template return render_template('json.html', json=json.dumps(lang))
def create_projection(): database_url = os.environ[DATABASE_URL] database_replica_set = os.environ[DATABASE_REPLICA_SET] database_name = os.environ[DATABASE_NAME] parent_filename = request.json[PARENT_FILENAME_NAME] projection_filename = request.json[PROJECTION_FILENAME_NAME] projection_fields = request.json[FIELDS_NAME] database = Database( database_url, database_replica_set, os.environ[DATABASE_PORT], database_name, ) request_validator = UserRequest(database) request_errors = analyse_request_errors(request_validator, parent_filename, projection_filename, projection_fields) if request_errors is not None: return request_errors database_url_input = Database.collection_database_url( database_url, database_name, parent_filename, database_replica_set, ) database_url_output = Database.collection_database_url( database_url, database_name, projection_filename, database_replica_set, ) metadata_creator = Metadata(database) projection = Projection(metadata_creator, database_url_input, database_url_output) projection.create(parent_filename, projection_filename, projection_fields) return ( jsonify({ MESSAGE_RESULT: MICROSERVICE_URI_GET + projection_filename + MICROSERVICE_URI_GET_PARAMS }), HTTP_STATUS_CODE_SUCCESS_CREATED, )
def __init__(self, autoload=True): """ Constructor :param autoload: Automaticaly load parameters as attributes ? :rtype: ParamsTable """ # Is the database connexion initialized ? if not Database.is_ready(): Database.on() # Load parameters as attributes if autoload: self.load()
def __init__(self): self.db = Database() if self.db.get('latest'): self.height = int(self.db.get('latest')) self.prev_block = pickle.loads(self.db.get(int( self.height))) # gonna creat a new block else: genesis_block = Block(0, 'This is the Genesis block baeeeee', '') genesis_block.time = '0' self.prev_block = genesis_block.pow_of_block() self.db.put(0, pickle.dumps(self.prev_block)) self.db.put('latest', 0) self.height = 0
def api_products_list_key(api): """ API method : Gets all items from the products table. Outputs JSON. Returns the latest version of the grocery list. JSON format : - {"status": ..., "items" ...} Possible return status : - OK (200) """ # AJAX Auth check Database.on() # Load parameters params = models.Params() # Database : end connection # (open it only when needed because this program is meant to be shutdown harshly) Database.off() # Database access api_key = params.api_key if api_key != api: return render_template('json.html', json="{}"), 401 # Output data = {"status": "OK", "items": []} # Get info Database.on() data['items'] = models.Products().get_list() Database.off() # Render return render_template('json.html', json=json.dumps(data))
def generate(user, courses, selected, destructive) : grouped = list() for course in courses : day, month, year = course.date.split(".") month = Config.Months[month] if [month, year] in selected : if year not in _keys(grouped) : grouped.append((year, list())) if month not in _keys(_values(grouped, year)) : _values(grouped, year).append((month, list())) _values(_values(grouped, year), month).append(course) if destructive : Database.deleteCourse(user.username, course.id) return storeWithId(user, grouped)
def register(): if request.method == 'POST': params = ( request.form['regEmail'], request.form['regPassword'], request.form['regFirstname'], request.form['regLastname'], request.form['departmentCode'], request.form['accountType']) sproc = """[usr].[CreateUser] @Email = ?, @Password= ?, @FirstName = ?, @LastName = ?, @DepartmentCode = ?, @isStaff = ?""" Database.execute_query(sproc, params) return redirect(url_for('auth.Auth'))
def getAll(user) : data = Database.loadSheets(user.username) sheets = [ Sheet(user, pickle.loads(b64decode(cdata)), sid) for cdata, sid in data ] return sheets
def getAllUsers(): query = "SELECT * FROM [StoreManagement].[usr].[User]" rows = Database.get_rows(query) users = [] for row in rows: print(row) return users
def products(): """ Shows PRODUCTS template if the user is logged. """ # Auth check if 'is_logged' not in session or not session['is_logged']: return redirect(url_for('login')) # Database access + loads basic info Database.on() lang = utils.Lang(models.Params().lang) Database.off() # Prepare template data data = {'lang': lang.__dict__, 'body_class': 'products'} # Return template return render_template('products.html', **data)
def login(): if request.method == 'POST': sproc = "[usr].[UserLogin] @Email = ?, @Password= ?" user_email = request.form['email'] params = (user_email, request.form['password']) result = Database.execute_query(sproc, params) if "Login successful" == result[0][0]: sproc = "[usr].[getUser] @Email = ?" session['email'] = user_email params = user_email result = Database.execute_query(sproc, params) is_admin = result[0][4] if is_admin: return redirect('/admin') else: return redirect('/basket') return redirect('/auth')
def create_prediction_files_uri(classifiers_list, test_filename): classifiers_uri = [] for classifier in classifiers_list: classifiers_uri.append( MICROSERVICE_URI_GET + Database.create_prediction_filename(test_filename, classifier) + MICROSERVICE_URI_GET_PARAMS) return classifiers_uri
def execute(form) : query = form.get("query") res = None try : res = Database.exeq(query) except Exception as e : flash(e, Config.Flash.error) else : flash(u"Befehl erfolgreich ausgeführt!", Config.Flash.success) return view(query, res)
def setup_method(self): """ Setup method, creates a dummy database """ # Creates test database Database.TEST_MODE = True Database.on() self.cursor = Database.CURSOR # Create tables models.Params(autoload=False).create_table() models.Products().create_table() models.Groceries().create_table() # Defaults barcodes self.valid_barcode = '3017620424403' self.invalid_barcode = '123456789ABCD' # Deconnects database to let threads use them Database.off()
def render_chart(): try: sensors = [ r.sensor_id for r in Database().get_instance().session.query( Climate.sensor_id).distinct() ] last = Climate.query.order_by(Climate.date.desc()).first() return render_template('charts.html', sensors=sensors, measurement=last) except TemplateNotFound: abort(404)
def climate_add(): temp = request.form.get('tmp') or request.args.get('tmp') or request.json.get('tmp') humidity = request.form.get('hmd') or request.args.get('hmd') or request.json.get('hmd') sensor_id = request.form.get('sensor') or request.args.get('sensor') or request.json.get('sensor') date = datetime.now() try: climate_record = Climate() climate_record.temperature = float(temp) climate_record.humidity = float(humidity) # TODO: remove hardcoded id climate_record.hub_id = 1 climate_record.sensor_id = int(sensor_id) climate_record.date = date Database().get_instance().session.add(climate_record) Database().get_instance().session.commit() return '', 200 except Exception as e: return jsonify({'error': str(e)}), 501
def create_projection(): parent_filename = request.json[PARENT_FILENAME_NAME] projection_filename = request.json[PROJECTION_FILENAME_NAME] projection_fields = request.json[FIELDS_NAME] request_errors = analyse_request_errors(request_validator, parent_filename, projection_filename, projection_fields) if request_errors is not None: return request_errors database_url_input = Database.collection_database_url( database_url, database_name, parent_filename, database_replica_set, ) database_url_output = Database.collection_database_url( database_url, database_name, projection_filename, database_replica_set, ) metadata_creator = Metadata(database) projection = Projection(metadata_creator, database_url_input, database_url_output) projection.create(parent_filename, projection_filename, projection_fields) return ( jsonify({ MESSAGE_RESULT: f'{MICROSERVICE_URI_GET}{projection_filename}' f'{MICROSERVICE_URI_GET_PARAMS}' }), HTTP_STATUS_CODE_SUCCESS_CREATED, )
class DeleteTool(tk.Toplevel): """Opens a window to retrieve investigation data""" def __init__(self, master=None, *args, **kwargs): """Initializes Toplevel object and builds interface""" super().__init__(master, *args, **kwargs) # initialize variables self.selection = tk.StringVar(self) # initialize database self.db_handler = Database() # hide window in background during drawing and load, to prevent flickering and glitches during frame load self.withdraw() # build and draw the window self.build() # unhide the Toplevel window immediately after draw and load self.after(0, self.deiconify) def build(self): """Initializes and builds application widgets""" # create input labelframe labelframe_1 = tk.LabelFrame(self, fg='brown') labelframe_1.pack(side="top", expand='yes', fill='both', padx=2, pady=2, anchor="n") # create explanation label self.label = tk.Label(labelframe_1, text='Delete...') self.label.pack(expand=True, fill='x', side="left", padx=2, pady=2) # create data input entry widget self.options = tk.OptionMenu(labelframe_1, self.selection, *self.db_handler.retrieve_investigation_ids(), command=self.delete_data) self.options.pack(expand=True, fill='x', side="left", padx=2, pady=2) self.selection.set(self.db_handler.retrieve_investigation_ids()[0]) # create save button self.save_button = tk.Button(labelframe_1, text="Delete", command=self.delete_data) self.save_button.pack(expand=False, side="left", padx=2, pady=2, anchor="e") # create cancel button self.cancel_button = tk.Button(labelframe_1, text="Cancel", command=self.quit) self.cancel_button.pack(expand=False, side="left", padx=2, pady=2, anchor="e") def delete_data(self, value=None): """Deletes investigation data from database""" if value: investigation_id = value else: investigation_id = self.selection.get() try: self.db_handler.delete_investigation(investigation_id) self.quit() except Exception as e: print("[*] Error: ", e) self.quit() def quit(self): """Quits the open window""" self.db_handler.close_connection() self.destroy()
def groceries(): """ Shows GROCERIES template if the user is logged. """ # Auth check if 'is_logged' not in session or not session['is_logged']: return redirect(url_for('login')) # Database access + loads basic info Database.on() lang = utils.Lang(models.Params().lang) items = models.Products().get_list() Database.off() # Prepare template data data = { 'lang': lang.__dict__, 'body_class': 'groceries', 'products_list': items } # Return template return render_template('groceries.html', **data)
def create_model(): train_filename = request.json[TRAINING_FILENAME] test_filename = request.json[TEST_FILENAME] classifiers_name = request.json[CLASSIFIERS_NAME] request_errors = analyse_request_errors(request_validator, train_filename, test_filename, classifiers_name) if request_errors is not None: return request_errors database_url_training = Database.collection_database_url( database_url, database_name, train_filename, database_replica_set, ) database_url_test = Database.collection_database_url( database_url, database_name, test_filename, database_replica_set, ) builder = Builder(database, metadata_creator, spark_session) builder.build(request.json[MODELING_CODE_NAME], classifiers_name, train_filename, test_filename, database_url_training, database_url_test) return ( jsonify({ MESSAGE_RESULT: create_prediction_files_uri(classifiers_name, test_filename) }), HTTP_STATUS_CODE_SUCCESS_CREATED, )
def api_products_delete(barcode): """ API method : Deletes an item from the products table. Outputs JSON. Returns the latest version of the grocery list. JSON format : - {"status": ...} Possible return status : - OK (200) - DELETE ERROR (400) """ # AJAX Auth check if not ('is_logged' in session and session['is_logged']): return render_template('json.html', json="{}"), 401 # Remove unwanted chars to_escape = ['"', "<", ">", "&", "'"] for char in to_escape: barcode = barcode.replace(char, '') # Output data = {"status": "OK"} # Try to delete Database.on() try: models.Products().delete_item(barcode) data['status'] = 'OK' status_code = 200 except Exception as trace: data['status'] = 'DELETE ERROR' status_code = 400 Database.off() # Render return render_template('json.html', json=json.dumps(data)), status_code
def createTables(log = Log.info) : log("Creating table 'users'...") Database.exeq("CREATE TABLE users (username varchar(255) PRIMARY KEY, password varchar(255), role varchar(255));") log("Table 'users' created.") log("Creating table 'courses'...") Database.exeq("CREATE TABLE courses (id serial PRIMARY KEY, username varchar(255) REFERENCES users (username) ON UPDATE CASCADE ON DELETE CASCADE, name varchar(255), date varchar(255), time varchar(255), role varchar(255));") log("Table 'courses' created.") log("Creating table 'sheets'...") Database.exeq("CREATE TABLE sheets (id serial PRIMARY KEY, username varchar(255) REFERENCES users (username) ON UPDATE CASCADE ON DELETE CASCADE, courses text);") log("Table 'sheets' created.")
def get(self) : if self.exists() : username = cookie.get(self.key) data = Database.loadUser(username) if data : return self.UserCls(*data)
def grantAdminRights(log = Log.info) : log("Granting admin rights to all users...") Database.exeq("UPDATE users SET role=%s;", Config.User.Roles.admin) log("Rights granted.")
def delete(username, id) : Database.deleteCourse(username, id)
def getAll(username) : data = Database.loadCourses(username) courses = [Course(*obj) for obj in data] return sorted(courses, key = _sortDate, reverse = True)
def deleteAll(username) : Database.deleteCourses(username)
def storeWithId(user, courses) : data = b64encode(pickle.dumps(courses)).decode(Config.encoding) sid = Database.storeSheetWithId(user.username, data) return sid
def getById(user, sid) : data, sid = Database.loadSheet(user.username, sid) courses = pickle.loads(b64decode(data)) sheet = Sheet(user, courses, sid) return sheet
def get_db_cursor(cls, config): db = Database(**config) return db._connect(), db._conn.cursor()
def getByRegister(credentials) : username, password = credentials.get("username"), credentials.get("password") if not Database.existsUser(username) : user = User(username, Hash.hash(password)) Database.storeUser(user) return user
def delete(username, sid) : Database.deleteSheet(username, sid)
def getByLogin(credentials) : data = Database.loadUserByLogin(credentials.get("username"), Hash.hash(credentials.get("password"))) if data : user = User(*data) return user