針對前文所述 機器學習模型部署摘要 中docker+fastapi部署機器學習的一個完整示例
outline
- fastapi簡單示例
- 基於文件內容檢測的機器學習&fastapi
- 在docker容器部署
Install
pip install fastapi
pip install "uvicorn[standard]"
example
from typing import Optional
from fastapi import FastAPI
#創建FastAPI實例
app = FastAPI()
#創建訪問路徑
@app.get("/")
def read_root():#定義根目錄方法
return {"message": "Hello World"}#返回響應信息
#定義方法,處理請求
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
在開發代碼時,為了調試方便,可以使用如下命令
uvicorn main:app --reload
uvicorn main:app --reload 含義
- main:main.py 文件
- app:在
main.py
文件中通過app = FastAPI()
創建的對象。--reload
:讓服務器在更新代碼后重新啟動。僅在開發時使用該選項。
upload file and predict
一個簡單的上傳文件並對文件進行檢測的小樣例
from typing import Optional
from sympy import content
import uvicorn
from fastapi import FastAPI,File,UploadFile
from io import BytesIO
from ml.predict import load_model,Features,predict
#創建FastAPI實例
app = FastAPI()
#創建訪問路徑
@app.get("/")
def read_root():
return {"message": "Hello World"}
# 加載模型
models = load_model()
def test(file):
feature = Features(file)
return model.predict(feature)
#調用模型接口
@app.post("/detect/v2")
async def detect2(file: UploadFile):
f = file.file
content = await file.read()
res = test(content)
return {
"filename": file.filename,
"attributes": (len(content),str(type(f)),str(type(content))),
"result": res
}
#運行
if __name__ == '__main__':
uvicorn.run(app, host="127.0.0.1", port=8000)
test
在127.0.0.1:8000/docs
頁面可以測試驗證模型
request post
使用request構造post請求驗證結果
import time
import requests
t0 = time.time()
url2 = 'http://127.0.0.1:8000/detect/v2'
filename2 = "examples/00bb57e75b014b9342326afd2e7b7b071ee3f08205e56d0f1bfab8542509212a"
# requests庫post請求文件格式
files = {
'file':(filename2,open(filename2, 'rb'))
}
response2 = requests.post(url2, files=files)
print(response2.content, f"\n spend time: {time.time()-t0}")
deployment
install docker
$ curl -fsSL https://get.docker.com -o get-docker.sh
$ sudo sh get-docker.sh
官方文檔 https://docs.docker.com/engine/install/ubuntu
創建Dockerfile
目錄結構如下
.
├── app
│ ├── __init__.py
│ └── main.py #代碼目錄
├── Dockerfile
└── requirements.txt
構建Dockerfile
vim Dockerfile
輸入以下內容
FROM python:3.9
WORKDIR /code
COPY ./requirements.txt /code/requirements.txt
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
COPY ./app /code/app
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
build docker image
在Dockerfile所在目錄執行
docker build -t myimage .
Start the Docker Container
docker run -d --name mycontainer -p 80:80 myimage
至此,基於docker的fastapi部署完成,可以在主機對應地址看到web信息,或發起對應http請求。