-
First Check
Commit to Help
Example Codefrom fastapi.middleware.gzip import GZipMiddleware
from starlette.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(GZipMiddleware)
csv_file(path: str):
with open(path) as f:
yield f.readline()
@app.get("/receivings")
def receivings(start: str = start_date, end: str = now) -> StreamingResponse:
return StreamingResponse(csv_file(path), media_type='text/csv')
app.add_middleware(
CORSMiddleware,
allow_origins=["https://www.website.com"],
allow_methods=["POST"],
allow_headers=["*"]
)
if __name__ == '__main__':
uvicorn.run("middleserver:app", host="0.0.0.0", port=8080, log_level='trace')Description
Operating SystemWindows Operating System DetailsNo response FastAPI Version0.75 Python Version3.10.3 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 7 comments
-
|
You try add middleware after your receivings function? |
Beta Was this translation helpful? Give feedback.
-
|
Yes, made no difference. I've abandoned this entire method of responses as a result. |
Beta Was this translation helpful? Give feedback.
-
|
I played around a bit with this, and found a couple of quirks. First of, your generator that you feed as However, the Starlette documentation on
And, when I change your code to the following: @app.get("/receivings")
def receivings() -> StreamingResponse:
file = open("filepath/1mb.txt")
return StreamingResponse(file, media_type='text/csv')it does work (meaning, I get the proper headers and the response is gzipped). However, I never close the file explicitly and that worries me. When wrapping the response into a context manager like so: with open(path) as f:
return Streamingresponse(f, media_type='text/csv')raises a ValueError: Strange behaviour, and I cannot put my finger on it yet. I would expect we would need to close the file-handler ourselves, but trying to do so gives the ValueError. |
Beta Was this translation helpful? Give feedback.
-
|
Hey guys! I read the code that
@JarroVGIT That will be great. But only user pass below code can do it def csv_file(path: str):
with open(path) as f:
for line in f:
yield line |
Beta Was this translation helpful? Give feedback.
-
|
Of course, that is a neat solution! |
Beta Was this translation helpful? Give feedback.
-
|
yah this streaming response doing no compress at split file either .... i tried brotli and gzip both fail |
Beta Was this translation helpful? Give feedback.
-
|
There's nothing FastAPI can do about it. This is entirely Starlette. Feel free to create a discussion over there. |
Beta Was this translation helpful? Give feedback.
There's nothing FastAPI can do about it. This is entirely Starlette.
Feel free to create a discussion over there.