dict -> tableclass -> write to table seems to work
This commit is contained in:
parent
dfa7156b9f
commit
770fd3f1e1
132
slaeforms/app.py
132
slaeforms/app.py
@ -6,14 +6,16 @@ from flask import Flask, redirect, url_for, request, session, make_response, jso
|
|||||||
from flask import render_template
|
from flask import render_template
|
||||||
from flask_sqlalchemy import SQLAlchemy
|
from flask_sqlalchemy import SQLAlchemy
|
||||||
from sqlalchemy.orm import DeclarativeBase
|
from sqlalchemy.orm import DeclarativeBase
|
||||||
from sqlalchemy import Integer, String
|
from sqlalchemy import Integer, String, Column
|
||||||
from sqlalchemy.orm import Mapped, mapped_column
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
from sqlalchemy.dialects.postgresql import UUID
|
from sqlalchemy.dialects.postgresql import UUID
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
import uuid
|
import uuid
|
||||||
|
from sqlalchemy.exc import SQLAlchemyError
|
||||||
|
|
||||||
|
# declarative base for testing dynamical creaton of table
|
||||||
|
from sqlalchemy.orm import DeclarativeBase
|
||||||
|
|
||||||
# get all dbtables that the user created
|
|
||||||
from dbtables import *
|
|
||||||
|
|
||||||
random_order = True
|
random_order = True
|
||||||
|
|
||||||
@ -25,6 +27,9 @@ app = Flask(__name__)
|
|||||||
# configure the database, give it a path (it will be in the instances folder)
|
# configure the database, give it a path (it will be in the instances folder)
|
||||||
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///database.db"
|
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///database.db"
|
||||||
db = SQLAlchemy(app)
|
db = SQLAlchemy(app)
|
||||||
|
|
||||||
|
Base = DeclarativeBase()
|
||||||
|
|
||||||
#set the secret key (TODO change this for final deployment)
|
#set the secret key (TODO change this for final deployment)
|
||||||
app.secret_key = b"29fe9e8edd407c5491d4f1c05632d9fa33e26ed8734a3f5e080ebac3772a555a"
|
app.secret_key = b"29fe9e8edd407c5491d4f1c05632d9fa33e26ed8734a3f5e080ebac3772a555a"
|
||||||
|
|
||||||
@ -41,9 +46,102 @@ questions = list(config)
|
|||||||
|
|
||||||
# JSON TEST-------------------------------------------
|
# JSON TEST-------------------------------------------
|
||||||
configtest = open("test.json")
|
configtest = open("test.json")
|
||||||
config = json.load(configtest) #convert json to dict
|
#config = json.load(configtest) #convert json to dict
|
||||||
configtest.close()
|
configtest.close()
|
||||||
blocks = list(config) # get the block names, aka a list of all keys
|
#blocks = list(config) # get the block names, aka a list of all keys
|
||||||
|
|
||||||
|
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"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@ -68,18 +166,15 @@ class User(db.Model):
|
|||||||
return "<User %r>" % self.user_id
|
return "<User %r>" % self.user_id
|
||||||
|
|
||||||
# create the table (existing tables are not overwritten)
|
# create the table (existing tables are not overwritten)
|
||||||
with app.app_context():
|
try:
|
||||||
db.create_all()
|
with app.app_context():
|
||||||
|
db.create_all()
|
||||||
|
except SQLAlchemyError as e:
|
||||||
|
print("Error occurred during database creation:", str(e))
|
||||||
|
|
||||||
@app.route("/customsend/<inputid>", methods=["POST"])
|
@app.route("/customsend/<inputid>", methods=["POST"])
|
||||||
def customsend():
|
def customsend():
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
session_user_id = session["slaeform_user_id"]
|
session_user_id = session["slaeform_user_id"]
|
||||||
likert_score = request.form["likertscale"]
|
likert_score = request.form["likertscale"]
|
||||||
text_input = request.form["feedback"]
|
text_input = request.form["feedback"]
|
||||||
@ -96,14 +191,6 @@ def customsend():
|
|||||||
except:
|
except:
|
||||||
return "There was a problem while adding the response to the Database"
|
return "There was a problem while adding the response to the Database"
|
||||||
|
|
||||||
@app.route("/custom")
|
|
||||||
def custom():
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return render_template(
|
|
||||||
"templatetest1.html"
|
|
||||||
)
|
|
||||||
|
|
||||||
@app.route("/video", methods=["GET", "POST"])
|
@app.route("/video", methods=["GET", "POST"])
|
||||||
def videopage():
|
def videopage():
|
||||||
@ -271,3 +358,6 @@ def blank():
|
|||||||
return "blank page"
|
return "blank page"
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
# Create database tables
|
||||||
|
db.create_all()
|
@ -9,7 +9,15 @@
|
|||||||
</head>
|
</head>
|
||||||
|
|
||||||
<body>
|
<body>
|
||||||
|
<form action = "http://localhost:5000/customsendtest" method = "post">
|
||||||
|
<label for="id">id:</label>
|
||||||
|
<input type="number" id="id" name="id" min="0" max="999" required>
|
||||||
|
<label for="feedback">Additional Feedback: </label>
|
||||||
|
<textarea id="username" name="username" rows="1" cols="30" maxlength="20" required></textarea>
|
||||||
|
<label for="age">age:</label>
|
||||||
|
<input type="number" id="age" name="age" min="0" max="999">
|
||||||
|
<p><input id="submitbutton" type = "submit" value = "submit";/></p>
|
||||||
|
</form>
|
||||||
|
|
||||||
</body>
|
</body>
|
||||||
|
|
||||||
|
@ -6,10 +6,10 @@
|
|||||||
"Block 2":{
|
"Block 2":{
|
||||||
"type": "TaskTemplate",
|
"type": "TaskTemplate",
|
||||||
"tempalte": "tempaltetest1.html",
|
"tempalte": "tempaltetest1.html",
|
||||||
"name" : "Block2Responses"
|
"name" : "Block2Responses",
|
||||||
"databasetable": {
|
"databasetable": {
|
||||||
"question_title" : {
|
"question_title" : {
|
||||||
"type:"
|
"type":"likert"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
Loading…
Reference in New Issue
Block a user