FastAPI (24) - explain File and upload File
preface
You can use the File provided by FastAPI to define the File to be uploaded by the client
Before learning File, you'd better learn Form: https://www.cnblogs.com/poloyy/p/15311533.html
Install Python multipart
To use File, you need to install this library first
pip install python-multipart
FIle
File inherits Form, so you can define the same metadata and additional validation as Form
Upload chestnuts for a single file
#!usr/bin/env python # -*- coding:utf-8 _*- """ # author: Little pineapple test notes # blog: https://www.cnblogs.com/poloyy/ # time: 2021/9/22 9:52 am # file: 21_File.py """ import uvicorn from fastapi import FastAPI, File, UploadFile app = FastAPI() # The file parameter type is bytes @app.post("/files/") async def create_file(file: bytes = File(...)): return {"file_size": len(file)} # The file parameter type is UploadFile @app.post("/uploadfile/") async def create_upload_file(file: UploadFile = File(...)): result = { "filename": file.filename, "content-type": file.content_type, "read": await file.read() } return result if __name__ == "__main__": uvicorn.run(app="21_File:app", host="127.0.0.1", port=8080, reload=True, debug=True)
a key
- Because the methods provided by the UploadFile object are async asynchronous, await should be added when calling, such as await file Read() (async/await will be explained later)
- When asynchronous methods are used, the FastAPI runs file methods in the thread pool and waits for them
Calling async method without await will report an error
raise ValueError(errors) ValueError: [TypeError("'coroutine' object is not iterable"), TypeError('vars() argument must have __dict__ attribute')] WARNING: StatReload detected file change in '21_File.py'. Reloading...
File: request result of bytes
File: request result of UploadFile
View Swagger API documentation
In this way, you can test the upload file function directly on the Swagger API document
file: bytes
- The FastAPI will read the file and receive the file bytes
- The whole content is stored in memory, which is more suitable for small files
file: UploadFile
The UploadFile of FastAPI directly inherits the UploadFile of Starlette, but adds some necessary parts to make it compatible with Pydantic and other parts of FastAPI
Advantages of UploadFile over bytes
- The file stored in memory reaches the maximum size limit. After exceeding this limit, it will be stored in disk, which can handle large files, such as images, videos, large binary files, etc., without consuming all memory
- Metadata can be obtained from the uploaded file
- There is a file like async asynchronous interface
- It exposes a Python SpooledTemporaryFile object that can be passed to other libraries that need files
UploadFile has the following properties
- filename: str, the original file name uploaded, for example, myimage jpg
- content_type: str, including content type (MIME type / media type), such as {image/jpeg
- File: a SpooledTemporaryFile (an object similar to a file). This is the actual Python file, which can be passed directly to other functions or libraries that need "class file" objects
Uploadfill has the following async asynchronous methods
- write(data): write data (str# or bytes) to a file
- read(size): read the size (int) bytes / characters of the file
- seek(offset): go to the byte position offset(int) in the file, such as await myfile Seek (0) will go to the beginning of the file
- close(): close the file
Uploading multiple files of chestnuts
from typing import List @app.post("/files/") async def create_files(files: List[bytes] = File(...)): return {"file_sizes": [len(file) for file in files]} @app.post("/uploadfiles/") async def create_upload_files(files: List[UploadFile] = File(...)): return {"filenames": [file.filename for file in files]}
Request result for correct parameter transmission
View Swagger API documentation
- Author: Little pineapple test notes
- Link to this article: https://www.cnblogs.com/poloyy/p/15312290.html