1. 程式人生 > 程式設計 >使用Python FastAPI構建Web服務的實現

使用Python FastAPI構建Web服務的實現

FastAPI 是一個使用 Python 編寫的 Web 框架,還應用了 Python asyncio 庫中最新的優化。本文將會介紹如何搭建基於容器的開發環境,還會展示如何使用 FastAPI 實現一個小型 Web 服務。

起步

我們將使用 Fedora 作為基礎映象來搭建開發環境,並使用 Dockerfile 為映象注入 FastAPI、Uvicorn 和 aiofiles 這幾個包。

FROM fedora:32
RUN dnf install -y python-pip \
  && dnf clean all \
  && pip install fastapi uvicorn aiofiles
WORKDIR /srv
CMD ["uvicorn","main:app","--reload"]

在工作目錄下儲存 Dockerfile 之後,執行 podman 命令構建容器映象。

$ podman build -t fastapi .
$ podman images
REPOSITORY TAG IMAGE ID CREATED SIZE
localhost/fastapi latest 01e974cabe8b 18 seconds ago 326 MB

下面我們可以開始建立一個簡單的 FastAPI 應用程式,並通過容器映象執行。

from fastapi import FastAPI
 
app = FastAPI()
 
@app.get("/")
async def root():
  return {"message": "Hello Fedora Magazine!"}

將上面的程式碼儲存到 main.py 檔案中,然後執行以下命令開始執行:

$ podman run --rm -v $PWD:/srv:z -p 8000:8000 --name fastapi -d fastapi
$ curl http://127.0.0.1:8000
{"message":"Hello Fedora Magazine!"

這樣,一個基於 FastAPI 的 Web 服務就跑起來了。由於指定了 --reload 引數,一旦 main.py 檔案發生了改變,整個應用都會自動重新載入。你可以嘗試將返回資訊 "Hello Fedora Magazine!" 修改為其它內容,然後觀察效果。

可以使用以下命令停止應用程式:

$ podman stop fastapi

構建一個小型 Web 服務

接下來我們會構建一個需要 I/O 操作的應用程式,通過這個應用程式,我們可以看到 FastAPI 自身的特點,以及它在效能上有什麼優勢(可以在這裡參考 FastAPI 和其它 Python Web 框架的對比)。為簡單起見,我們直接使用 dnf history 命令的輸出來作為這個應用程式使用的資料。

首先將 dnf history 命令的輸出儲存到檔案。

$ dnf history | tail --lines=+3 > history.txt

在上面的命令中,我們使用 tail 去除了 dnf history 輸出內容中無用的表頭資訊。剩餘的每一條 dnf 事務都包括了以下資訊:

  • id:事務編號(每次執行一條新事務時該編號都會遞增)
  • command:事務中執行的 dnf 命令
  • date:執行事務的日期和時間

然後修改 main.py 檔案將相關的資料結構新增進去。

from fastapi import FastAPI
from pydantic import BaseModel
 
app = FastAPI()
 
class DnfTransaction(BaseModel):
  id: int
  command: str
  date: str

FastAPI 自帶的 pydantic 庫讓你可以輕鬆定義一個數據類,其中的型別註釋對資料的驗證也提供了方便。

再增加一個函式,用於從 history.txt 檔案中讀取資料。

import aiofiles
 
from fastapi import FastAPI
from pydantic import BaseModel
 
app = FastAPI()
 
class DnfTransaction(BaseModel):
  id: int
  command: str
  date: str
 
 
async def read_history():
  transactions = []
  async with aiofiles.open("history.txt") as f:
    async for line in f:
      transactions.append(DnfTransaction(
        id=line.split("|")[0].strip(" "),command=line.split("|")[1].strip(" "),date=line.split("|")[2].strip(" ")))
  return transactions

這個函式中使用了 aiofiles 庫,這個庫提供了一個非同步 API 來處理 Python 中的檔案,因此開啟檔案或讀取檔案的時候不會阻塞其它對伺服器的請求。

最後,修改 root 函式,讓它返回事務列表中的資料。

@app.get("/")
async def read_root():
  return await read_history()

執行以下命令就可以看到應用程式的輸出內容了。

$ curl http://127.0.0.1:8000 | python -m json.tool
[
{
"id": 103,"command": "update","date": "2020-05-25 08:35"
},{
"id": 102,"date": "2020-05-23 15:46"
},{
"id": 101,"date": "2020-05-22 11:32"
},....
]

總結

FastAPI 提供了一種使用 asyncio 構建 Web 服務的簡單方法,因此它在 Python Web 框架的生態中日趨流行。要了解 FastAPI 的更多資訊,歡迎查閱 FastAPI 文件。

本文中的程式碼可以在 GitHub 上找到。

到此這篇關於使用Python FastAPI構建Web服務的實現的文章就介紹到這了,更多相關Python FastAPI構建Web服務內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!