murphyslemon / Raspberry_Pi_Server

International Sensor Development Project: This project is a voting system that uses a raspberry pi server and multiple voting devices. The system is easy, secure, scalable, and supports anonymous and registered voting. This repository focuses on the Raspberry Pi server.
0 stars 3 forks source link

submitVoteToDB Function #10

Open MagnusLii opened 10 months ago

MagnusLii commented 10 months ago

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

{
  "vote": "Yes/No/Pass",
  "Voting title": "title of vote"
}

Returns

Function Name: submitVoteToDB

Javimetro commented 9 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)