From 50fcf096eb8be20c9a0de9c5d50f4bcb59b85d4a Mon Sep 17 00:00:00 2001 From: Jan Date: Sun, 19 May 2024 13:58:48 +0200 Subject: [PATCH] =?UTF-8?q?Bisschen=20aufr=C3=A4umen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- slaeforms/app.py | 210 ++++++++++------------------- slaeforms/dbtables.py | 12 -- slaeforms/static/attributions.txt | 5 + slaeforms/templates/all_links.html | 20 +++ slaeforms/templates/data.html | 31 ----- 5 files changed, 96 insertions(+), 182 deletions(-) delete mode 100644 slaeforms/dbtables.py create mode 100644 slaeforms/templates/all_links.html delete mode 100644 slaeforms/templates/data.html diff --git a/slaeforms/app.py b/slaeforms/app.py index 0a20898..b71bfe5 100644 --- a/slaeforms/app.py +++ b/slaeforms/app.py @@ -16,7 +16,7 @@ random_order = True # activate environment: cd C:\Users\Jan\Google Drive\Master Stuff\Code\SLAEForms Testing\.venv\Scripts\ # then this: activate - +#SETUP-------------------------------------------------- #Set up sqlalchemy class Base(DeclarativeBase): @@ -30,11 +30,12 @@ app = Flask(__name__) app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///database.db" db.init_app(app) - - #set the secret key (TODO change this for final deployment) app.secret_key = b"29fe9e8edd407c5491d4f1c05632d9fa33e26ed8734a3f5e080ebac3772a555a" + + + #---------testing #open the json file with the config configfile = open("singleformconfig.json") @@ -53,6 +54,8 @@ configtest = open("test.json") configtest.close() #blocks = list(config) # get the block names, aka a list of all keys + + #--------temporär der code für database_schema = { "table_name": "userstest", @@ -63,13 +66,6 @@ database_schema = { tablename = database_schema["table_name"].capitalize() -#check tables -@app.route('/print_tables') -def print_tables(): - inspector = db.inspect(db.engine) - tables = inspector.get_table_names() - return ', '.join(tables) - # test function to create tables from dicts def create_model_class(schema): class_name = schema["table_name"].capitalize() @@ -94,7 +90,6 @@ def create_model_class(schema): print("creating the userstest table") customtable = create_model_class(database_schema) -print(customtable) try: with app.app_context(): print("try to create tables") @@ -102,8 +97,6 @@ try: except SQLAlchemyError as e: print("Error occurred during database creation:", str(e)) - - @app.route("/customsendtest/", methods=["POST"]) def customsendtest(): # Extract form data @@ -129,13 +122,8 @@ def customsendtest(): print("Error occurred during database commit:", str(e)) return 'Data not submitted successfully!' -@app.route("/datatest") -def testdatapage(): - table1 = customtable.query.all() - return render_template( - "data.html", - responses = table1 - ) + + @app.route("/custom") def custom(): try: @@ -147,7 +135,30 @@ def custom(): "templatetest1.html" ) +@app.route("/customsend/", methods=["POST"]) +def customsend(): + session_user_id = session["slaeform_user_id"] + likert_score = request.form["likertscale"] + text_input = request.form["feedback"] + question_title = session["current_question"] + new_id = uuid.uuid4() + date = datetime.today() + print("new idea: {new_id} ".format(new_id=new_id)) + new_response = Response(id=new_id,user_id = session_user_id, question_title = question_title,likert_result = likert_score,notes = text_input, date_created = date) + + try: + db.session.add(new_response) + db.session.commit() + return redirect("/form") + except: + return "There was a problem while adding the response to the Database" + + +# End testing------------------------------------- + +#------------------------------------------------------------------------ +# Setting up DB Models -> should be removed eventually and replaced by json files and automatic generation ---------------------------- # create the model for the response table class Response(db.Model): @@ -177,83 +188,8 @@ except SQLAlchemyError as e: print("Error occurred during database creation:", str(e)) -#----------testing------------------------------------------------ -from sqlalchemy import inspect, select -with app.app_context(): - tables = db.metadata.tables.keys() - table_contents = {} - for table_name in tables: - table = db.metadata.tables[table_name] - table_contents[table_name] = db.session.query(table).all() - - # Print or do whatever you want with the table_contents dictionary - for table_name, contents in table_contents.items(): - print(f"Table: {table_name}") - for row in contents: - print(row) - print("------------------------------------------") - tables = db.metadata.tables.keys() - table_contents = {} - - for table_name in tables: - table = db.metadata.tables[table_name] - columns = table.columns.keys() - rows = db.session.query(table).all() - - table_contents[table_name] = { - 'columns': columns, - 'rows': rows - } - - # Print the table contents including column names - for table_name, contents in table_contents.items(): - print(f"Table: {table_name}") - print("Columns:", contents['columns']) - for row in contents['rows']: - row_data = {column: getattr(row, column) for column in contents['columns']} - print(row_data) - -@app.route("/table_contents") -def table_contents(): - tables = db.metadata.tables.keys() - table_contents = {} - - for table_name in tables: - table = db.metadata.tables[table_name] - columns = table.columns.keys() - rows = db.session.query(table).all() - - table_contents[table_name] = { - 'columns': columns, - 'rows': rows - } - - return render_template( - "table_contents.html", - table_contents=table_contents, - ) -#------- - - -@app.route("/customsend/", methods=["POST"]) -def customsend(): - - session_user_id = session["slaeform_user_id"] - likert_score = request.form["likertscale"] - text_input = request.form["feedback"] - question_title = session["current_question"] - new_id = uuid.uuid4() - date = datetime.today() - print("new idea: {new_id} ".format(new_id=new_id)) - new_response = Response(id=new_id,user_id = session_user_id, question_title = question_title,likert_result = likert_score,notes = text_input, date_created = date) - - try: - db.session.add(new_response) - db.session.commit() - return redirect("/form") - except: - return "There was a problem while adding the response to the Database" +# Actual main code for Form etc ----------------------------------------------------- @app.route("/video", methods=["GET", "POST"]) def videopage(): @@ -376,22 +312,27 @@ def startpage(): ) +# Database stuff------------------------------------ -@app.route('/show_tables') -def show_tables(): - tables = db.metadata.tables - return render_template('show_tables.html', tables=tables) +# the contents of all tables +@app.route("/table_contents") +def table_contents(): + tables = db.metadata.tables.keys() + table_contents = {} + for table_name in tables: + table = db.metadata.tables[table_name] + columns = table.columns.keys() + rows = db.session.query(table).all() -# Show the data in the responses and users table -@app.route("/data") -def datapage(): - responses = Response.query.order_by(Response.date_created).all() - users = User.query.order_by(User.date_created).all() + table_contents[table_name] = { + 'columns': columns, + 'rows': rows + } + return render_template( - "data.html", - responses = responses, - users = users + "table_contents.html", + table_contents=table_contents, ) # Route to delete all entries @@ -410,41 +351,32 @@ def delete_all_entries(): finally: # Close the session db.session.close() - """ - try: - # Query all entries - entries = Response.query.all() - entries2 = User.query.all() - - # Delete each entry - for entry in entries: - db.session.delete(entry) - for entry in entries2: - db.session.delete(entry) - - # Commit changes - db.session.commit() - - return 'All entries deleted successfully' - except Exception as e: - # Rollback changes if any error occurs - db.session.rollback() - return f'Error occurred: {str(e)}', 500 - finally: - # Close the session - db.session.close() - """ +@app.route('/show_tables') +def show_tables(): + tables = db.metadata.tables + return render_template('show_tables.html', tables=tables) + +# Root page ----------------------------- + +def has_no_empty_params(rule): + defaults = rule.defaults if rule.defaults is not None else () + arguments = rule.arguments if rule.arguments is not None else () + return len(defaults) >= len(arguments) @app.route("/") -def blank(): - return "blank page" +def all_links(): + links = [] + for rule in app.url_map.iter_rules(): + # Filter out rules we can't navigate to in a browser + # and rules that require parameters + if "GET" in rule.methods and has_no_empty_params(rule): + url = url_for(rule.endpoint, **(rule.defaults or {})) + links.append((url, rule.endpoint)) + return render_template("all_links.html", links=links) + + -""" -tables = db.metadata.tables -print("the tables in the db:") -print(tables) -""" if __name__ == '__main__': # Create database tables diff --git a/slaeforms/dbtables.py b/slaeforms/dbtables.py deleted file mode 100644 index e81fd66..0000000 --- a/slaeforms/dbtables.py +++ /dev/null @@ -1,12 +0,0 @@ - -from app import db - -class Response(db.Model): - id = db.Column(db.UUID(as_uuid=True), primary_key=True, nullable=False) - user_id = db.Column(db.UUID(as_uuid=True), nullable=False) - question_title = db.Column(db.String(30)) - likert_result = db.Column(db.Integer, nullable=False) - notes = db.Column(db.String(200)) - date_created = db.Column(db.DateTime) - def __repr__(self) -> str: - return "" % self.id \ No newline at end of file diff --git a/slaeforms/static/attributions.txt b/slaeforms/static/attributions.txt index 1ae57aa..d76b728 100644 --- a/slaeforms/static/attributions.txt +++ b/slaeforms/static/attributions.txt @@ -1,6 +1,11 @@ +# Likert Scale https://jamesalvarez.co.uk/blog/how-to-make-responsive-likert-scales-in-css-(like-qualtrics)/ +# Rootpage that shows all defined routes +https://stackoverflow.com/questions/13317536/get-list-of-all-routes-defined-in-the-flask-app + + Licenses: Open Iconic Icon Set (https://github.com/iconic/open-iconic) diff --git a/slaeforms/templates/all_links.html b/slaeforms/templates/all_links.html new file mode 100644 index 0000000..421e630 --- /dev/null +++ b/slaeforms/templates/all_links.html @@ -0,0 +1,20 @@ + + + + + + + all links + + + + + +
    + {% for url, endpoint in links %} +
  • {{ endpoint }}
  • + {% endfor %} +
+ + + \ No newline at end of file diff --git a/slaeforms/templates/data.html b/slaeforms/templates/data.html deleted file mode 100644 index 250af53..0000000 --- a/slaeforms/templates/data.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - Testform - - - - -

Users

- {% for user in users%} -

user_id: {{user.user_id}}

-

question_order: {{user.question_order}}

-

time: {{user.date_created}}

-

-------------------------------------------------------------------------

- {% endfor %} -

Responses

- {% for response in responses%} -

id: {{response.id}}

-

question_title: {{response.question_title}}

-

user_id: {{response.user_id}}

-

Likert score: {{response.likert_result}}

-

Feedback: {{response.notes}}

-

time: {{response.date_created}}

-

-------------------------------------------------------------------------

- {% endfor %} - - - \ No newline at end of file