Aufräumen, auslagern von Testcode in andere files

This commit is contained in:
Jan 2024-05-19 16:28:51 +02:00
parent 50fcf096eb
commit b582b5e220
15 changed files with 214 additions and 160 deletions

View File

@ -1,11 +0,0 @@
{
"folders": [
{
"path": "../.."
},
{
"path": "../../../CSS Testing"
}
],
"settings": {}
}

View File

@ -36,129 +36,24 @@ app.secret_key = b"29fe9e8edd407c5491d4f1c05632d9fa33e26ed8734a3f5e080ebac3772a5
#---------testing
#---------testing JSON Stuff
#open the json file with the config
configfile = open("singleformconfig.json")
configfile2 = open("pairwiseformconfig.json")
#convert it to dict
config = json.load(configfile)
config2 = json.load(configfile2)
configfile.close()
configfile2.close()
# get the questions: Questions is a list that contains the keys of the dictionary
questions = list(config)
# JSON TEST-------------------------------------------
configtest = open("test.json")
#config = json.load(configtest) #convert json to dict
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",
"id": {"type": "integer", "nullable": False},
"username": {"type": "string", "nullable": False, "size": 20},
"age": {"type": "integer", "nullable": True}
}
tablename = database_schema["table_name"].capitalize()
# test function to create tables from dicts
def create_model_class(schema):
class_name = schema["table_name"].capitalize()
# Define class attributes dynamically
attributes = {"__tablename__": schema["table_name"]}
attributes["uid"] = Column(db.UUID(as_uuid=True), primary_key=True, nullable=False)
for column_name, column_info in schema.items():
if column_name != "table_name":
if column_info["type"] == "integer":
column_type = Integer
elif column_info["type"] == "string":
column_type = String(column_info["size"])
attributes[column_name] = Column(column_type, nullable=column_info["nullable"])
# Create the model class
return type(class_name, (db.Model,), attributes)
print("creating the userstest table")
customtable = create_model_class(database_schema)
try:
with app.app_context():
print("try to create tables")
db.create_all()
except SQLAlchemyError as e:
print("Error occurred during database creation:", str(e))
@app.route("/customsendtest/", methods=["POST"])
def customsendtest():
# Extract form data
form_data = request.form
# Create a new instance of the dynamically generated model
new_user = customtable()
# Assign form data to model attributes
for key, value in form_data.items():
if hasattr(new_user, key):
setattr(new_user, key, value)
new_id = uuid.uuid4()
setattr(new_user, "uid",new_id)
# Add new user to the database session and commit changes
try:
#print("new idea: {new_id} ".format(new_id=new_id))
db.session.add(new_user)
db.session.commit()
return 'Data submitted successfully!'
except SQLAlchemyError as e:
print("Error occurred during database commit:", str(e))
return 'Data not submitted successfully!'
@app.route("/custom")
def custom():
try:
with app.app_context():
db.create_all()
except SQLAlchemyError as e:
print("Error occurred during database creation:", str(e))
return render_template(
"templatetest1.html"
)
@app.route("/customsend/<inputid>", 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 ----------------------------
# Setting up DB Models, response -> should be removed eventually and replaced by json files and automatic generation ----------------------------
# create the model for the response table
class Response(db.Model):
@ -171,12 +66,12 @@ class Response(db.Model):
def __repr__(self) -> str:
return "<Response %r>" % self.id
# This table is created always
# This table is always created
class User(db.Model):
user_id = db.Column(db.UUID(as_uuid=True), primary_key=True, nullable=False)
device_id = db.Column(db.UUID(as_uuid=True), nullable=False)
question_order = db.Column(db.String(60))
date_created = db.Column(db.DateTime, default=datetime.today())
date_created = db.Column(db.DateTime, default=datetime.today()) # todo test if this default works
def __repr__(self) -> str:
return "<User %r>" % self.user_id
@ -229,7 +124,7 @@ def sendpage():
@app.route("/form", methods=["GET", "POST"]) # /<username> should not even be needed right?
@app.route("/form", methods=["GET", "POST"])
def formpage():
#user is not yet registered and should not be here
if not "slaeform_user_id" in session:

43
slaeforms/default.json Normal file
View File

@ -0,0 +1,43 @@
{
"Block_1":{
"type": "SinglePage",
"template": "startpage.html",
"database_table" :{
"TableName": "Datenschutzerklärung",
"Fields": {
}
}
},
"Block 2":{
"type": "TaskTemplate",
"tempalte": "tempaltetest1.html",
"name" : "Block2Responses",
"databasetable": {
"question_title" : {
"type":"likert"
}
}
},
"question 3":{
"type": "single",
"video1": "https://www.youtube-nocookie.com/embed/XTMIomsXxKM?si=r2zB6OKERH6Jdpi6",
"scales": {
"block1":{
"type": "likert",
"numberofpoints": "3",
"points":{
"point1": "left",
"point2": "none",
"point3": "right"
}
},
"block2":{
"type": "textinput",
"length": "200"
},
"block3":{
"type": "video"
}
}
}
}

View File

@ -30,6 +30,7 @@ db = SQLAlchemy(app)
app.secret_key = b"29fe9e8edd407c5491d4f1c05632d9fa33e26ed8734a3f5e080ebac3772a555a"
#--------temporär der code für dict to db test
database_schema = {
"table_name": "userstest",
"id": {"type": "integer", "nullable": False},
@ -39,13 +40,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()
@ -70,7 +64,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")
@ -78,9 +71,7 @@ try:
except SQLAlchemyError as e:
print("Error occurred during database creation:", str(e))
@app.route("/customsendtest/", methods=["POST"])
@app.route("/customsendtest", methods=["POST"])
def customsendtest():
# Extract form data
form_data = request.form
@ -105,20 +96,25 @@ 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():
@app.route("/customsend/<inputid>", 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:
with app.app_context():
db.create_all()
except SQLAlchemyError as e:
print("Error occurred during database creation:", str(e))
return render_template(
"templatetest1.html"
)
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-------------------------------------

View File

@ -0,0 +1,61 @@
{
"Block_1":{
"type": "single_page",
"html_template": "the jinja templat in the template folder that should be used",
"database_table" :{
"table_name": "Name of the table in the database",
"fields": {
"answer_1": {
"type": "string or integer",
"nullable": "true (must have a value) or false (must not have a value)",
"size" : "max number of chars in the string (only usable with type:string)"
}
}
}
},
"Block 2":{
"type": "template",
"html_template": "the jinja templat in the template folder that should be used",
"template_blocks":{
"likert_block_1":{
"type":"likert",
"scale_size":"7",
"text_left":"bad",
"text_right":"good"
}
},
"content":{
"item that should be given to the template":{
"type":"list",
"values":{
"1":"whatever",
"2":"also whatever"
}
}
},
"database_table" :{
"table_name": "Name of the table in the database",
"fields": {
"answer_1": {
"type": "string or integer",
"nullable": "true (must have a value) or false (must not have a value)",
"size" : "max number of chars in the string (only usable with type:string)"
}
}
}
},
"Block 3":{
"type": "custom_template",
"html_template": "the jinja templat in the template folder that should be used",
"database_table" :{
"table_name": "Name of the table in the database",
"fields": {
"answer_1": {
"type": "string or integer",
"nullable": "true (must have a value) or false (must not have a value)",
"size" : "max number of chars in the string (only usable with type:string)"
}
}
}
}
}

View File

@ -0,0 +1,80 @@
import sys
import json
import random
import base64
from flask import Flask, redirect, url_for, request, session, make_response, jsonify, send_from_directory
from flask import render_template
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Integer, String, Column
from datetime import datetime
import uuid
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy import inspect
from sqlalchemy.orm import DeclarativeBase
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):
pass
db = SQLAlchemy(model_class=Base)
#create the app
app = Flask(__name__)
# configure the database, give it a path (it will be in the instances folder)
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")
#convert it to dict
config = json.load(configfile)
configfile.close()
# get the questions: Questions is a list that contains the keys of the dictionary
questions = list(config)
@app.route("/form", methods=["GET", "POST"])
def formpage():
#user is not yet registered and should not be here
if not "slaeform_user_id" in session:
return redirect("/start")
#TODO fill in code that determins at which question the user is
print("form starts, the sessionorder rn:")
print(session["question_order"])
if not session["question_order"]:
print("---------------question order is empty------------")
return redirect("/data")
print("pop the first element")
current_question = session["question_order"].pop(0)
session["current_question"] = current_question
print(current_question)
print("the new sessionorder rn:")
print(session["question_order"])
session["question_order"] = session["question_order"]
print("has this changed sth?:")
print(session["question_order"])
return render_template(
"layout2.html",
config=config,
current_question = current_question,
videotype=config[current_question]["type"],
video_url= config[current_question]["video1"],
blocks = config[current_question]["blocks"]
)

View File

@ -1,10 +0,0 @@
{
"folders": [
{
"path": ".."
},
{
"path": "../../../CSS Testing"
}
]
}