fastapi: After executing first request, rest of the request got stuck till the first one is executed


##  IN MY app/repository/connector.py  

import os
import sys
import psutil


async def get_all_lines(loc="xyz.log"):
    try:
        with open(loc) as read_file:
            all_lines = read_file.readlines()
            all_lines = list(map(lambda s: s.strip(), all_lines))
            all_lines = [s for s in all_lines if s]
        return all_lines[-1].split("-")[0].split(",")[0]
    except Exception as e:
        return "[ERROR] Unable to process file {}".format(loc)


async def checkIfProcessRunning(processName):
    for proc in psutil.process_iter():
        try:
            if processName.lower() in proc.name().lower():
                return True
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
    return False

async def get_running_status(processes=['ABC', 'chrome.exe', "java"]):
    status = ""
    for process in processes:
        if await checkIfProcessRunning(process):
            status += "{} is in running state\n".format(process)
        else:
            status += "{} is NOT in running state\n".format(process)
    return status

##  IN MY app/router/connection.py  

from fastapi import APIRouter, Depends, status, HTTPException
from .. import schemas, oauth2
from typing import List
from .. repository import connector

router = APIRouter(
    tags=['connector'],
    prefix="/connector"
)


@router.get('/', status_code=200)
async def show(current_user = Depends(oauth2.get_current_user)):
    status = await connector.get_all_lines()
    return {"last_connected_at": status}

@router.get('/process_running_status', status_code=200)
async def show(current_user = Depends(oauth2.get_current_user)):
    status = await connector.get_running_status()
    return {"process_status": status}

Description

  • Open the browser and I call the endpoint /process_running_status.
  • It returns a { “process_status”: "ABC is NOT in running state\nchrome.exe is in running state\njava is in running state }` but takes sometime to respond
  • But when this is executing, my all other requests to the API are on hold till it gets completed. Am i doing this right way?
  • I want if this request /process_running_status is running, it should not hold the other request.

Environment

  • OS: Windows:

  • FastAPI Version: 0.63.0

  • Python version: Python3.9

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 15 (1 by maintainers)

Most upvoted comments

Also, any help is much appreciated. @tiangolo or anyone from this community. I request all of you to Please look into this on priority

an example

import time
import concurrent.futures


def func(num: int):
    time.sleep(1)
    print(num)


nums = [1, 2, 3]


with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:

    executor.map(func, nums)

Ok, but any idea how I can code with the help of multithreading to achieve the goal in fastapi here. Can you please paste the code. I will be extremely grateful to you

if still the same is After executing first request, rest of the request got stuck till the first one is executed: this is not a question, because you do not use async and you can use thead or process. elif the error is ValueError: [TypeError("'coroutine' object is not iterable"): i do not know

@panla still the same.

IN MY app/repository/connector.py

import os
import sys
import psutil


def get_all_lines(loc="xyz.log"):
    try:
        with open(loc) as read_file:
            all_lines = read_file.readlines()
            all_lines = list(map(lambda s: s.strip(), all_lines))
            all_lines = [s for s in all_lines if s]
        return all_lines[-1].split("-")[0].split(",")[0]
    except Exception as e:
        return "[ERROR] Unable to process file {}".format(loc)


def checkIfProcessRunning(processName):
    for proc in psutil.process_iter():
        try:
            if processName.lower() in proc.name().lower():
                return True
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
    return False

def get_running_status(processes=['ABC', 'chrome.exe', "java"]):
    status = ""
    for process in processes:
        if checkIfProcessRunning(process):
            status += "{} is in running state\n".format(process)
        else:
            status += "{} is NOT in running state\n".format(process)
    return status

IN MY app/router/connection.py

from fastapi import APIRouter, Depends, status, HTTPException
from .. import schemas, oauth2
from typing import List
from .. repository import connector

router = APIRouter(
    tags=['connector'],
    prefix="/connector"
)


@router.get('/', status_code=200)
async def show(current_user = Depends(oauth2.get_current_user)):
    status = connector.get_all_lines()
    return {"last_connected_at": status}

@router.get('/process_running_status', status_code=200)
async def show(current_user = Depends(oauth2.get_current_user)):
    status = connector.get_running_status()
    return {"process_status": status}

you can try it, andI haven’t tested, ha ha ha ha.