使用Python FastAPI構(gòu)建Web服務(wù)的實(shí)現(xiàn)
FastAPI 是一個(gè)使用 Python 編寫的 Web 框架,還應(yīng)用了 Python asyncio 庫(kù)中最新的優(yōu)化。本文將會(huì)介紹如何搭建基于容器的開(kāi)發(fā)環(huán)境,還會(huì)展示如何使用 FastAPI 實(shí)現(xiàn)一個(gè)小型 Web 服務(wù)。
起步
我們將使用 Fedora 作為基礎(chǔ)鏡像來(lái)搭建開(kāi)發(fā)環(huán)境,并使用 Dockerfile 為鏡像注入 FastAPI、Uvicorn 和 aiofiles 這幾個(gè)包。
FROM fedora:32RUN dnf install -y python-pip && dnf clean all && pip install fastapi uvicorn aiofilesWORKDIR /srvCMD ['uvicorn', 'main:app', '--reload']
在工作目錄下保存 Dockerfile 之后,執(zhí)行 podman 命令構(gòu)建容器鏡像。
$ podman build -t fastapi .$ podman imagesREPOSITORY TAG IMAGE ID CREATED SIZElocalhost/fastapi latest 01e974cabe8b 18 seconds ago 326 MB
下面我們可以開(kāi)始創(chuàng)建一個(gè)簡(jiǎn)單的 FastAPI 應(yīng)用程序,并通過(guò)容器鏡像運(yùn)行。
from fastapi import FastAPI app = FastAPI() @app.get('/')async def root(): return {'message': 'Hello Fedora Magazine!'}
將上面的代碼保存到 main.py 文件中,然后執(zhí)行以下命令開(kāi)始運(yùn)行:
$ 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!'
這樣,一個(gè)基于 FastAPI 的 Web 服務(wù)就跑起來(lái)了。由于指定了 --reload 參數(shù),一旦 main.py 文件發(fā)生了改變,整個(gè)應(yīng)用都會(huì)自動(dòng)重新加載。你可以嘗試將返回信息 'Hello Fedora Magazine!' 修改為其它內(nèi)容,然后觀察效果。
可以使用以下命令停止應(yīng)用程序:
$ podman stop fastapi
構(gòu)建一個(gè)小型 Web 服務(wù)
接下來(lái)我們會(huì)構(gòu)建一個(gè)需要 I/O 操作的應(yīng)用程序,通過(guò)這個(gè)應(yīng)用程序,我們可以看到 FastAPI 自身的特點(diǎn),以及它在性能上有什么優(yōu)勢(shì)(可以在這里參考 FastAPI 和其它 Python Web 框架的對(duì)比)。為簡(jiǎn)單起見(jiàn),我們直接使用 dnf history 命令的輸出來(lái)作為這個(gè)應(yīng)用程序使用的數(shù)據(jù)。
首先將 dnf history 命令的輸出保存到文件。
$ dnf history | tail --lines=+3 > history.txt
在上面的命令中,我們使用 tail 去除了 dnf history 輸出內(nèi)容中無(wú)用的表頭信息。剩余的每一條 dnf 事務(wù)都包括了以下信息:
id:事務(wù)編號(hào)(每次運(yùn)行一條新事務(wù)時(shí)該編號(hào)都會(huì)遞增) command:事務(wù)中運(yùn)行的 dnf 命令 date:執(zhí)行事務(wù)的日期和時(shí)間然后修改 main.py 文件將相關(guān)的數(shù)據(jù)結(jié)構(gòu)添加進(jìn)去。
from fastapi import FastAPIfrom pydantic import BaseModel app = FastAPI() class DnfTransaction(BaseModel): id: int command: str date: str
FastAPI 自帶的 pydantic 庫(kù)讓你可以輕松定義一個(gè)數(shù)據(jù)類,其中的類型注釋對(duì)數(shù)據(jù)的驗(yàn)證也提供了方便。
再增加一個(gè)函數(shù),用于從 history.txt 文件中讀取數(shù)據(jù)。
import aiofiles from fastapi import FastAPIfrom 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
這個(gè)函數(shù)中使用了 aiofiles 庫(kù),這個(gè)庫(kù)提供了一個(gè)異步 API 來(lái)處理 Python 中的文件,因此打開(kāi)文件或讀取文件的時(shí)候不會(huì)阻塞其它對(duì)服務(wù)器的請(qǐng)求。
最后,修改 root 函數(shù),讓它返回事務(wù)列表中的數(shù)據(jù)。
@app.get('/')async def read_root(): return await read_history()
執(zhí)行以下命令就可以看到應(yīng)用程序的輸出內(nèi)容了。
$ 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'},....]
總結(jié)
FastAPI 提供了一種使用 asyncio 構(gòu)建 Web 服務(wù)的簡(jiǎn)單方法,因此它在 Python Web 框架的生態(tài)中日趨流行。要了解 FastAPI 的更多信息,歡迎查閱 FastAPI 文檔。
本文中的代碼可以在 GitHub 上找到。
到此這篇關(guān)于使用Python FastAPI構(gòu)建Web服務(wù)的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Python FastAPI構(gòu)建Web服務(wù)內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
