温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python中FastAPI构建Web服务的实现方法

发布时间:2020-07-18 09:35:39 来源:亿速云 阅读:258 作者:小猪 栏目:开发技术

这篇文章主要讲解了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,
"command": "update",
"date": "2020-05-23 15:46"
},
{
"id": 101,
"command": "update",
"date": "2020-05-22 11:32"
},
....
]

看完上述内容,是不是对Python中FastAPI构建Web服务的实现方法有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI