user15772986
user15772986

Reputation: 41

Background task in Fastapi application

I want to perform background task when delete endpoint returns successful response of 204, but it executes the delete process fine but gives error before executing the background task, error is "Response content longer than Content-Length"

this is my delete_endpoint code:-

from fastapi import APIRouter, Depends, status, Response, BackgroundTasks,Request

def delete_assessment(response: Response,
                      request : Request,
                      background_tasks: BackgroundTasks,
                      header: Header = Depends(HeaderParams),
                      params: DeleteAssessmentArgs = Depends(DeleteAssessmentArgs)
                      ):
    response_obj = {
        'response_code': status.HTTP_204_NO_CONTENT,
        'response_obj': {}
    }
    try:
        dao = AssessmentRequestDao()
        response_obj = dao.delete_assessment(params.assessment_id,params.is_delete_with_submitted_Responses,background_tasks,request)
        response.status_code = response_obj['response_code']

        # Onetream event block
        deleted_assessment =response_obj['response_obj']['categories'][0]
        event_type = AssessmentEventTypes.Deleted
        endpoint = AssessmentEndPoint.Assessment
        if response.status_code == 204:
            background_tasks.add_task(
                onestream_publish_service.send_business_event,
                request.headers.get('Correlation-Id'),
                params.assessment_id,
                endpoint,deleted_assessment,event_type
            )

        response_obj['response_obj'] = {}

        # #till here
        return JSONResponse(response_obj['response_obj'], status_code=response_obj['response_code'])
    except Exception as e:
        logger.exception(e)
        
        return JSONResponse(response_obj['response_obj'], status_code=response_obj['response_code'])here

here is the code of my background task:

def send_business_event(client_correlation_id, object_id,endpoint_name=None,response_object=None,event_type=None):

    if ONESTREAM_ENABLED:
        onestream_payload_list = []
        try:
           # some logic
           
        except Exception as e:
            logger.info("Error in send_business_event: " + str(e))

it works fine if we return status of 200, but gives error in the run() of _asyncio.py becuase request object doen't have value for the content-lenght. It is working before I update the starlette to 0.27.0 or fastapi package to 0.96.0

Upvotes: 0

Views: 195

Answers (1)

Sam
Sam

Reputation: 43

You told FastAPI that there would be no response body, as that’s what HTTP 204 “no content” means.

But you have a return value, so FastAPI/Starlette would have to contradict itself. FastAPI is setting the Content-Length header to 0, and then returning some content.

Either use a different status code, or remove your return values.

Upvotes: 0

Related Questions