1

I have a Server on FastAPI and a Client running on ReactJS. I am running a loop(analysis()) on Server which starts when an API call(/start) is made from React front end on button click which works fine. But I need to stop the loop as well when another event is fired from same button on a different API call(/stop).

I am trying to achieve this by making asyn tasks run on server but I am not able to close the tasks by changing the global variable(analyzing). Currently the loop starts on first API call but is stuck on it and keeps printing "currenlty analyzing". The 2nd API call of "/stop" is not reaching the server.

Server Side code - FastAPI

analyzing = True

async def analysis():
    while analyzing:
        print("currenlty analyzing")

router = APIRouter(
    prefix='/analysis',
    tags=['Analysis']
)

@router.get("/stop", status_code=status.HTTP_201_CREATED)
def stop_analysis(db: Session = Depends(get_db)):
    global analyzing
    analyzing = False
    print("here in stop API")
    return {"message":"In stop analysis"}


@router.get("/start")
async def start_analysis(db: Session = Depends(get_db)):
    global analyzing
    analyzing = True
    task = asyncio.create_task(analysis())
    return {"message":"In start analysis"}

Client Side code - ReactJS

import React, { useState, useRef, useEffect } from 'react';
import axios from 'axios'

const Analysis = () => {


  const [recording, setRecording] = useState(false);

  const startRecording = async () => {

    try {
        let res = await axios.get("http://127.0.0.1:8000/analysis/start");
        let res1 = res.data;
        console.log(res1);
    } catch(e){
        console.log(e)
    }
    setRecording(true);
  }

  const stopRecording = async () => {
  
    console.log("React stop function top")
    try {
        let res = await axios.get("http://127.0.0.1:8000/analysis/stop");
        let res1 = res.data;
        console.log(res1);
    } catch(e){
        console.log(e)
    }
    setRecording(false);
}


  return (
    <div className='user__recording'>
      
        {recording ? (
                console.log("recording")
            ) : (
                console.log("Not recording")
        )}
        
        <button className='user__recording__button' onClick={recording ? stopRecording : startRecording}>
            {recording ? 'Stop recording' : 'Start recording'}
        </button>    
            
    </div>
  );
};

export default Analysis;

Please let me know if there is any better way to achieve this funcitonility with the same tech stack, I tried doing this with SocketIO sessions but couldn't make it work.

  • Does this answer your question? [How to stop FastAPI app after raising an Exception?](https://stackoverflow.com/questions/74517267/how-to-stop-fastapi-app-after-raising-an-exception) – Chris Mar 21 '23 at 07:05

0 Answers0