3

Im trying to return a matplotlib.figure.Figure in FastAPI. If I save it like an image it works (code here):

@router.get("/graph/{id_file}", name="Return the graph obtained")
async def create_graph(id_file: str):
        data = HAR.createGraph(id_file)
        graph = HAR.scatterplot(data['dateTimes'], data['label'], "Time", "Activity")
        graph.savefig('saved_figure.jpg')
        
        return FileResponse('saved_figure.jpg')

Where graph is my Figure. But I would like to show it without saving in mi computer.

a.v. Magia
  • 43
  • 1
  • 4

1 Answers1

3

savefig can accept binary file-like object. It can be used to achieve what you want.

The code could be:

from io import BytesIO
from starlette.responses import StreamingResponse
...


@router.get("/graph/{id_file}", name="Return the graph obtained")
async def create_graph(id_file: str):
    data = HAR.createGraph(id_file)
    graph = HAR.scatterplot(data['dateTimes'], data['label'], "Time", "Activity")
    
    # create a buffer to store image data
    buf = BytesIO()
    graph.savefig(buf, format="png")
    buf.seek(0)
        
    return StreamingResponse(buf, media_type="image/png")
umat
  • 607
  • 1
  • 13
  • 25