自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

使用Python FastAPI構(gòu)建Web服務(wù)

開發(fā) 后端
FastAPI 是一個使用 Python 編寫的 Web 框架,還應(yīng)用了 Python asyncio 庫中最新的優(yōu)化。本文將會介紹如何搭建基于容器的開發(fā)環(huán)境,還會展示如何使用 FastAPI 實現(xiàn)一個小型 Web 服務(wù)。

[[328983]]

FastAPI 是一個使用 Python 編寫的 Web 框架,還應(yīng)用了 Python asyncio 庫中最新的優(yōu)化。本文將會介紹如何搭建基于容器的開發(fā)環(huán)境,還會展示如何使用 FastAPI 實現(xiàn)一個小型 Web 服務(wù)。

起步

我們將使用 Fedora 作為基礎(chǔ)鏡像來搭建開發(fā)環(huán)境,并使用 Dockerfile 為鏡像注入 FastAPI、Uvicornaiofiles 這幾個包。

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

在工作目錄下保存 Dockerfile 之后,執(zhí)行 podman 命令構(gòu)建容器鏡像。

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

下面我們可以開始創(chuàng)建一個簡單的 FastAPI 應(yīng)用程序,并通過容器鏡像運行。

  1. from fastapi import FastAPI
  2.  
  3. app = FastAPI()
  4.  
  5. @app.get("/")
  6. async def root():
  7. return {"message": "Hello Fedora Magazine!"}

將上面的代碼保存到 main.py 文件中,然后執(zhí)行以下命令開始運行:

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

這樣,一個基于 FastAPI 的 Web 服務(wù)就跑起來了。由于指定了 --reload 參數(shù),一旦 main.py 文件發(fā)生了改變,整個應(yīng)用都會自動重新加載。你可以嘗試將返回信息 "Hello Fedora Magazine!" 修改為其它內(nèi)容,然后觀察效果。

可以使用以下命令停止應(yīng)用程序:

  1. $ podman stop fastapi

構(gòu)建一個小型 Web 服務(wù)

接下來我們會構(gòu)建一個需要 I/O 操作的應(yīng)用程序,通過這個應(yīng)用程序,我們可以看到 FastAPI 自身的特點,以及它在性能上有什么優(yōu)勢(可以在這里參考 FastAPI 和其它 Python Web 框架的對比)。為簡單起見,我們直接使用 dnf history 命令的輸出來作為這個應(yīng)用程序使用的數(shù)據(jù)。

首先將 dnf history 命令的輸出保存到文件。

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

在上面的命令中,我們使用 tail 去除了 dnf history 輸出內(nèi)容中無用的表頭信息。剩余的每一條 dnf 事務(wù)都包括了以下信息:

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

然后修改 main.py 文件將相關(guān)的數(shù)據(jù)結(jié)構(gòu)添加進去。

  1. from fastapi import FastAPI
  2. from pydantic import BaseModel
  3.  
  4. app = FastAPI()
  5.  
  6. class DnfTransaction(BaseModel):
  7. id: int
  8. command: str
  9. date: str

FastAPI 自帶的 pydantic 庫讓你可以輕松定義一個數(shù)據(jù)類,其中的類型注釋對數(shù)據(jù)的驗證也提供了方便。

再增加一個函數(shù),用于從 history.txt 文件中讀取數(shù)據(jù)。

  1. import aiofiles
  2.  
  3. from fastapi import FastAPI
  4. from pydantic import BaseModel
  5.  
  6. app = FastAPI()
  7.  
  8. class DnfTransaction(BaseModel):
  9. id: int
  10. command: str
  11. date: str
  12.  
  13.  
  14. async def read_history():
  15. transactions = []
  16. async with aiofiles.open("history.txt") as f:
  17. async for line in f:
  18. transactions.append(DnfTransaction(
  19. id=line.split("|")[0].strip(" "),
  20. command=line.split("|")[1].strip(" "),
  21. date=line.split("|")[2].strip(" ")))
  22. return transactions

這個函數(shù)中使用了 aiofiles 庫,這個庫提供了一個異步 API 來處理 Python 中的文件,因此打開文件或讀取文件的時候不會阻塞其它對服務(wù)器的請求。

最后,修改 root 函數(shù),讓它返回事務(wù)列表中的數(shù)據(jù)。

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

執(zhí)行以下命令就可以看到應(yīng)用程序的輸出內(nèi)容了。

  1. $ curl http://127.0.0.1:8000 | python -m json.tool
  2. [
  3. {
  4. "id": 103,
  5. "command": "update",
  6. "date": "2020-05-25 08:35"
  7. },
  8. {
  9. "id": 102,
  10. "command": "update",
  11. "date": "2020-05-23 15:46"
  12. },
  13. {
  14. "id": 101,
  15. "command": "update",
  16. "date": "2020-05-22 11:32"
  17. },
  18. ....
  19. ]

總結(jié)

FastAPI 提供了一種使用 asyncio 構(gòu)建 Web 服務(wù)的簡單方法,因此它在 Python Web 框架的生態(tài)中日趨流行。要了解 FastAPI 的更多信息,歡迎查閱 FastAPI 文檔。

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

責任編輯:龐桂玉 來源: Linux中國
相關(guān)推薦

2022-03-18 09:00:00

開發(fā)Web服務(wù)應(yīng)用程序

2023-06-01 15:14:55

架構(gòu)Python微服務(wù)

2013-03-12 09:50:45

GoRESTful Web

2023-10-09 18:17:52

Python語言Web

2025-01-13 12:23:51

2018-01-17 10:28:34

JavaHttp Server服務(wù)器

2016-02-26 15:28:45

CasperJSWeb爬蟲

2011-03-21 14:41:04

LAMPapacheweb

2010-06-13 09:22:37

jQuery

2023-03-27 15:07:27

PythonWeb 開發(fā)編程語言

2021-11-07 14:29:13

ChromeAPI 藍牙

2009-09-22 12:59:07

ibmdwWeb

2023-04-19 07:39:55

RustHTTP服務(wù)器

2023-12-26 00:58:53

Web應(yīng)用Go語言

2019-05-20 13:20:36

Python編程語言情感分析

2024-10-31 13:56:30

FastAPIGradioDjango

2022-09-05 08:00:00

Java微服務(wù)AuraDB

2020-02-17 16:28:49

開發(fā)技能代碼

2018-12-03 08:00:00

微服務(wù)gRPC

2009-01-03 14:25:10

ibmdwWeb
點贊
收藏

51CTO技術(shù)棧公眾號