Defínelo como un parámetro de función de operación de path (o dependencia).
Si estás usando una función def regular, puedes usar el atributo upload_file.file
para acceder al archivo estándar de Python crudo (bloqueante, no async), útil y
necesario para código no async.
def__init__(self,file:BinaryIO,*,size:int|None=None,filename:str|None=None,headers:Headers|None=None,)->None:self.filename=filenameself.file=fileself.size=sizeself.headers=headersorHeaders()# Capture max size from SpooledTemporaryFile if one is provided. This slightly speeds up future checks.# Note 0 means unlimited mirroring SpooledTemporaryFile's __init__self._max_mem_size=getattr(self.file,"_max_size",0)
Para ser awaitable, compatible con async, esto se ejecuta en un threadpool.
PARÁMETRO
DESCRIPCIÓN
size
El número de bytes a leer del archivo.
TIPO:intDEFAULT:-1
Código fuente en fastapi/datastructures.py
asyncdefread(self,size:Annotated[int,Doc(""" The number of bytes to read from the file. """),]=-1,)->bytes:""" Read some bytes from the file. To be awaitable, compatible with async, this is run in threadpool. """returnawaitsuper().read(size)
Normalmente no usarías esto con un archivo que lees en una petición.
Para ser awaitable, compatible con async, esto se ejecuta en un threadpool.
PARÁMETRO
DESCRIPCIÓN
data
Los bytes a escribir al archivo.
TYPE:bytes
Código fuente en fastapi/datastructures.py
asyncdefwrite(self,data:Annotated[bytes,Doc(""" The bytes to write to the file. """),],)->None:""" Write some bytes to the file. You normally wouldn't use this from a file you read in a request. To be awaitable, compatible with async, this is run in threadpool. """returnawaitsuper().write(data)
Cualquier próxima lectura o escritura se hará desde esa posición.
Para ser awaitable, compatible con async, esto se ejecuta en un threadpool.
PARÁMETRO
DESCRIPCIÓN
offset
La posición en bytes a la que moverse en el archivo.
TIPO:int
Código fuente en fastapi/datastructures.py
asyncdefseek(self,offset:Annotated[int,Doc(""" The position in bytes to seek to in the file. """),],)->None:""" Move to a position in the file. Any next read or write will be done from that position. To be awaitable, compatible with async, this is run in threadpool. """returnawaitsuper().seek(offset)