fix: uploaded file were closed automatically before the model could infer their data

This commit is contained in:
faraphel 2025-01-10 11:05:41 +01:00
parent 639425ad7d
commit b89fafdc96
6 changed files with 62 additions and 12 deletions

39
source/utils/fastapi.py Normal file
View file

@ -0,0 +1,39 @@
"""
fastapi.UploadFile currently have an issue where using an UploadFile and giving it to a StreamingResponse close it.
Fix from this comment :
https://github.com/fastapi/fastapi/issues/10857#issuecomment-2079878117
"""
from fastapi import UploadFile
class UploadFileFix(UploadFile):
"""Patches `fastapi.UploadFile` due to buffer close issue.
See the related github issue:
https://github.com/tiangolo/fastapi/issues/10857
"""
def __init__(self, upload_file: UploadFile) -> None:
"""Wraps and mutates input `fastapi.UploadFile`.
Swaps `close` method on the input instance so it's a no-op when called
by the framework. Adds `close` method of input as `_close` here, to be
called later with overridden `close` method.
"""
self.filename = upload_file.filename
self.file = upload_file.file
self.size = upload_file.size
self.headers = upload_file.headers
_close = upload_file.close
setattr(upload_file, "close", self._close)
setattr(self, "_close", _close)
async def _close(self) -> None:
pass
async def close(self) -> None: # noqa: D102
await self._close()

View file

@ -1,8 +1,7 @@
import inspect
from datetime import datetime
import fastapi
from fastapi import UploadFile
# the list of types and their name that can be used by the API
types: dict[str, type] = {
@ -16,7 +15,7 @@ types: dict[str, type] = {
"set": set,
"dict": dict,
"datetime": datetime,
"file": fastapi.UploadFile,
"file": UploadFile,
}