From d2e50677585fa699c71498244a3f5b349bb1f75f Mon Sep 17 00:00:00 2001 From: shriyasshah Date: Wed, 8 Jan 2025 20:44:47 -0800 Subject: [PATCH 1/9] made quizquestions work --- main.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/main.py b/main.py index fc2726f..1f4a636 100644 --- a/main.py +++ b/main.py @@ -23,7 +23,7 @@ from api.section import section_api from api.nestPost import nestPost_api # Justin added this, custom format for his website from api.quizgrading import quizgrading_api -from api.questionsq import quizquestions_api +from api.quizquestions import quizquestions_api from api.messages_api import messages_api # Adi added this, messages for his website # New API's being tested from api.general import general_api @@ -34,7 +34,6 @@ # database Initialization functions from model.carChat import CarChat from model.quizgrading import initquizgrading -from model.questionsq import initquizquestions from model.user import User, initUsers from model.section import Section, initSections from model.group import Group, initGroups From 38cbfc57bc1a2d169c5ad3bb73d838b20c208502 Mon Sep 17 00:00:00 2001 From: shriyasshah Date: Thu, 9 Jan 2025 15:23:55 -0800 Subject: [PATCH 2/9] backend quiz --- api/quizquestions.py | 64 +++++++++---------- main.py | 5 +- model/quizquestions.py | 137 ++++++++++++++++++++++++++++++++++++++++- 3 files changed, 168 insertions(+), 38 deletions(-) diff --git a/api/quizquestions.py b/api/quizquestions.py index 5d7d622..8760da5 100644 --- a/api/quizquestions.py +++ b/api/quizquestions.py @@ -1,49 +1,45 @@ -import jwt from flask import Blueprint, request, jsonify, current_app, Response, g from flask_restful import Api, Resource # used for REST API building from datetime import datetime -from __init__ import app from api.jwt_authorize import token_required -from model.quizquestions import quizquestions -from model.user import User -from model.section import Section +# from model.quizquestions import quizquestions +from model.nestPost import NestPost quizquestions_api = Blueprint('quizquestions_api', __name__, url_prefix='/api') +""" +The Api object is connected to the Blueprint object to define the API endpoints. +- The API object is used to add resources to the API. +- The objects added are mapped to code that contains the actions for the API. +- For more information, refer to the API docs: https://flask-restful.readthedocs.io/en/latest/api.html +""" api = Api(quizquestions_api) -class GroupAPI: +class quizquestionsAPI: """ - The API CRUD endpoints correspond to common HTTP methods: - - post: create a new group - - get: read groups - - put: update a group - - delete: delete a group + Define the API CRUD endpoints for the Post model. + There are four operations that correspond to common HTTP methods: + - post: create a new post + - get: read posts + - put: update a post + - delete: delete a post """ class _CRUD(Resource): @token_required() - def post(self): - """ - Create a new group. - """ - # Obtain the current user from the token required setting in the global context - current_user = g.current_user - # Obtain the request data sent by the RESTful client API - data = request.get_json() - # Create a new group object using the data from the request - chat = quizquestions(data['message'], current_user.id) - # Save the chat object using the Object Relational Mapper (ORM) method defined in the model - chat.create() - # Return response to the client in JSON format, converting Python dictionaries to JSON format - return jsonify(chat.read()) - def get(self): - chats = quizquestions.query.all() - allChats = [] - for i in range(len(chats)): - allChats.append(chats[i].read()) + # Find all the posts by the current user + # scores = quizquestions.query.all() + scores = NestPost.query.all() + # Prepare a JSON list of all the posts, uses for loop shortcut called list comprehension + json_ready = [score.read() for score in scores] + # Return a JSON list, converting Python dictionaries to JSON format + #return jsonify(json_ready) + return jsonify("Shriya is so cool") - # Return a JSON restful response to the client - return jsonify(allChats) - - api.add_resource(_CRUD, '/quizquestions') \ No newline at end of file + + """ + Map the _CRUD class to the API endpoints for /post. + - The API resource class inherits from flask_restful.Resource. + - The _CRUD class defines the HTTP methods for the API. + """ + api.add_resource(_CRUD, '/quizquestions/guizquestions') \ No newline at end of file diff --git a/main.py b/main.py index 1f4a636..0ce22b3 100644 --- a/main.py +++ b/main.py @@ -23,10 +23,10 @@ from api.section import section_api from api.nestPost import nestPost_api # Justin added this, custom format for his website from api.quizgrading import quizgrading_api -from api.quizquestions import quizquestions_api from api.messages_api import messages_api # Adi added this, messages for his website # New API's being tested from api.general import general_api +from api.quizquestions import quizquestions_api from api.binaryLearningGame import binaryLearningGameScores_api from api.vote import vote_api @@ -51,10 +51,11 @@ app.register_blueprint(post_api) app.register_blueprint(channel_api) app.register_blueprint(section_api) -# apis under development app.register_blueprint(binaryLearningGameScores_api) app.register_blueprint(student_api) app.register_blueprint(quizgrading_api) +# API's following this are under development +app.register_blueprint(quizquestions_api) # Tell Flask-Login the view function name of your login route login_manager.login_view = "login" diff --git a/model/quizquestions.py b/model/quizquestions.py index 7c760dc..0d216b9 100644 --- a/model/quizquestions.py +++ b/model/quizquestions.py @@ -4,7 +4,7 @@ class quizquestions(db.Model): __tablename__ = 'quizquestions' - + id = db.Column(db.Integer, primary_key=True) _q1 = db.Column(db.Integer, nullable=False) _q2 = db.Column(db.Integer, nullable=False) @@ -16,4 +16,137 @@ class quizquestions(db.Model): _q8 = db.Column(db.Integer, nullable=False) _q9 = db.Column(db.Integer, nullable=False) _q10 = db.Column(db.Integer, nullable=False) - _user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) \ No newline at end of file + _user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) + + def __init__(self, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, user_id): + self._q1 = q1 + self._q2 = q2 + self._q3 = q3 + self._q4 = q4 + self._q5 = q5 + self._q6 = q6 + self._q7 = q7 + self._q8 = q8 + self._q9 = q9 + self._q10 = q10 + self._user_id = user_id + + +def __repr__(self): + """ + The __repr__ method is a special method used to represent the object in a string format. + Called by the repr(post) built-in function, where post is an instance of the Post class. + + Returns: + str: A text representation of how to create the object. + """ + return f"Post(id={self.id}, q1={self._q1}, q2={self._q2}, q3={self._q3}, q4={self._q4}, q5={self._q5}, q6={self._q6}, q7={self._q7}, q8={self._q8}, q9={self._q9}, q10={self._q10} user_id={self._user_id})" + + +def create(self): + """ + The create method adds the object to the database and commits the transaction. + + Uses: + The db ORM methods to add and commit the transaction. + + Raises: + Exception: An error occurred when adding the object to the database. + """ + try: + db.session.add(self) + db.session.commit() + except Exception as e: + db.session.rollback() + raise e + +def read(self): + """ + The read method retrieves the object data from the object's attributes and returns it as a dictionary. + + Uses: + The Group.query and User.query methods to retrieve the group and user objects. + + Returns: + dict: A dictionary containing the post data, including user and group names. + """ + user = User.query.get(self._user_id) + data = { + "id": self.id, + "q1": self._q1, + "q2": self._q2, + "q3": self._q3, + "q4": self._q4, + "q5": self._q5, + "q6": self._q6, + "q7": self._q7, + "q8": self._q8, + "q9": self._q9, + "q10": self._q10, + "user_name": user.name if user else None, + } + return data + +def update(self): + """ + The update method commits the transaction to the database. + + Uses: + The db ORM method to commit the transaction. + + Raises: + Exception: An error occurred when updating the object in the database. + """ + try: + db.session.commit() + except Exception as e: + db.session.rollback() + raise e + +def delete(self): + """ + The delete method removes the object from the database and commits the transaction. + + Uses: + The db ORM methods to delete and commit the transaction. + + Raises: + Exception: An error occurred when deleting the object from the database. + """ + try: + db.session.delete(self) + db.session.commit() + except Exception as e: + db.session.rollback() + raise e + + +def initquizquestions(): + """ + The initPosts function creates the Post table and adds tester data to the table. + + Uses: + The db ORM methods to create the table. + + Instantiates: + Post objects with tester data. + + Raises: + IntegrityError: An error occurred when adding the tester data to the table. + """ + with app.app_context(): + """Create database and tables""" + db.create_all() + """Tester data for table""" + + p1 = quizquestions(q1='0', q2='0', q3='0',q4='0',q5='0',q6='0',q7='0',q8='0',q9='0',q10='0', user_id=1) + + for post in [p1]: + try: + post.create() + print(f"Record created: {repr(post)}") + except IntegrityError: + '''fails with bad or duplicate data''' + db.session.remove() + print(f"Records exist, duplicate email, or error: {post.uid}") + From 20da480f5e7a506dd432fa41ca2e8172382892f8 Mon Sep 17 00:00:00 2001 From: shriyasshah Date: Wed, 15 Jan 2025 17:00:32 -0800 Subject: [PATCH 3/9] quiz question table --- api/quizquestions.py | 47 ++++++++++++++++++++++------- main.py | 2 ++ model/quizquestions.py | 68 ++++++++++++++---------------------------- 3 files changed, 61 insertions(+), 56 deletions(-) diff --git a/api/quizquestions.py b/api/quizquestions.py index 8760da5..6e84f00 100644 --- a/api/quizquestions.py +++ b/api/quizquestions.py @@ -1,10 +1,13 @@ -from flask import Blueprint, request, jsonify, current_app, Response, g +from flask import Blueprint, request, jsonify, g from flask_restful import Api, Resource # used for REST API building -from datetime import datetime from api.jwt_authorize import token_required -# from model.quizquestions import quizquestions -from model.nestPost import NestPost +from model.quizquestions import quizquestions +""" +This Blueprint object is used to define APIs for the Post model. +- Blueprint is used to modularize application files. +- This Blueprint is registered to the Flask app in main.py. +""" quizquestions_api = Blueprint('quizquestions_api', __name__, url_prefix='/api') """ @@ -26,20 +29,44 @@ class quizquestionsAPI: """ class _CRUD(Resource): @token_required() + def post(self): + # Obtain the current user from the token + current_user = g.current_user + # Obtain the request data sent by the RESTful client API + data = request.get_json() + # Create a new post object using the data from the request + post = quizquestions(data['question']) + # Save the post object using the ORM method defined in the model + post.create() + # Return response to the client in JSON format + return jsonify(post.read()) + def get(self): + # Obtain the current user + # current_user = g.current_user # Find all the posts by the current user - # scores = quizquestions.query.all() - scores = NestPost.query.all() + posts = quizquestions.query.all() # Prepare a JSON list of all the posts, uses for loop shortcut called list comprehension - json_ready = [score.read() for score in scores] + json_ready = [post.read() for post in posts] # Return a JSON list, converting Python dictionaries to JSON format - #return jsonify(json_ready) - return jsonify("Shriya is so cool") + return jsonify(json_ready) + @token_required() + def delete(self): + # Obtain the current user + current_user = g.current_user + # Obtain the request data + data = request.get_json() + # Find the current post from the database table(s) + post = quizquestions.query.get(data['id']) + # Delete the post using the ORM method defined in the model + post.delete() + # Return response + return jsonify({"message": "Post deleted"}) """ Map the _CRUD class to the API endpoints for /post. - The API resource class inherits from flask_restful.Resource. - The _CRUD class defines the HTTP methods for the API. """ - api.add_resource(_CRUD, '/quizquestions/guizquestions') \ No newline at end of file + api.add_resource(_CRUD, '/quizquestions') \ No newline at end of file diff --git a/main.py b/main.py index 0ce22b3..a8c13a7 100644 --- a/main.py +++ b/main.py @@ -41,6 +41,7 @@ from model.post import Post, initPosts # under development from model.binaryLearningGame import initBinaryLearningGameScores +from model.quizquestions import quizquestions, initquizquestions # server only Views # register URIs for api endpoints @@ -163,6 +164,7 @@ def generate_data(): # initPosts() # New data being tested initBinaryLearningGameScores() + initquizquestions() # Backup the old database def backup_database(db_uri, backup_uri): diff --git a/model/quizquestions.py b/model/quizquestions.py index 0d216b9..beb1b7e 100644 --- a/model/quizquestions.py +++ b/model/quizquestions.py @@ -1,4 +1,5 @@ from sqlite3 import IntegrityError +from sqlalchemy import Text from __init__ import app, db from model.user import User @@ -6,33 +7,15 @@ class quizquestions(db.Model): __tablename__ = 'quizquestions' id = db.Column(db.Integer, primary_key=True) - _q1 = db.Column(db.Integer, nullable=False) - _q2 = db.Column(db.Integer, nullable=False) - _q3 = db.Column(db.Integer, nullable=False) - _q4 = db.Column(db.Integer, nullable=False) - _q5 = db.Column(db.Integer, nullable=False) - _q6 = db.Column(db.Integer, nullable=False) - _q7 = db.Column(db.Integer, nullable=False) - _q8 = db.Column(db.Integer, nullable=False) - _q9 = db.Column(db.Integer, nullable=False) - _q10 = db.Column(db.Integer, nullable=False) - _user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) + _question = db.Column(db.String(255), nullable=False) + - def __init__(self, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, user_id): - self._q1 = q1 - self._q2 = q2 - self._q3 = q3 - self._q4 = q4 - self._q5 = q5 - self._q6 = q6 - self._q7 = q7 - self._q8 = q8 - self._q9 = q9 - self._q10 = q10 - self._user_id = user_id + def __init__(self, question): + self._question = question + -def __repr__(self): + def __repr__(self): """ The __repr__ method is a special method used to represent the object in a string format. Called by the repr(post) built-in function, where post is an instance of the Post class. @@ -40,10 +23,10 @@ def __repr__(self): Returns: str: A text representation of how to create the object. """ - return f"Post(id={self.id}, q1={self._q1}, q2={self._q2}, q3={self._q3}, q4={self._q4}, q5={self._q5}, q6={self._q6}, q7={self._q7}, q8={self._q8}, q9={self._q9}, q10={self._q10} user_id={self._user_id})" + return f"Post(id={self.id}, q1={self._question})" -def create(self): + def create(self): """ The create method adds the object to the database and commits the transaction. @@ -60,7 +43,7 @@ def create(self): db.session.rollback() raise e -def read(self): + def read(self): """ The read method retrieves the object data from the object's attributes and returns it as a dictionary. @@ -70,24 +53,14 @@ def read(self): Returns: dict: A dictionary containing the post data, including user and group names. """ - user = User.query.get(self._user_id) data = { "id": self.id, - "q1": self._q1, - "q2": self._q2, - "q3": self._q3, - "q4": self._q4, - "q5": self._q5, - "q6": self._q6, - "q7": self._q7, - "q8": self._q8, - "q9": self._q9, - "q10": self._q10, - "user_name": user.name if user else None, + "q1": self._question, + } return data -def update(self): + def update(self): """ The update method commits the transaction to the database. @@ -103,7 +76,7 @@ def update(self): db.session.rollback() raise e -def delete(self): + def delete(self): """ The delete method removes the object from the database and commits the transaction. @@ -139,14 +112,17 @@ def initquizquestions(): db.create_all() """Tester data for table""" - p1 = quizquestions(q1='0', q2='0', q3='0',q4='0',q5='0',q6='0',q7='0',q8='0',q9='0',q10='0', user_id=1) + p1 = quizquestions(question="What is the capital of France?") + p2 = quizquestions(question="What is the capital of Britain?") + p3 = quizquestions(question="What is the capital of China?") + p4 = quizquestions(question="What is the capital of India?") + p5 = quizquestions(question="What is the capital of Japam?") - for post in [p1]: + for question in [p1, p2, p3, p4, p5]: try: - post.create() - print(f"Record created: {repr(post)}") + question.create() + print(f"Record created: {repr(question)}") except IntegrityError: '''fails with bad or duplicate data''' db.session.remove() - print(f"Records exist, duplicate email, or error: {post.uid}") From 50286a4d1eb74906195cc57fa0c1c03c206a2c53 Mon Sep 17 00:00:00 2001 From: shriyasshah Date: Tue, 21 Jan 2025 18:43:56 -0800 Subject: [PATCH 4/9] made quiz grading --- main.py | 2 ++ model/quizquestions.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/main.py b/main.py index a8c13a7..f7819f0 100644 --- a/main.py +++ b/main.py @@ -42,6 +42,7 @@ # under development from model.binaryLearningGame import initBinaryLearningGameScores from model.quizquestions import quizquestions, initquizquestions +from model.quizgrading import quizgrading, initquizgrading # server only Views # register URIs for api endpoints @@ -165,6 +166,7 @@ def generate_data(): # New data being tested initBinaryLearningGameScores() initquizquestions() + initquizgrading() # Backup the old database def backup_database(db_uri, backup_uri): diff --git a/model/quizquestions.py b/model/quizquestions.py index beb1b7e..99932ac 100644 --- a/model/quizquestions.py +++ b/model/quizquestions.py @@ -116,7 +116,7 @@ def initquizquestions(): p2 = quizquestions(question="What is the capital of Britain?") p3 = quizquestions(question="What is the capital of China?") p4 = quizquestions(question="What is the capital of India?") - p5 = quizquestions(question="What is the capital of Japam?") + p5 = quizquestions(question="What is the capital of Japan?") for question in [p1, p2, p3, p4, p5]: try: From 10ec3e98bbcce4930cbcba566fb4d4cee14f34d6 Mon Sep 17 00:00:00 2001 From: shriyasshah Date: Mon, 27 Jan 2025 16:56:20 -0800 Subject: [PATCH 5/9] quiz changes --- api/quizgrading.py | 41 ++++++++++++++++++++++++++++++++++----- api/quizquestions1.py | 45 +++++++++++++++++++++++++++++++++++++++++++ main.py | 3 +-- model/quizgrading.py | 33 +++++++++++++++---------------- 4 files changed, 97 insertions(+), 25 deletions(-) create mode 100644 api/quizquestions1.py diff --git a/api/quizgrading.py b/api/quizgrading.py index 4a74b89..c09dde7 100644 --- a/api/quizgrading.py +++ b/api/quizgrading.py @@ -21,17 +21,15 @@ class GroupAPI: - delete: delete a group """ class _CRUD(Resource): - @token_required() + def post(self): """ Create a new group. """ - # Obtain the current user from the token required setting in the global context - current_user = g.current_user # Obtain the request data sent by the RESTful client API data = request.get_json() # Create a new group object using the data from the request - chat = quizgrading(data['message'], current_user.id) + chat = quizgrading(data['quizgrade'], data['attempt']) # Save the chat object using the Object Relational Mapper (ORM) method defined in the model chat.create() # Return response to the client in JSON format, converting Python dictionaries to JSON format @@ -45,5 +43,38 @@ def get(self): # Return a JSON restful response to the client return jsonify(allChats) + + def put(self): + # Obtain the current user + # Obtain the request data + data = request.get_json() + # Find the current post from the database table(s) + post = quizgrading.query.get(data['id']) + # Update the post + post._quizgrade = data['quizgrade'] + post._attempt = data['attempt'] + # Save the post + post.update() + # Return response + return jsonify(post.read()) + + def delete(self): + # Obtain the request data + data = request.get_json() + # Find the current post from the database table(s) + post = quizgrading.query.get(data['id']) + # Delete the post using the ORM method defined in the model + post.delete() + # Return response + return jsonify({"message": "Post deleted"}) + + """ + Map the _CRUD class to the API endpoints for /post. + - The API resource class inherits from flask_restful.Resource. + - The _CRUD class defines the HTTP methods for the API. + """ - api.add_resource(_CRUD, '/quizgrading') \ No newline at end of file + api.add_resource(_CRUD, '/quizgrading') + +if __name__ == '__main__': + app.run(debug=True) \ No newline at end of file diff --git a/api/quizquestions1.py b/api/quizquestions1.py new file mode 100644 index 0000000..8760da5 --- /dev/null +++ b/api/quizquestions1.py @@ -0,0 +1,45 @@ +from flask import Blueprint, request, jsonify, current_app, Response, g +from flask_restful import Api, Resource # used for REST API building +from datetime import datetime +from api.jwt_authorize import token_required +# from model.quizquestions import quizquestions +from model.nestPost import NestPost + +quizquestions_api = Blueprint('quizquestions_api', __name__, url_prefix='/api') + +""" +The Api object is connected to the Blueprint object to define the API endpoints. +- The API object is used to add resources to the API. +- The objects added are mapped to code that contains the actions for the API. +- For more information, refer to the API docs: https://flask-restful.readthedocs.io/en/latest/api.html +""" +api = Api(quizquestions_api) + +class quizquestionsAPI: + """ + Define the API CRUD endpoints for the Post model. + There are four operations that correspond to common HTTP methods: + - post: create a new post + - get: read posts + - put: update a post + - delete: delete a post + """ + class _CRUD(Resource): + @token_required() + def get(self): + # Find all the posts by the current user + # scores = quizquestions.query.all() + scores = NestPost.query.all() + # Prepare a JSON list of all the posts, uses for loop shortcut called list comprehension + json_ready = [score.read() for score in scores] + # Return a JSON list, converting Python dictionaries to JSON format + #return jsonify(json_ready) + return jsonify("Shriya is so cool") + + + """ + Map the _CRUD class to the API endpoints for /post. + - The API resource class inherits from flask_restful.Resource. + - The _CRUD class defines the HTTP methods for the API. + """ + api.add_resource(_CRUD, '/quizquestions/guizquestions') \ No newline at end of file diff --git a/main.py b/main.py index f7819f0..5073702 100644 --- a/main.py +++ b/main.py @@ -33,7 +33,6 @@ from api.student import student_api # database Initialization functions from model.carChat import CarChat -from model.quizgrading import initquizgrading from model.user import User, initUsers from model.section import Section, initSections from model.group import Group, initGroups @@ -42,7 +41,7 @@ # under development from model.binaryLearningGame import initBinaryLearningGameScores from model.quizquestions import quizquestions, initquizquestions -from model.quizgrading import quizgrading, initquizgrading +from model.quizgrading import initquizgrading # server only Views # register URIs for api endpoints diff --git a/model/quizgrading.py b/model/quizgrading.py index ca732cf..78f7305 100644 --- a/model/quizgrading.py +++ b/model/quizgrading.py @@ -6,15 +6,13 @@ class quizgrading(db.Model): __tablename__ = 'quizgrading' id = db.Column(db.Integer, primary_key=True) - _quizgrade = db.Column(db.Integer, nullable=False) - _attempt = db.Column(db.Integer, nullable=False) - _user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) + _quizgrade = db.Column(db.String, nullable=False) + _attempt = db.Column(db.String, nullable=False) - def __init__(self, quizgrade, attempt, user_id): + def __init__(self, quizgrade, attempt): self._quizgrade = quizgrade self._attempt = attempt - self._user_id = user_id def __repr__(self): """ @@ -24,7 +22,7 @@ def __repr__(self): Returns: str: A text representation of how to create the object. """ - return f"Post(id={self.id}, quizgrade={self._quizgrade}, attempt={self._attempt}, user_id={self._user_id})" + return f"" def create(self): """ @@ -53,12 +51,10 @@ def read(self): Returns: dict: A dictionary containing the post data, including user and group names. """ - user = User.query.get(self._user_id) data = { "id": self.id, "quizgrade": self._quizgrade, "attempt": self._attempt, - "user_name": user.name if user else None, } return data @@ -113,16 +109,17 @@ def initquizgrading(): db.create_all() """Tester data for table""" - p1 = quizgrading(quizgrade=50, attempt=1, user_id=1) - p2 = quizgrading(quizgrade=60, attempt=2, user_id=1) - p3 = quizgrading(quizgrade=70, attempt=3, user_id=1) - p4 = quizgrading(quizgrade=80, attempt=4, user_id=1) - - for post in [p1, p2, p3, p4]: + entries = [ + quizgrading(quizgrade=50, attempt=1), + quizgrading(quizgrade=60, attempt=2), + quizgrading(quizgrade=70, attempt=3), + quizgrading(quizgrade=80, attempt=4) + ] + for entry in entries: try: - post.create() - print(f"Record created: {repr(post)}") + db.session.add(entry) + db.session.commit() except IntegrityError: '''fails with bad or duplicate data''' - db.session.remove() - print(f"Records exist, duplicate email, or error: {post.uid}") \ No newline at end of file + db.session.rollback() + print(f"Record creation failed: {entry}") \ No newline at end of file From 499271422ea0f8630f06cd36d3dd18c3a1020c94 Mon Sep 17 00:00:00 2001 From: shriyasshah Date: Tue, 28 Jan 2025 08:40:28 -0800 Subject: [PATCH 6/9] link --- api/quizgrading.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/api/quizgrading.py b/api/quizgrading.py index c09dde7..5700b3c 100644 --- a/api/quizgrading.py +++ b/api/quizgrading.py @@ -77,4 +77,5 @@ def delete(self): api.add_resource(_CRUD, '/quizgrading') if __name__ == '__main__': - app.run(debug=True) \ No newline at end of file + app.run(debug=True) + From f4f666e0b88488422c38a89b94cf69ed5f3e7ad1 Mon Sep 17 00:00:00 2001 From: shriyasshah Date: Wed, 29 Jan 2025 18:17:59 -0800 Subject: [PATCH 7/9] add quiz feature to backend --- api/quizgrading.py | 90 +++++++++++++++++++++++++++++ main.py | 3 + model/quizgrading.py | 132 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 225 insertions(+) create mode 100644 api/quizgrading.py create mode 100644 model/quizgrading.py diff --git a/api/quizgrading.py b/api/quizgrading.py new file mode 100644 index 0000000..898d529 --- /dev/null +++ b/api/quizgrading.py @@ -0,0 +1,90 @@ +import jwt +from flask import Blueprint, request, jsonify, current_app, Response, g +from flask_restful import Api, Resource # used for REST API building +from datetime import datetime +from __init__ import app +from api.jwt_authorize import token_required +from model.quizgrading import quizgrading +from model.user import User +from model.section import Section + + +quizgrading_api = Blueprint('quizgrading_api', __name__, url_prefix='/api') + + +api = Api(quizgrading_api) + + +class GroupAPI: + """ + The API CRUD endpoints correspond to common HTTP methods: + - post: create a new group + - get: read groups + - put: update a group + - delete: delete a group + """ + class _CRUD(Resource): + + + def post(self): + """ + Create a new group. + """ + # Obtain the request data sent by the RESTful client API + data = request.get_json() + # Create a new group object using the data from the request + chat = quizgrading(data['quizgrade'], data['attempt']) + # Save the chat object using the Object Relational Mapper (ORM) method defined in the model + chat.create() + # Return response to the client in JSON format, converting Python dictionaries to JSON format + return jsonify(chat.read()) + + def get(self): + chats = quizgrading.query.all() + allChats = [] + for i in range(len(chats)): + allChats.append(chats[i].read()) + + + # Return a JSON restful response to the client + return jsonify(allChats) + + + def put(self): + # Obtain the current user + # Obtain the request data + data = request.get_json() + # Find the current post from the database table(s) + post = quizgrading.query.get(data['id']) + # Update the post + post._quizgrade = data['quizgrade'] + post._attempt = data['attempt'] + # Save the post + post.update() + # Return response + return jsonify(post.read()) + + + def delete(self): + # Obtain the request data + data = request.get_json() + # Find the current post from the database table(s) + post = quizgrading.query.get(data['id']) + # Delete the post using the ORM method defined in the model + post.delete() + # Return response + return jsonify({"message": "Post deleted"}) + + + """ + Map the _CRUD class to the API endpoints for /post. + - The API resource class inherits from flask_restful.Resource. + - The _CRUD class defines the HTTP methods for the API. + """ + + api.add_resource(_CRUD, '/quizgrading') + +if __name__ == '__main__': + app.run(debug=True) + + diff --git a/main.py b/main.py index 0ebc801..8fa0672 100644 --- a/main.py +++ b/main.py @@ -28,6 +28,7 @@ from api.carChat import car_chat_api from api.newQuizCreation import quizCreation_api from api.binaryConverter import binaryConverter_api +from api.quizgrading import quizgrading_api from api.vote import vote_api # database Initialization functions from model.carChat import CarChat @@ -39,6 +40,7 @@ from model.nestPost import initNestPosts # under development from model.binaryLearningGame import initBinaryLearningGameScores +from model.quizgrading import initquizgrading # server only Views # register URIs for api endpoints @@ -53,6 +55,7 @@ app.register_blueprint(quizCreation_api) app.register_blueprint(binaryConverter_api) app.register_blueprint(binary_history_api) +app.register_blueprint(quizgrading_api) # Tell Flask-Login the view function name of your login route login_manager.login_view = "login" diff --git a/model/quizgrading.py b/model/quizgrading.py new file mode 100644 index 0000000..1419e4d --- /dev/null +++ b/model/quizgrading.py @@ -0,0 +1,132 @@ +from sqlite3 import IntegrityError +from __init__ import app, db +from model.user import User + + +class quizgrading(db.Model): + __tablename__ = 'quizgrading' + + + id = db.Column(db.Integer, primary_key=True) + _quizgrade = db.Column(db.String, nullable=False) + _attempt = db.Column(db.String, nullable=False) + + + def __init__(self, quizgrade, attempt): + + + self._quizgrade = quizgrade + self._attempt = attempt + + + def __repr__(self): + """ + The __repr__ method is a special method used to represent the object in a string format. + Called by the repr(post) built-in function, where post is an instance of the Post class. + + Returns: + str: A text representation of how to create the object. + """ + return f"" + + + def create(self): + """ + The create method adds the object to the database and commits the transaction. + + Uses: + The db ORM methods to add and commit the transaction. + + Raises: + Exception: An error occurred when adding the object to the database. + """ + try: + db.session.add(self) + db.session.commit() + except Exception as e: + db.session.rollback() + raise e + + def read(self): + """ + The read method retrieves the object data from the object's attributes and returns it as a dictionary. + + Uses: + The Group.query and User.query methods to retrieve the group and user objects. + + Returns: + dict: A dictionary containing the post data, including user and group names. + """ + data = { + "id": self.id, + "quizgrade": self._quizgrade, + "attempt": self._attempt, + } + return data + + def update(self): + """ + The update method commits the transaction to the database. + + Uses: + The db ORM method to commit the transaction. + + Raises: + Exception: An error occurred when updating the object in the database. + """ + try: + db.session.commit() + except Exception as e: + db.session.rollback() + raise e + + def delete(self): + """ + The delete method removes the object from the database and commits the transaction. + + Uses: + The db ORM methods to delete and commit the transaction. + + Raises: + Exception: An error occurred when deleting the object from the database. + """ + try: + db.session.delete(self) + db.session.commit() + except Exception as e: + db.session.rollback() + raise e + + +def initquizgrading(): + """ + The initPosts function creates the Post table and adds tester data to the table. + + Uses: + The db ORM methods to create the table. + + Instantiates: + Post objects with tester data. + + Raises: + IntegrityError: An error occurred when adding the tester data to the table. + """ + with app.app_context(): + """Create database and tables""" + db.create_all() + """Tester data for table""" + + entries = [ + quizgrading(quizgrade=50, attempt=1), + quizgrading(quizgrade=60, attempt=2), + quizgrading(quizgrade=70, attempt=3), + quizgrading(quizgrade=80, attempt=4) + ] + for entry in entries: + try: + db.session.add(entry) + db.session.commit() + except IntegrityError: + '''fails with bad or duplicate data''' + db.session.rollback() + print(f"Record creation failed: {entry}") \ No newline at end of file From 8bcd3fc6783c8f7d730bb5231562c2a3e1765e0c Mon Sep 17 00:00:00 2001 From: shriyasshah Date: Wed, 29 Jan 2025 18:24:10 -0800 Subject: [PATCH 8/9] undo --- api/quizgrading.py | 90 ----------------------------- main.py | 3 - model/quizgrading.py | 132 ------------------------------------------- 3 files changed, 225 deletions(-) delete mode 100644 api/quizgrading.py delete mode 100644 model/quizgrading.py diff --git a/api/quizgrading.py b/api/quizgrading.py deleted file mode 100644 index 898d529..0000000 --- a/api/quizgrading.py +++ /dev/null @@ -1,90 +0,0 @@ -import jwt -from flask import Blueprint, request, jsonify, current_app, Response, g -from flask_restful import Api, Resource # used for REST API building -from datetime import datetime -from __init__ import app -from api.jwt_authorize import token_required -from model.quizgrading import quizgrading -from model.user import User -from model.section import Section - - -quizgrading_api = Blueprint('quizgrading_api', __name__, url_prefix='/api') - - -api = Api(quizgrading_api) - - -class GroupAPI: - """ - The API CRUD endpoints correspond to common HTTP methods: - - post: create a new group - - get: read groups - - put: update a group - - delete: delete a group - """ - class _CRUD(Resource): - - - def post(self): - """ - Create a new group. - """ - # Obtain the request data sent by the RESTful client API - data = request.get_json() - # Create a new group object using the data from the request - chat = quizgrading(data['quizgrade'], data['attempt']) - # Save the chat object using the Object Relational Mapper (ORM) method defined in the model - chat.create() - # Return response to the client in JSON format, converting Python dictionaries to JSON format - return jsonify(chat.read()) - - def get(self): - chats = quizgrading.query.all() - allChats = [] - for i in range(len(chats)): - allChats.append(chats[i].read()) - - - # Return a JSON restful response to the client - return jsonify(allChats) - - - def put(self): - # Obtain the current user - # Obtain the request data - data = request.get_json() - # Find the current post from the database table(s) - post = quizgrading.query.get(data['id']) - # Update the post - post._quizgrade = data['quizgrade'] - post._attempt = data['attempt'] - # Save the post - post.update() - # Return response - return jsonify(post.read()) - - - def delete(self): - # Obtain the request data - data = request.get_json() - # Find the current post from the database table(s) - post = quizgrading.query.get(data['id']) - # Delete the post using the ORM method defined in the model - post.delete() - # Return response - return jsonify({"message": "Post deleted"}) - - - """ - Map the _CRUD class to the API endpoints for /post. - - The API resource class inherits from flask_restful.Resource. - - The _CRUD class defines the HTTP methods for the API. - """ - - api.add_resource(_CRUD, '/quizgrading') - -if __name__ == '__main__': - app.run(debug=True) - - diff --git a/main.py b/main.py index 8fa0672..0ebc801 100644 --- a/main.py +++ b/main.py @@ -28,7 +28,6 @@ from api.carChat import car_chat_api from api.newQuizCreation import quizCreation_api from api.binaryConverter import binaryConverter_api -from api.quizgrading import quizgrading_api from api.vote import vote_api # database Initialization functions from model.carChat import CarChat @@ -40,7 +39,6 @@ from model.nestPost import initNestPosts # under development from model.binaryLearningGame import initBinaryLearningGameScores -from model.quizgrading import initquizgrading # server only Views # register URIs for api endpoints @@ -55,7 +53,6 @@ app.register_blueprint(quizCreation_api) app.register_blueprint(binaryConverter_api) app.register_blueprint(binary_history_api) -app.register_blueprint(quizgrading_api) # Tell Flask-Login the view function name of your login route login_manager.login_view = "login" diff --git a/model/quizgrading.py b/model/quizgrading.py deleted file mode 100644 index 1419e4d..0000000 --- a/model/quizgrading.py +++ /dev/null @@ -1,132 +0,0 @@ -from sqlite3 import IntegrityError -from __init__ import app, db -from model.user import User - - -class quizgrading(db.Model): - __tablename__ = 'quizgrading' - - - id = db.Column(db.Integer, primary_key=True) - _quizgrade = db.Column(db.String, nullable=False) - _attempt = db.Column(db.String, nullable=False) - - - def __init__(self, quizgrade, attempt): - - - self._quizgrade = quizgrade - self._attempt = attempt - - - def __repr__(self): - """ - The __repr__ method is a special method used to represent the object in a string format. - Called by the repr(post) built-in function, where post is an instance of the Post class. - - Returns: - str: A text representation of how to create the object. - """ - return f"" - - - def create(self): - """ - The create method adds the object to the database and commits the transaction. - - Uses: - The db ORM methods to add and commit the transaction. - - Raises: - Exception: An error occurred when adding the object to the database. - """ - try: - db.session.add(self) - db.session.commit() - except Exception as e: - db.session.rollback() - raise e - - def read(self): - """ - The read method retrieves the object data from the object's attributes and returns it as a dictionary. - - Uses: - The Group.query and User.query methods to retrieve the group and user objects. - - Returns: - dict: A dictionary containing the post data, including user and group names. - """ - data = { - "id": self.id, - "quizgrade": self._quizgrade, - "attempt": self._attempt, - } - return data - - def update(self): - """ - The update method commits the transaction to the database. - - Uses: - The db ORM method to commit the transaction. - - Raises: - Exception: An error occurred when updating the object in the database. - """ - try: - db.session.commit() - except Exception as e: - db.session.rollback() - raise e - - def delete(self): - """ - The delete method removes the object from the database and commits the transaction. - - Uses: - The db ORM methods to delete and commit the transaction. - - Raises: - Exception: An error occurred when deleting the object from the database. - """ - try: - db.session.delete(self) - db.session.commit() - except Exception as e: - db.session.rollback() - raise e - - -def initquizgrading(): - """ - The initPosts function creates the Post table and adds tester data to the table. - - Uses: - The db ORM methods to create the table. - - Instantiates: - Post objects with tester data. - - Raises: - IntegrityError: An error occurred when adding the tester data to the table. - """ - with app.app_context(): - """Create database and tables""" - db.create_all() - """Tester data for table""" - - entries = [ - quizgrading(quizgrade=50, attempt=1), - quizgrading(quizgrade=60, attempt=2), - quizgrading(quizgrade=70, attempt=3), - quizgrading(quizgrade=80, attempt=4) - ] - for entry in entries: - try: - db.session.add(entry) - db.session.commit() - except IntegrityError: - '''fails with bad or duplicate data''' - db.session.rollback() - print(f"Record creation failed: {entry}") \ No newline at end of file From 83c394198bdaf82987e879c8503390f237bb42a1 Mon Sep 17 00:00:00 2001 From: shriyasshah Date: Wed, 29 Jan 2025 19:17:34 -0800 Subject: [PATCH 9/9] delete quiz questions --- api/quizquestions.py | 72 ----------------------- api/quizquestions1.py | 45 --------------- main.py | 3 - model/quizquestions.py | 128 ----------------------------------------- 4 files changed, 248 deletions(-) delete mode 100644 api/quizquestions.py delete mode 100644 api/quizquestions1.py delete mode 100644 model/quizquestions.py diff --git a/api/quizquestions.py b/api/quizquestions.py deleted file mode 100644 index 6e84f00..0000000 --- a/api/quizquestions.py +++ /dev/null @@ -1,72 +0,0 @@ -from flask import Blueprint, request, jsonify, g -from flask_restful import Api, Resource # used for REST API building -from api.jwt_authorize import token_required -from model.quizquestions import quizquestions - -""" -This Blueprint object is used to define APIs for the Post model. -- Blueprint is used to modularize application files. -- This Blueprint is registered to the Flask app in main.py. -""" -quizquestions_api = Blueprint('quizquestions_api', __name__, url_prefix='/api') - -""" -The Api object is connected to the Blueprint object to define the API endpoints. -- The API object is used to add resources to the API. -- The objects added are mapped to code that contains the actions for the API. -- For more information, refer to the API docs: https://flask-restful.readthedocs.io/en/latest/api.html -""" -api = Api(quizquestions_api) - -class quizquestionsAPI: - """ - Define the API CRUD endpoints for the Post model. - There are four operations that correspond to common HTTP methods: - - post: create a new post - - get: read posts - - put: update a post - - delete: delete a post - """ - class _CRUD(Resource): - @token_required() - def post(self): - # Obtain the current user from the token - current_user = g.current_user - # Obtain the request data sent by the RESTful client API - data = request.get_json() - # Create a new post object using the data from the request - post = quizquestions(data['question']) - # Save the post object using the ORM method defined in the model - post.create() - # Return response to the client in JSON format - return jsonify(post.read()) - - def get(self): - # Obtain the current user - # current_user = g.current_user - # Find all the posts by the current user - posts = quizquestions.query.all() - # Prepare a JSON list of all the posts, uses for loop shortcut called list comprehension - json_ready = [post.read() for post in posts] - # Return a JSON list, converting Python dictionaries to JSON format - return jsonify(json_ready) - - @token_required() - def delete(self): - # Obtain the current user - current_user = g.current_user - # Obtain the request data - data = request.get_json() - # Find the current post from the database table(s) - post = quizquestions.query.get(data['id']) - # Delete the post using the ORM method defined in the model - post.delete() - # Return response - return jsonify({"message": "Post deleted"}) - - """ - Map the _CRUD class to the API endpoints for /post. - - The API resource class inherits from flask_restful.Resource. - - The _CRUD class defines the HTTP methods for the API. - """ - api.add_resource(_CRUD, '/quizquestions') \ No newline at end of file diff --git a/api/quizquestions1.py b/api/quizquestions1.py deleted file mode 100644 index 8760da5..0000000 --- a/api/quizquestions1.py +++ /dev/null @@ -1,45 +0,0 @@ -from flask import Blueprint, request, jsonify, current_app, Response, g -from flask_restful import Api, Resource # used for REST API building -from datetime import datetime -from api.jwt_authorize import token_required -# from model.quizquestions import quizquestions -from model.nestPost import NestPost - -quizquestions_api = Blueprint('quizquestions_api', __name__, url_prefix='/api') - -""" -The Api object is connected to the Blueprint object to define the API endpoints. -- The API object is used to add resources to the API. -- The objects added are mapped to code that contains the actions for the API. -- For more information, refer to the API docs: https://flask-restful.readthedocs.io/en/latest/api.html -""" -api = Api(quizquestions_api) - -class quizquestionsAPI: - """ - Define the API CRUD endpoints for the Post model. - There are four operations that correspond to common HTTP methods: - - post: create a new post - - get: read posts - - put: update a post - - delete: delete a post - """ - class _CRUD(Resource): - @token_required() - def get(self): - # Find all the posts by the current user - # scores = quizquestions.query.all() - scores = NestPost.query.all() - # Prepare a JSON list of all the posts, uses for loop shortcut called list comprehension - json_ready = [score.read() for score in scores] - # Return a JSON list, converting Python dictionaries to JSON format - #return jsonify(json_ready) - return jsonify("Shriya is so cool") - - - """ - Map the _CRUD class to the API endpoints for /post. - - The API resource class inherits from flask_restful.Resource. - - The _CRUD class defines the HTTP methods for the API. - """ - api.add_resource(_CRUD, '/quizquestions/guizquestions') \ No newline at end of file diff --git a/main.py b/main.py index 5073702..ef08e22 100644 --- a/main.py +++ b/main.py @@ -26,7 +26,6 @@ from api.messages_api import messages_api # Adi added this, messages for his website # New API's being tested from api.general import general_api -from api.quizquestions import quizquestions_api from api.binaryLearningGame import binaryLearningGameScores_api from api.vote import vote_api @@ -40,7 +39,6 @@ from model.post import Post, initPosts # under development from model.binaryLearningGame import initBinaryLearningGameScores -from model.quizquestions import quizquestions, initquizquestions from model.quizgrading import initquizgrading # server only Views @@ -56,7 +54,6 @@ app.register_blueprint(student_api) app.register_blueprint(quizgrading_api) # API's following this are under development -app.register_blueprint(quizquestions_api) # Tell Flask-Login the view function name of your login route login_manager.login_view = "login" diff --git a/model/quizquestions.py b/model/quizquestions.py deleted file mode 100644 index 99932ac..0000000 --- a/model/quizquestions.py +++ /dev/null @@ -1,128 +0,0 @@ -from sqlite3 import IntegrityError -from sqlalchemy import Text -from __init__ import app, db -from model.user import User - -class quizquestions(db.Model): - __tablename__ = 'quizquestions' - - id = db.Column(db.Integer, primary_key=True) - _question = db.Column(db.String(255), nullable=False) - - - def __init__(self, question): - self._question = question - - - - def __repr__(self): - """ - The __repr__ method is a special method used to represent the object in a string format. - Called by the repr(post) built-in function, where post is an instance of the Post class. - - Returns: - str: A text representation of how to create the object. - """ - return f"Post(id={self.id}, q1={self._question})" - - - def create(self): - """ - The create method adds the object to the database and commits the transaction. - - Uses: - The db ORM methods to add and commit the transaction. - - Raises: - Exception: An error occurred when adding the object to the database. - """ - try: - db.session.add(self) - db.session.commit() - except Exception as e: - db.session.rollback() - raise e - - def read(self): - """ - The read method retrieves the object data from the object's attributes and returns it as a dictionary. - - Uses: - The Group.query and User.query methods to retrieve the group and user objects. - - Returns: - dict: A dictionary containing the post data, including user and group names. - """ - data = { - "id": self.id, - "q1": self._question, - - } - return data - - def update(self): - """ - The update method commits the transaction to the database. - - Uses: - The db ORM method to commit the transaction. - - Raises: - Exception: An error occurred when updating the object in the database. - """ - try: - db.session.commit() - except Exception as e: - db.session.rollback() - raise e - - def delete(self): - """ - The delete method removes the object from the database and commits the transaction. - - Uses: - The db ORM methods to delete and commit the transaction. - - Raises: - Exception: An error occurred when deleting the object from the database. - """ - try: - db.session.delete(self) - db.session.commit() - except Exception as e: - db.session.rollback() - raise e - - -def initquizquestions(): - """ - The initPosts function creates the Post table and adds tester data to the table. - - Uses: - The db ORM methods to create the table. - - Instantiates: - Post objects with tester data. - - Raises: - IntegrityError: An error occurred when adding the tester data to the table. - """ - with app.app_context(): - """Create database and tables""" - db.create_all() - """Tester data for table""" - - p1 = quizquestions(question="What is the capital of France?") - p2 = quizquestions(question="What is the capital of Britain?") - p3 = quizquestions(question="What is the capital of China?") - p4 = quizquestions(question="What is the capital of India?") - p5 = quizquestions(question="What is the capital of Japan?") - - for question in [p1, p2, p3, p4, p5]: - try: - question.create() - print(f"Record created: {repr(question)}") - except IntegrityError: - '''fails with bad or duplicate data''' - db.session.remove() -