1

I have a frontend in React.js that is trying to send data to a Flask backend to get an output from my AWS database. The relevant parts of my code looks as follows:

Frontend:

import './dropdown.css';
import React, { useState } from "react";
import { MultiSelect } from 'primereact/multiselect';
import Button from './button.js';
import Pie from './piechart.js';
import Slider from './slider.js';
import ChangeData from './changedata.js';

var query_details = {
    filters: {Gender: "", RaceEthnicity: "", TypeLoss: ""},
    outputCol: "",
    category: "",
    time: "", 
    person: "", 
}

export function Dropdown(){

    // Multiselect code: https://primereact.org/multiselect/
    const [selectedGender, setSelectedGender] = useState(null);
    const genders = ['Male','Female' ];

    const [selectedAssessmentType, setSelectedAssessmentType] = useState(null);
    const assessmentTypes = ['Parent','Participant'];

    const [selectedTypeLoss, setSelectedTypeLoss] = useState(null);
    const typeOfLoss = ['Death of a parent or loved one',
    ...
    'Deportation of a parent or loved one'];

    const [selectedRace, setSelectedRace] = useState(null);
    const races = ['White or Caucasian','Hispanic or Latino',
        ...
    'American Indian or Alaskan Native'];

    const [selectedLevel, setSelectedLevel] = useState(null);
    const levels = ['Sunbeam','Rainbow','Spectrum'];

    const [selectedPrePost, setSelectedPrePost] = useState(null);
    const prePost = ['Pre','Post','Change'];

    const [selectedOutputCol, setSelectedOutputCol] = useState(null);
    const outcol = [
        { name: 'School Performance', code: 'SchoolPerformance'},
         ....
        { name: 'Aggregate Data', code: 'AggregateData'},
    ];

    const [iData, setiData] = useState([]);

    const [showCd, setShowCd] = useState(false);
    const [showSlider, setShowSlider] = useState(false);
    const [showPie, setShowPie] = useState(false);

     const handleButtonClick = () => {
        setShowCd(selectedPrePost.includes('Change') && !(selectedOutputCol.includes('AggregateData')));
        setShowPie(selectedOutputCol.includes('AggregateData'));
        setShowSlider(!(selectedPrePost.includes('Change') || selectedOutputCol.includes('AggregateData')));
        query_details.filters.Gender = selectedGender;
        query_details.filters.RaceEthnicity = selectedRace;
        query_details.filters.TypeLoss = selectedTypeLoss;
        query_details.outputCol = selectedOutputCol;
        query_details.category = selectedLevel;
        query_details.time = selectedPrePost;
        query_details.person = selectedAssessmentType;
        fetch('https://4nh9******.execute-api.us-east-1.amazonaws.com/update', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(query_details),
          })
          .then(response => {
                if (response.ok){
                    response.json(); 
                    console.log("Request successful");
                }
                else {
                    console.error("Request failed");
                }
            }) 
            .catch(error => {
              console.error('Error while sending data: ', error);
            });
        fetch('https://4nh9******.execute-api.us-east-1.amazonaws.com/', { 
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
              }
        })
        .then(response => response.json())
        .then(response => {
            setiData(response); 
            console.log("Data retrieval successful");
        }) 
        .catch(error => {
            console.error("Error while retrieving data: ", error);
        });
    };

    return (
    
    <div className="dropdown-all">

        <div className="dropdown-gender">
            <MultiSelect value={selectedGender} onChange={(e) => setSelectedGender(e.value)} options={genders} 
            placeholder="Gender" maxSelectedLabels={3} style={{ width: "100%", height: '100%' }} />
        </div>

        <div className="dropdown-assessmentType">
            <MultiSelect value={selectedAssessmentType} onChange={(e) => setSelectedAssessmentType(e.value)} options={assessmentTypes}  
            placeholder="Assessment Type" maxSelectedLabels={3} style={{ width: "100%", height: '100%' }}/>
        </div>
        
        <div className="dropdown-typeOfLoss">
            <MultiSelect value={selectedTypeLoss} onChange={(e) => setSelectedTypeLoss(e.value)} options={typeOfLoss} 
            placeholder="Type of loss" maxSelectedLabels={3} style={{ width: "100%", height: '100%' }}/>
        </div>

        <div className="dropdown-race">
            <MultiSelect value={selectedRace} onChange={(e) => setSelectedRace(e.value)} options={races} 
            placeholder="Race/Ethnicity" maxSelectedLabels={2} style={{ width: "100%", height: '100%' }}/>
        </div>

        <div className="dropdown-level">
            <MultiSelect value={selectedLevel} onChange={(e) => setSelectedLevel(e.value)} options={levels}  
            placeholder="Assessment Level" maxSelectedLabels={1} style={{ width: "100%", height: '100%' }}/>
        </div>

        <div className="dropdown-prePost">
            <MultiSelect value={selectedPrePost} onChange={(e) => setSelectedPrePost(e.value)} options={prePost}  
            placeholder="Pre/Post Data" maxSelectedLabels={3} selectionLimit = {1} showSelectAll={false} style={{ width: "100%", height: '100%' }}/>
        </div>
        <div className="dropdown-outputCol">
            <MultiSelect value={selectedOutputCol} onChange={(e) => setSelectedOutputCol(e.value)} options={outcol} optionLabel="name" optionValue="code"
            placeholder="Output Column" maxSelectedLabels={1} selectionLimit = {1} showSelectAll={false} style={{ width: "100%", height: '100%' }}/>
        </div>
        <button className = "buttonShadow" onClick={handleButtonClick}>Get Data!</button>
        {showCd && <ChangeData inputData={iData} />}
        {showSlider && <Slider inputData={iData} />}
        {showPie && <Pie inputData={iData} />}

    </div> );
}

export default Dropdown

Backend:

from flask import Flask, jsonify, request, render_template, redirect, url_for
import requests
#import db_client as db_client
import json

from flask_cors import CORS

app = Flask(__name__)
CORS(app)

# Global variable for storing state

# query has values in [0,3] with the following mapping:
# 0 - no query yet
# 1 - fetchFromTable
# 2 - fetchChangeData
# 3 - fetchAggregateData

# result maintains the processed results from the last query

state = {'query': 0, 'result':None, "queryDetails":{}}
base_url = 'https://4nh*******.execute-api.us-east-1.amazonaws.com/'

@app.route('/', methods=["GET"])
def index():
    if state["query"] and state["result"] is None:
        # Perform the necessary API call and update the result based on the query
        if state["query"] == 1:
            # Logic for fetchFromTable query
            # Make the API call, process the data, and update the state
            state["result"] = fetch_from_table(state["queryDetails"])
        elif state["query"] == 2:
            # Logic for fetchChangeData query
            # Make the API call, process the data, and update the state
            state["result"] = fetch_change_data(state["queryDetails"])
        elif state["query"] == 3:
            # Logic for fetchAggregateData query
             # Make the API call, process the data, and update the state
            state["result"] = fetch_aggregate_data(state["queryDetails"])
        elif state["query"] == 4:
            # Add CSV data to the table
            state["result"] = add_to_table(state["queryDetails"])

        # Reset the query after processing
        # state["query"] = 0

    return jsonify(state["result"])

@app.route('/update', methods=['POST'])
def update_state():
    #example queryDetails obj
    #query_details = {
    #    "filters":{"Gender":["Male"], "RaceEthnicity":["White or Caucasian"]},
    #    "outputCol":"PersonalBehavior",
    #    "category": "Rainbow", 
    #    "time": ["Pre", "Post"],
    #    "person": ["Participant", "Parent"]
    #}
    data = request.get_json()

    #set state['query']
    #state['query'] = data['query']
    if data["time"] == ["Change"] and data["outputCol"] != "Aggregate":
        state["query"] = 2
    elif data["outputCol"] == "Aggregate":
        state["query"] = 3
    else:
        state["query"] = 1
    
    
    query_details = {}
    query_details["category"] = data["category"] 
    query_details["filters"] = data["filters"]
    query_details["outputCol"] = data["outputCol"]
    query_details["tableName"] = data["time"] + data["person"] + data["category"]
    state['queryDetails'] = query_details
    state['result'] = None  # Reset the result to trigger re-processing
    return 

def generate_query_string(fn_name, table_string, table_name,filters,output_col):
    #'https://4nh*******.execute-api.us-east-1.amazonaws.com/fetchFromTable?tableName=PostParticipantRainbow&filters={"Gender":["Male"], "RaceEthnicity": ["White or Caucasian"]}&outputCol=PersonalBehavior'
    filters = json.dumps(filters)
    return base_url + f"{fn_name}?{table_string}={table_name}&filters={filters}&outputCol={output_col}"

def fetch_averages(query_string):
    result_sums = {}
    result_counts = {}
    all_results = make_api_call(query_string)
    for ind_res in all_results:
        for k,v in ind_res.items():
            if k not in result_sums:
                result_sums[k] = 0
                result_counts[k] = 0
            result_sums[k] += v
            result_counts[k] += 1
    result = {}
    for q, s in result_sums.items():
        result[q] = round(s/result_counts[q],2)
    return result 

def fetch_from_table(query_details):
    #question mapping to average answer
    query_string = generate_query_string("fetchFromTable", "tableName", query_details["tableName"], query_details["filters"], query_details["outputCol"])
    state["result"] = fetch_averages(query_string)

def fetch_change_data(query_details):
    #question mapping to delta average as a percent of pre
    #delta: post average - pre average
    pre_query_string = generate_query_string("fetchFromTable", "tableName", "Pre" + query_details["tableName"], query_details["filters"], query_details["outputCol"])
    pre_result = fetch_averages(pre_query_string)
    post_query_string = generate_query_string("fetchFromTable", "tableName", "Post" + query_details["tableName"], query_details["filters"], query_details["outputCol"])
    post_result = fetch_averages(post_query_string)
    result = {}
    for k,v in pre_result.items():
        result[k] = round(post_result[k] - v, 2)
    state["result"] = result

def fetch_aggregate_data(query_details):
    #straight output
    query_string = generate_query_string("fetchAggregateData", "category", query_details["category"], query_details["filters"], query_details["outputCol"])
    state["result"] = make_api_call(query_string)



def make_api_call(endpoint):
    try:
        response = requests.get(endpoint)
        response.raise_for_status()  # Raise an exception if the request was unsuccessful (status code >= 400)
        result = response.json()  # Assuming the response is in JSON format
        return result
    except requests.exceptions.RequestException as e:
        print(f"Error: {e}")
        return None

if __name__ == '__main__':
    app.run()

(with slight changes in the front end for brevity and privacy). However, I keep getting the following error:

Error while retrieving data: TypeError: Failed to fetch
    at handleButtonClick (c:\Users\anous\OneDrive\Desktop\DISC\RFAC\frontend\src\components\dropdown.js:119:1)
    at HTMLUnknownElement.callCallback (c:\Users\anous\OneDrive\Desktop\DISC\RFAC\frontend\node_modules\react-dom\cjs\react-dom.development.js:4164:1)
    at Object.invokeGuardedCallbackDev (c:\Users\anous\OneDrive\Desktop\DISC\RFAC\frontend\node_modules\react-dom\cjs\react-dom.development.js:4213:1)
    at invokeGuardedCallback (c:\Users\anous\OneDrive\Desktop\DISC\RFAC\frontend\node_modules\react-dom\cjs\react-dom.development.js:4277:1)
    at invokeGuardedCallbackAndCatchFirstError (c:\Users\anous\OneDrive\Desktop\DISC\RFAC\frontend\node_modules\react-dom\cjs\react-dom.development.js:4291:1)
    at executeDispatch (c:\Users\anous\OneDrive\Desktop\DISC\RFAC\frontend\node_modules\react-dom\cjs\react-dom.development.js:9041:1)
    at processDispatchQueueItemsInOrder (c:\Users\anous\OneDrive\Desktop\DISC\RFAC\frontend\node_modules\react-dom\cjs\react-dom.development.js:9073:1)
    at processDispatchQueue (c:\Users\anous\OneDrive\Desktop\DISC\RFAC\frontend\node_modules\react-dom\cjs\react-dom.development.js:9086:1)
    at dispatchEventsForPlugins (c:\Users\anous\OneDrive\Desktop\DISC\RFAC\frontend\node_modules\react-dom\cjs\react-dom.development.js:9097:1)
    at http://localhost:3000/static/js/bundle.js:25487:16 
{stack: 'TypeError: Failed to fetch
    at handleButto…//localhost:3000/static/js/bundle.js:25487:16', message: 'Failed to fetch'}

with a similar one for sending data through my POST call. Both my Flask backend and frontend are running simultaneously on different ports (127.0.0.1:5000 and localhost:3000 respectively), and I thought CORS would allow this to happen. I have extensively tested my AWS endpoint with Postman as well and it's working. Even the following code works fine:

import requests
import json
import pprint

base_url = 'https://4nh*******.execute-api.us-east-1.amazonaws.com/'

def generate_query_string(fn_name, table_string, table_name,filters,output_col):
    #'https://4nh*******.execute-api.us-east-1.amazonaws.com/fetchFromTable?tableName=PostParticipantRainbow&filters={"Gender":["Male"], "RaceEthnicity": ["White or Caucasian"]}&outputCol=PersonalBehavior'
    filters = json.dumps(filters)
    return base_url + f"{fn_name}?{table_string}={table_name}&filters={filters}&outputCol={output_col}"

def fetch_averages(query_string):
    result_sums = {}
    result_counts = {}
    all_results = make_api_call(query_string)
    for ind_res in all_results:
        for k,v in ind_res.items():
            if k not in result_sums:
                result_sums[k] = 0
                result_counts[k] = 0
            result_sums[k] += v
            result_counts[k] += 1
    result = {}
    for q, s in result_sums.items():
        result[q] = round(s/result_counts[q],2)
    return result


def fetch_aggregate_data(query_details):
    #straight output
    query_string = generate_query_string("fetchAggregateData", "category", query_details["category"], query_details["filters"], query_details["outputCol"])
    return make_api_call(query_string)

def fetch_from_table(query_details):
    #question mapping to average answer
    query_string = generate_query_string("fetchFromTable", "tableName", query_details["tableName"], query_details["filters"], query_details["outputCol"])
    return fetch_averages(query_string)

def fetch_change_data(query_details):
    #question mapping to delta average as a percent of pre
    #delta: post average - pre average
    pre_query_string = generate_query_string("fetchFromTable", "tableName", "Pre" + query_details["tableName"], query_details["filters"], query_details["outputCol"])
    pre_result = fetch_averages(pre_query_string)
    #print(pre_result)
    post_query_string = generate_query_string("fetchFromTable", "tableName", "Post" + query_details["tableName"], query_details["filters"], query_details["outputCol"])
    post_result = fetch_averages(post_query_string)
    #print(post_result)
    #input()
    result = {}
    for k,v in pre_result.items():
        result[k] = round(post_result[k] - v,2)
    return result

def make_api_call(endpoint):
    try:
        response = requests.get(endpoint)
        response.raise_for_status()  # Raise an exception if the request was unsuccessful (status code >= 400)
        result = response.json()  # Assuming the response is in JSON format
        return result
    except requests.exceptions.RequestException as e:
        print(f"Error: {e}")
        return None

query_details = {
    "category":"Spectrum",
    "filters":{"Gender":["Female"]},
    "outputCol":"RaceEthnicity"
}
query = 'https://4nh*******.execute-api.us-east-1.amazonaws.com/fetchFromTable?tableName=PostParticipantRainbow&filters={"Gender":["Male"], "RaceEthnicity": ["White or Caucasian"]}&outputCol=PersonalBehavior'
pprint.pprint(fetch_aggregate_data(query_details))

So I just can't figure out what's going wrong. Any ideas? Any help at all would be appreciated!

1 Answer 1

0

There is a similiar example in AWS Github that can help you.

This example shows you how to use the AWS SDK for Python (Boto3) to create a REST service that lets you do the following:

  1. Build a Flask REST service that integrates with AWS services.
  2. Read, write, and update work items that are stored in an Amazon Aurora Serverless database.
  3. Create an AWS Secrets Manager secret that contains database credentials and use it to authenticate calls to the database.
  4. Use Amazon Simple Email Service (Amazon SES) to send email reports of work items.

The REST service is used in conjunction with a React client to present a fully functional web application.

https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/aurora_item_tracker

2
  • I have already used DynamoDB, so is there anything I can do with that?
    – Diana
    Jun 27 at 17:29
  • Amazon Aurora Serverless database was just an example database to use. The important thing to note here is a Python backend and a React front end and how they work together.
    – smac2020
    Jun 27 at 18:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.