FastAPI 是一個使用 Python 編寫的 Web 框架,還應用了 Python asyncio 庫中最新的優化。本文將會介紹如何搭建基於容器的開發環境,還會展現如何使用 FastAPI 實現一個小型 Web 服務。python
咱們將使用 Fedora 做爲基礎鏡像來搭建開發環境,並使用 Dockerfile 爲鏡像注入 FastAPI、Uvicorn 和 aiofiles 這幾個包。linux
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
命令構建容器鏡像。git
$ podman build -t fastapi .
$ podman images
REPOSITORY TAG IMAGE ID CREATED SIZE
localhost/fastapi latest 01e974cabe8b 18 seconds ago 326 MB
複製代碼
下面咱們能夠開始建立一個簡單的 FastAPI 應用程序,並經過容器鏡像運行。github
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello Fedora Magazine!"}
複製代碼
將上面的代碼保存到 main.py
文件中,而後執行如下命令開始運行:web
$ 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!"
修改成其它內容,而後觀察效果。json
可使用如下命令中止應用程序:api
$ podman stop fastapi
複製代碼
接下來咱們會構建一個須要 I/O 操做的應用程序,經過這個應用程序,咱們能夠看到 FastAPI 自身的特色,以及它在性能上有什麼優點(能夠在這裏參考 FastAPI 和其它 Python Web 框架的對比)。爲簡單起見,咱們直接使用 dnf history
命令的輸出來做爲這個應用程序使用的數據。bash
首先將 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,
"command": "update",
"date": "2020-05-23 15:46"
},
{
"id": 101,
"command": "update",
"date": "2020-05-22 11:32"
},
....
]
複製代碼
FastAPI 提供了一種使用 asyncio 構建 Web 服務的簡單方法,所以它在 Python Web 框架的生態中日趨流行。要了解 FastAPI 的更多信息,歡迎查閱 FastAPI 文檔。
本文中的代碼能夠在 GitHub 上找到。
via: fedoramagazine.org/use-fastapi…
做者:Clément Verna 選題:lujun9972 譯者:HankChow 校對:wxy