日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

Python利用fastapi實(shí)現(xiàn)上傳文件_python

作者:小飛牛 ? 更新時(shí)間: 2022-08-16 編程語言

使用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

欄目分類
最近更新