Step 2
from flask import Blueprint, request, jsonify, g
from flask_restful import Api, Resource
kanhay_api = Blueprint('kanhay_api', __name__, url_prefix='/api')
api = Api(kanhay_api)
class KanhayAPI:
class _K_Person(Resource):
def get(self):
return jsonify({
"name": "Kanhay Patil",
"age": 16,
"classes": ["Honors Principles of Engineering", "Advanced Placement Computer Science Principles", "Advance Placement English Seminar 1", "Advance Placement AP Calculus AB", "Advance Placement Physics C Mechanics"],
"favorite": {
"color": "Blue",
"number": 7
}
})
api.add_resource(KanhayAPI._K_Person, "/kanhay")
Step 3
I implemented the theme switching feature by adding a theme_mode column to the database schema to store each user’s theme preference, defaulting to light. I created a POST endpoint to handle theme change requests. When a request is received, I extract the user ID from the JWT in the cookies, find the user in the database, and update their theme_mode based on the provided value. This ensures that the user’s theme preference is saved and persists even after logging out. Here’s the endpoint code:
@app.route('/api/theme', methods=['POST'])
def change_theme():
data = request.get_json()
auth = request.cookies.get("jwt_python_flask")
jwtDecoded = jwt.decode(auth, current_app.config["SECRET_KEY"], algorithms="HS256")
values = list(jwtDecoded.values())
dui = values[0]
user = User.query.filter_by(_uid=dui).first()
if user:
_values = list(data.values())
user._theme_mode = _values[0] # Directly setting the attribute
db.session.commit() # Make sure to commit the transaction
return jsonify({"response": "good"}), 200
else:
return jsonify({"response": "user not found"}), 404