/table_contents funktioniert jetzt!

This commit is contained in:
Jan 2024-05-19 13:32:51 +02:00
parent 770fd3f1e1
commit 3210d9c133
12 changed files with 331 additions and 5995 deletions

View File

@ -1,70 +0,0 @@
import sys
import json
import random
from flask import Flask, redirect, url_for, request, session, make_response
from flask import render_template
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy import Integer, String
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.dialects.postgresql import UUID
from datetime import datetime
import uuid
random_order = True
#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 = SQLAlchemy(app)
#set the secret key (TODO change this for final deployment)
app.secret_key = b"29fe9e8edd407c5491d4f1c05632d9fa33e26ed8734a3f5e080ebac3772a555a"
#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 = list(config)
# create the model for the response table
class Response(db.Model):
id = db.Column(db.Integer, primary_key=True)
session_user_id = db.Column(db.String(36))
likert_result = db.Column(db.Integer, nullable=False)
notes = db.Column(db.String(200))
date_created = db.Column(db.DateTime, default=datetime.today())
def __repr__(self) -> str:
return "<Response %r>" % self.id
#test
@app.route("/test", methods=["GET", "POST"])
def testpage():
if not "slaeform_user_id" in session:
# If the cookie doesn't exist
print('Hello, new user! Setting cookie...')
new_user_id = str(uuid.uuid4())
session["slaeform_user_id"] = new_user_id
if request.method == "POST":
session_user_id = session["slaeform_user_id"]
likert_score = request.form["likertscale"]
text_input = request.form["feedback"]
print("new response: {session_user_id} {likert_score_1} {text_input_1}".format(session_user_id = session_user_id, likert_score_1 = likert_score, text_input_1 = text_input))
new_response = Response(session_user_id = session_user_id,likert_result = likert_score, notes = text_input)
try:
db.session.add(new_response)
db.session.commit()
return redirect("/start") #url_for("datapage")
except:
return "There was a problem while adding the response to the Database"
return render_template(
"layout1.html"
)

View File

@ -5,34 +5,37 @@ 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.orm import DeclarativeBase
from sqlalchemy import Integer, String, Column
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.dialects.postgresql import UUID
from datetime import datetime
import uuid
from sqlalchemy.exc import SQLAlchemyError
# declarative base for testing dynamical creaton of table
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
#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 = SQLAlchemy(app)
db.init_app(app)
Base = DeclarativeBase()
#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")
configfile2 = open("pairwiseformconfig.json")
@ -50,6 +53,7 @@ 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",
"id": {"type": "integer", "nullable": False},
@ -172,6 +176,65 @@ try:
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/<inputid>", methods=["POST"])
def customsend():
@ -314,8 +377,13 @@ def startpage():
@app.route('/show_tables')
def show_tables():
tables = db.metadata.tables
return render_template('show_tables.html', tables=tables)
# Show the data in the responses and users table
@app.route("/data")
def datapage():
responses = Response.query.order_by(Response.date_created).all()
@ -329,6 +397,20 @@ def datapage():
# Route to delete all entries
@app.route('/delete_all_entries', methods=['GET'])
def delete_all_entries():
try:
meta = db.metadata
for table in reversed(meta.sorted_tables): # Iterate through tables in reverse order to handle foreign key constraints
db.session.execute(table.delete())
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()
"""
try:
# Query all entries
entries = Response.query.all()
@ -352,11 +434,17 @@ def delete_all_entries():
finally:
# Close the session
db.session.close()
"""
@app.route("/")
def blank():
return "blank page"
"""
tables = db.metadata.tables
print("the tables in the db:")
print(tables)
"""
if __name__ == '__main__':
# Create database tables

32
slaeforms/currenturls.txt Normal file
View File

@ -0,0 +1,32 @@
"/" Blank page
'/delete_all_entries' delete entries from database (not actually all, hardcoded)
"/data" Show Data of some tables (Responses and users)

124
slaeforms/dicttablecode.py Normal file
View File

@ -0,0 +1,124 @@
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 sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.dialects.postgresql import UUID
from datetime import datetime
import uuid
from sqlalchemy.exc import SQLAlchemyError
random_order = True
# activate environment: cd C:\Users\Jan\Google Drive\Master Stuff\Code\SLAEForms Testing\.venv\Scripts\
# then this: activate
#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 = SQLAlchemy(app)
#set the secret key (TODO change this for final deployment)
app.secret_key = b"29fe9e8edd407c5491d4f1c05632d9fa33e26ed8734a3f5e080ebac3772a555a"
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()
#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()
# 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)
print(customtable)
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("/datatest")
def testdatapage():
table1 = customtable.query.all()
return render_template(
"data.html",
responses = table1
)
@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"
)

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -1,17 +0,0 @@
DROP TABLE IF EXISTS user;
DROP TABLE IF EXISTS post;
CREATE TABLE user (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL
);
CREATE TABLE post (
id INTEGER PRIMARY KEY AUTOINCREMENT,
author_id INTEGER NOT NULL,
created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
title TEXT NOT NULL,
body TEXT NOT NULL,
FOREIGN KEY (author_id) REFERENCES user (id)
);

View File

@ -132,4 +132,22 @@ input, label {
.likert span:hover {
background: #f1f1f1;
outline: lightgrey auto 0.5px;
}
table {
border-collapse: collapse;
margin: 20px 0;
table-layout: auto; /* Allows columns to adjust to their content */
width: auto; /* Adjusts the table width to the content */
}
th, td {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
word-wrap: break-word; /* Ensures content wraps and doesn't overflow */
}
th {
background-color: #f2f2f2;
}

View File

@ -3,7 +3,7 @@
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="styles.css" />
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles.css')}}" />
<title>Testform</title>
<link rel="shortcut icon" href="{{ url_for('static', filename='icons/favicon.ico') }}">
</head>

View File

@ -0,0 +1,26 @@
<!DOCTYPE html>
<html>
<head>
<title>Database Tables</title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles.css')}}" />
<link rel="shortcut icon" href="{{ url_for('static', filename='icons/favicon.ico') }}">
</head>
<body>
<h1>Database Tables</h1>
<ul>
{% for key, value in tables.items() %}
<li>
<strong>{{ key }}</strong>:<br>
<ul>
{% for column in value.columns %}
<li>{{ column.name }} - {{ column.type }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
</body>
</html>
<!DOCTYPE html>
<html>

View File

@ -0,0 +1,33 @@
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles.css')}}" />
<title>Database Tables</title>
<link rel="shortcut icon" href="{{ url_for('static', filename='icons/favicon.ico') }}">
</head>
<body>
<h1>Database Tables</h1>
{% for table_name, contents in table_contents.items() %}
<h2>{{table_name}}</h2>
<table>
<thead>
<tr>
{% for column in contents['columns'] %}
<th>{{column}}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for row in contents['rows'] %}
<tr>
{% for column in contents['columns'] %}
<td>{{row[column]}}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
{% endfor %}
</body>
</html>

Binary file not shown.