How do I return an image in fastAPI?

前端 未结 6 1906
灰色年华
灰色年华 2020-12-14 17:51

Using the python module fastAPI, I can\'t figure out how to return an image. In flask I would do something like this:

@app.route(\"/vector_image\", methods=[         


        
6条回答
  •  失恋的感觉
    2020-12-14 18:40

    The answer from @SebastiánRamírez pointed me in the right direction, but for those looking to solve the problem, I needed a few lines of code to make it work. I needed to import FileResponse from starlette (not fastAPI?), add CORS support, and return from a temporary file. Perhaps there is a better way, but I couldn't get streaming to work:

    from starlette.responses import FileResponse
    from starlette.middleware.cors import CORSMiddleware
    import tempfile
    
    app = FastAPI()
    app.add_middleware(
        CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]
    )
    
    @app.post("/vector_image")
    def image_endpoint(*, vector):
        # Returns a raw PNG from the document vector (define here)
        img = my_function(vector)
    
        with tempfile.NamedTemporaryFile(mode="w+b", suffix=".png", delete=False) as FOUT:
            FOUT.write(img)
            return FileResponse(FOUT.name, media_type="image/png")
    

提交回复
热议问题