当前位置:网站首页>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)
边栏推荐
- 1. Mx6ul core module uses serial can and buzzer test (XI)
- Kaggle registration method to solve the problem of man-machine verification
- LeetCode_动态规划_中等_264.丑数 II
- opengauss如何手工安装(非OM方式)
- [C language brush leetcode] 443. Compressed string (m)
- Redis cluster construction (based on 6.x)
- G2. passable paths (hard version) (tree diameter + LCA)
- BGP knowledge points summary
- PHP Alipay transfer to Alipay account
- 2022.7.25-----leetcode.919
猜你喜欢

1. Mx6ul core module uses serial EMMC read / write test (IV)

Error reporting caused by local warehouse

SQLyog数据导入导出图文教程

(CVPR 2019) GSPN: Generative Shape Proposal Network for 3D Instance Segmentation in Point Cloud
![[2021] [paper notes] 6G technology vision - otfs modulation technology](/img/50/577ad05bc16e80d1c68eec7b6da988.png)
[2021] [paper notes] 6G technology vision - otfs modulation technology

I.MX6UL核心模块使用连载-查看系统信息 (二)

Design and driver transplantation of matrix keyboard circuit of Ti am335x industrial control module
![[xxl-job] xxl-job learning](/img/2c/d3872983e4228a3ef52a9d1bef836e.png)
[xxl-job] xxl-job learning

Implementation of Ti am335x industrial control module network and file system nfs

obsidian移动端PC段同步
随机推荐
【红队】ATT&CK - 利用BITS服务实现持久化
1. Mx6ul core module use serialization - view system information (II)
Worthington产气荚膜梭菌神经氨酸酶的特征及测定
1. Mx6ul core module use serial RTC test (XII)
js给页面添加随机像素噪声背景
I.MX6UL核心模块使用连载-TF卡读写测试 (五)
AttributeError: ‘Document‘ object has no attribute ‘pageCount‘
opengauss如何手工安装(非OM方式)
1. Mx6ul core module uses serial EMMC read / write test (IV)
Tenant issues.
TI AM335x工控模块网络跟文件系统NFS的实现
MPLS知识点
[C language brush leetcode] 146. LRU cache (m)
重发布基础与配置
[C language brush leetcode] 443. Compressed string (m)
JS add random pixel noise background to the page
Create a future and enjoy extraordinary | gbase Nantah General Motors unveiled opengauss Developer Day 2022
I.MX6UL核心模块使用连载-RS485测试 (十)
3. Upload the avatar to qiniu cloud and display it
Worthington nuclease and Micrococcus related research and determination scheme