I am trying to return a response of a picture from S3. In StreamingResponse.stream_response I see, that chunks are read from the stream and sent to the socket. But on the other side, nothing comes.

import uvicorn
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from aiobotocore.session import get_session
from aioboto3 import session
app = FastAPI()
@app.get("/")
async def main():
sess = get_session()
async with sess.create_client(
's3',
endpoint_url="",
aws_secret_access_key="",
aws_access_key_id=""
) as client:
result = await client.get_object(Bucket="", Key="")
return StreamingResponse(result["Body"], media_type="image/jpeg")
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8080)```
just as an addition, if you use boto3 you don't need to write a wrapper around the StreamingResponse but can just pass the result of result["Body"].iter_chunks() as content:
import boto3
import uvicorn
from fastapi import FastAPI, HTTPException
from fastapi.responses import StreamingResponse
app = FastAPI()
s3 = boto3.client("s3")
@app.get("/")
async def main():
try:
result = s3.get_object(Bucket="my_awesome_bucket", Key="path/to/file")
return StreamingResponse(content=result["Body"].iter_chunks())
except Exception as e:
if hasattr(e, "message"):
raise HTTPException(
status_code=e.message["response"]["Error"]["Code"],
detail=e.message["response"]["Error"]["Message"],
)
else:
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8080)
Did not try it with aioboto3 yet
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With