Open MagnusLii opened 10 months ago
This function would parse the incoming JSON from ESP, updates the DB, and return an appropriate HTTP response for the front end team. This code is thought to check for the vote_type and the TopicID from the ESP´s message. TopicID could be pre-defined in the database with its respective titles.
from flask import Flask, request, jsonify
from app import db # Import the SQLAlchemy instance
from app.models import Vote, Topic
@app.route('/submit_vote', methods=['POST'])
def submit_vote():
data = request.json
vote_type = data.get("vote")
topic_id = data.get("TopicID")
if not vote_type or topic_id is None:
return jsonify({'error': 'Missing vote type or topic ID'}), 400
# Check if the topic exists
topic = Topic.query.get(topic_id)
if not topic:
return jsonify({'error': 'Topic not found'}), 404
# Create a new vote for the topic
new_vote = Vote(VoteType=vote_type, TopicID=topic_id, VoteTime=datetime.utcnow())
# Add the new vote to the session and commit the transaction
db.session.add(new_vote) #"session" is an object provided by **SQLAlchemy**
db.session.commit()
return jsonify({'message': 'Vote submitted successfully'}), 201
if __name__ == '__main__':
app.run(debug=True)
Vote Submission Function
Goal
The goal is to create a function that takes the JSON object created by an ESP when sending vote information, parses all relevant information, and creates a query to store the data in the DB.
Arguments
Returns
Function Name:
submitVoteToDB