当前位置:网站首页>18_ Request file
18_ Request file
2022-07-26 02:12:00 【Empty nest youth_ rui】
18_ Request file
This section describes how to use File Declare the uploaded file as ( Form data ) Input parameters .
File Used to define the file uploaded by the client .
Because uploading files is based on “ The form data ” Send as . So receive uploaded files , To pre install
python-multipart.
1. Import File:
When using , Need from fastapi Import File and UploadFile:
from fastapi import FastAPI, File, UploadFile
2. Definition File Parameters :
create a file (File) The method of parameters is the same as before Body and Form Same parameter :
from fastapi import FastAPI, File, UploadFile
app = FastAPI()
@app.post("/files/")
async def create_file(file: bytes = File()): # Definition File Parameters
return {
"file_size": len(file)}
FileIt is directly inherited fromFormClass , ImportFilewhen , It is actually a factory function that returns a specific class .
Tips :
The declaration file body must use
File, otherwise ,FastAPI This parameter will be treated as a query parameter or request body (JSON) Parameters .
File as “ The form data ” Upload . If the type of path operation function parameter is declared as bytes, FastAPI Will be with bytes Read and receive the contents of the file in the form of . In this way, all the contents of the file are stored in memory , Suitable for small files .
however , In many cases ,UploadFile Better to use .
3. contain UploadFile Of File Parameters :
Definition File Parameter is used UploadFile:
from fastapi import FastAPI, File, UploadFile
app = FastAPI()
@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile): # Definition UploadFile Parameters
return {
"filename": file.filename}
UploadFile And bytes Have more advantages than :
- Use
spooledfile :
When the file stored in memory exceeds the maximum limit ,FastAPI Will save the file to disk ; - This method is more suitable for processing images 、 video 、 Binary files and other large files , The advantage is that it won't take up all memory ;
- You can get the metadata of the uploaded file ;
- Bring their own file-like
asyncInterface ; - exposed python SpooledTemporaryFile Objects can be passed directly to other expectations file-like The library of objects .
UploadFile:
UploadFile The properties of are as follows :
filename: Upload file name string (str), for example ,myimage.jpg;content_type: Content type (MIME type / Media type ) character string (str), for exampleimage/jpeg;file:SpooledTemporaryFile(file-like object ). In fact, that is python file , It can be passed directly to other intended uses file-like Object's function or support library .
UploadFile Support the following async Method ,( Use the inside SpooledTemporaryFile) The corresponding file method can be called .
write(data): hold data(strorbytes) write file ;read(size): A specified number of bytes or characters (size(int)) Read file contents ;seek(offset): Move to file offset (int) Position at byte ;- Such as ,
await myfile.seek(0)Move to the beginning of steadiness ; - perform
await myfile.read()after , When you need to read the read content again , This method is particularly useful ;
- Such as ,
close(): Close file .
Because the above methods are async Method , So match await Use .
for example , stay async Path operation function in , To read the contents of the file in the following way :
contents = await myfile.read()
If it's in ordinary def In path operation function , You can directly access UploadFile.file, Such as :
contents = myfile.file.read()
asyncTechnical details :Use
asyncWhen the method is used ,FastAPI Method of executing files in the thread pool , andawaitWait for the operation to complete .
Starlette Technical details :
FastAPI Of
UploadFileInherit directly from Starlette OfUploadFile, But some necessary functions have been added , To that of the Pydantic And FastAPI Compatible with other components of .
4. What is? “ The form data ”?
And JSOn Different ,HTML Forms (<form></form>) Data sent to the server usually uses a 「 special 」 The coding , This is different from JSON Of .
FastAPI Make sure you read the data from the correct location , Instead of reading JSON.
Technical details :
When files are not included , Form data is generally used
application/x-www-form-urlencoded「 Media type 」 code .But when the form contains files , Encoded as
multipart/form-data. UsedFile,FastAPI You know to get the file from the correct location of the request body .For details of codes and form fields, see MDN Web Document POST Section .
Warning :
Multiple... Can be declared in one path operation File and Form Parameters , But you can't declare to receive at the same time JSON Of Body Field . Because the code of the request body is multipart/form-data, No application/json.
This is not FastAPI The problem of , It is HTTP Provisions of the agreement .
5. Optional file upload :
We can use the standard type annotation and set the parameter default value to None Make a file optional :
from fastapi import FastAPI, File, UploadFile
app = FastAPI()
@app.post("/files/")
async def create_file(file: bytes | None = File(default=None)): # Optional parameters
if not file:
return {
"message": "No file sent"}
else:
return {
"file_size": len(file)}
@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile | None = None): # Optional parameters
if not file:
return {
"message": "No upload file sent"}
else:
return {
"filename": file.filename}
6. With additional metadata UploadFile:
We can also go through UploadFile To use File() To set additional metadata for the file :
from fastapi import FastAPI, File, UploadFile
app = FastAPI()
@app.post("/files/")
async def create_file(file: bytes = File(description="A file read as bytes")):
return {
"file_size": len(file)}
@app.post("/uploadfile/")
async def create_upload_file(
file: UploadFile = File(description="A file read as UploadFile"), # Add metadata
):
return {
"filename": file.filename}
7. Multiple file upload :
FastAPi Support to upload multiple files at the same time . These multiple files will be associated with the sent “ The form data ” The same in “ form field ”.
In order to use it , You need to declare a bytes or UploadFile A list of :
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import HTMLResponse
app = FastAPI()
@app.post("/files/")
async def create_files(files: list[bytes] = File()): # Multiple bytes A list of
return {
"file_sizes": [len(file) for file in files]}
@app.post("/uploadfiles/")
async def create_upload_files(files: list[UploadFile]): # Multiple UploadFile A list of
return {
"filenames": [file.filename for file in files]}
@app.get("/")
async def main():
content = """ <body> <form action="/files/" enctype="multipart/form-data" method="post"> <input name="files" type="file" multiple> <input type="submit"> </form> <form action="/uploadfiles/" enctype="multipart/form-data" method="post"> <input name="files" type="file" multiple> <input type="submit"> </form> </body> """
return HTMLResponse(content=content)
It also contains bytes or UploadFile A list of (list).
Technical details :
You can also use
from starlette.responses import HTMLResponse.
fastapi.responsesIn fact, withstarlette.responsesidentical , Just for the convenience of developers . actually , majority FastAPI All responses are directly from Starlette call .
Multi file upload with additional metadata :
The same as before , We can use File() To set additional parameters , Even right UploadFile You can also set :
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import HTMLResponse
app = FastAPI()
@app.post("/files/")
async def create_files(
files: list[bytes] = File(description="Multiple files as bytes"), # Set metadata for multiple files
):
return {
"file_sizes": [len(file) for file in files]}
@app.post("/uploadfiles/")
async def create_upload_files(
files: list[UploadFile] = File(description="Multiple files as UploadFile"), # Set metadata for multiple files
):
return {
"filenames": [file.filename for file in files]}
@app.get("/")
async def main():
content = """ <body> <form action="/files/" enctype="multipart/form-data" method="post"> <input name="files" type="file" multiple> <input type="submit"> </form> <form action="/uploadfiles/" enctype="multipart/form-data" method="post"> <input name="files" type="file" multiple> <input type="submit"> </form> </body> """
return HTMLResponse(content=content)
边栏推荐
- Worthington papain - production of glycopeptides from purified proteoglycans (attached Literature)
- Wechat applet decryption and unpacking to obtain source code tutorial
- 一款可插拔的AM335X工控模块板载wifi模块
- Quick start of adding, deleting, modifying and checking business
- Make and makefile summary II
- [2021] [paper notes] biological effects of cell membrane under infrared and THz - effect is a phenomenon, action is a mechanism - the benefits of THz to medicine
- Ggplot2 learning summary
- 1. Mx6ul core module use serial -rs485 test (x)
- MySQL transaction isolation level
- Turn: do the right thing efficiently
猜你喜欢

(CVPR 2019) GSPN: Generative Shape Proposal Network for 3D Instance Segmentation in Point Cloud

增删改查业务的快速上手

Activiti workflow gateway

Composition API的优势

租户问题。

Worthington产气荚膜梭菌神经氨酸酶的特征及测定

Bitmap这个“内存刺客”你要小心~

2. Login - verification code function and saving login status

国标GB28181协议视频平台EasyGBS消息弹框模式优化

TI AM335x工控模块网络跟文件系统NFS的实现
随机推荐
[2019] [paper notes] tunable THz broadband absorption based on metamaterials——
Composition API的优势
js给页面添加随机像素噪声背景
【红队】ATT&CK - 利用BITS服务实现持久化
What are the functions of cloud notes, and how do browsers add cloud note plug-ins
Leetcode algorithm 147. insert and sort the linked list
Sqlyog data import and export graphic tutorial
图解B+树的插入过程
I.MX6UL核心模块使用连载-USB接口测试 (六)
LeetCode_动态规划_中等_264.丑数 II
Implementation of Ti am335x industrial control module network and file system nfs
(CVPR 2019) GSPN: Generative Shape Proposal Network for 3D Instance Segmentation in Point Cloud
Build embedded development environment and FRP penetration under win
These practical security browser plug-ins improve your efficiency
Worthington papain - production of glycopeptides from purified proteoglycans (attached Literature)
微信小程序解密并拆包获取源码教程
Why does the debugger display the wrong function
DialogRPT-Dialog Ranking Pretrained Transformers
Redis集群搭建(基于6.x)
【2021】【论文笔记】6G技术愿景——OTFS调制技术