網(wǎng)站首頁 編程語言 正文
使用File實(shí)現(xiàn)文件上傳
使用Form表單上傳文件,fastapi使用File
獲取上傳的文件。
指定了參數(shù)類型是bytes:file: bytes = File()
,此時(shí)會(huì)將文件內(nèi)容全部讀取到內(nèi)存,比較適合小文件。
使用File
需要提前安裝 python-multipart
from fastapi import FastAPI, File ? app = FastAPI() ? @app.post("/files/") async def create_file(file: bytes = File()): return {"file_size": len(file)}
只要在路徑操作函數(shù)中聲明了變量的類型是bytes
且使用了File,
則fastapi會(huì)將上傳文件的內(nèi)容全部去讀到參數(shù)中。
使用UploadFile實(shí)現(xiàn)文件上傳
對(duì)于大文件,不適合將文件內(nèi)容全部讀取到內(nèi)存中,此時(shí)使用UploadFile
from fastapi import FastAPI, UploadFile ? app = FastAPI() ? @app.post("/uploadfile/") async def create_upload_file(file: UploadFile): return {"filename": file.filename}
和bytes
相比,使用UploadFile
有如下好處:
- 不需要在使用
File()
作為路徑操作函數(shù)中參數(shù)的默認(rèn)值 - 不會(huì)把文件內(nèi)容全部加載到內(nèi)存中,而是批量讀取一定量的數(shù)據(jù),邊讀邊存硬盤。
- 可以獲取文件的元數(shù)據(jù)。
- 該類型的變量可以像文件變量一樣操作。
UploadFile的屬性
- filename:類型是str,用來獲取文件的名字,比如:myimage.png
- content_type: 類型是str, 用來獲取文件的類型,比如:image/png
- file: 類文件對(duì)象,是一個(gè)標(biāo)準(zhǔn)的python文件對(duì)象
除了這四個(gè)基礎(chǔ)屬性外,UploadFile還有三個(gè)async
方法:
- write, 將str或者bytes寫到文件中
- read: 讀文件
- seek: 移動(dòng)光標(biāo)
- close: 關(guān)閉文件
# 獲取文件內(nèi)容 contents = await myfile.read()
設(shè)置上傳文件是可選的
設(shè)置默認(rèn)值是None即可
from typing import Union ? from fastapi import FastAPI, File, UploadFile ? app = FastAPI() ? ? @app.post("/files/") async def create_file(file: Union[bytes, None] = File(default=None)): if not file: return {"message": "No file sent"} else: return {"file_size": len(file)} ? ? @app.post("/uploadfile/") async def create_upload_file(file: Union[UploadFile, None] = None): if not file: return {"message": "No upload file sent"} else: return {"filename": file.filename}
上傳多個(gè)文件
參數(shù)的參數(shù)的類型是列表:列表元素是bytes或者UploadFile
from typing import List ? from fastapi import FastAPI, File, UploadFile ? app = FastAPI() ? ? @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]): return {"filenames": [file.filename for file in files]}
知識(shí)點(diǎn)補(bǔ)充
1.FastAPI簡(jiǎn)介
FastAPI是什么
FastAPI是一個(gè)現(xiàn)代的,快速(高性能)python web框架。基于標(biāo)準(zhǔn)的python類型提示,使用python3.6+構(gòu)建API的Web框架。
FastAPI的主要特點(diǎn)如下:
- 快速:非常高的性能,與NodeJS和Go相當(dāng)(這個(gè)要感謝Starlette和Pydantic),是最快的Python框架之一。
- 快速編碼:將開發(fā)速度提高約200%到300%。
- 更少的bug:減少大約40%的開發(fā)人員人為引起的錯(cuò)誤。
- 直觀:強(qiáng)大的編輯器支持,調(diào)試時(shí)間更短。
- 簡(jiǎn)單:易于使用和學(xué)習(xí)。減少閱讀文檔的時(shí)間。
- 代碼簡(jiǎn)潔:盡量減少代碼重復(fù)。每個(gè)參數(shù)可以聲明多個(gè)功能,減少程序的bug。
- 健壯:生產(chǎn)代碼會(huì)自動(dòng)生成交互式文檔。
- 基于標(biāo)準(zhǔn):基于并完全兼容API的開放標(biāo)準(zhǔn):OpenAPI和JSON模式。
FastAPI 站在巨人的肩膀上:
- Starlette 用于構(gòu)建 Web 部件。
- Pydantic 用于數(shù)據(jù)部分。
環(huán)境準(zhǔn)備
安裝fastapi
pip install fastapi
對(duì)于生產(chǎn)環(huán)境,還需要一個(gè)ASGI服務(wù)器,如Uvicorn或Hypercorn
pip install "uvicorn[standard]"
入門示例程序
新建一個(gè)main.py,編寫如下程序:
from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"} @app.get("/items/{item_id}") def read_item(item_id: int, q: str = None): return {"item_id": item_id, "q": q}
運(yùn)行程序:
uvicorn main:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [28720]
INFO: Started server process [28722]
INFO: Waiting for application startup.
INFO: Application startup complete.
原文鏈接:https://juejin.cn/post/7111858811933032484
相關(guān)推薦
- 2022-06-21 Android基于Sqlite實(shí)現(xiàn)注冊(cè)和登錄功能_Android
- 2022-07-22 jQuery實(shí)現(xiàn)點(diǎn)擊顯示密碼框密碼
- 2023-10-13 is using incorrect casing. Use PascalCase for Reac
- 2022-08-29 Python軟件包安裝的三種常見方法_python
- 2022-03-18 .Net使用分表分庫(kù)框架ShardingCore實(shí)現(xiàn)多字段分片_實(shí)用技巧
- 2022-02-07 SSH遠(yuǎn)程連接Linux服務(wù)器,提示“Keyboard-interactive authentica
- 2022-11-10 Android實(shí)現(xiàn)傳感器功能_Android
- 2022-11-06 Python?munch包?/Munch()?的用法詳解_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支