FastAPI使用类内函数作为请求处理函数
1. FastAPI介绍
FastAPI 是一个现代、快速(高性能)的 web 框架,用于构建基于 Python 的 API。它是建立在 Starlette 和 Pydantic 之上的,这两者都是非常流行的 Python 库。FastAPI 旨在提供简单易用的 API 开发体验,同时保持高性能和强大的功能。以下是 FastAPI 的一些特点和优势:
- 快速高效:FastAPI 极其快速,并且具有异步请求处理的能力,这使得它成为处理高并发请求的理想选择。
- 基于标准:FastAPI 基于标准的 Python 类型提示和标准的 Python 异步框架,这使得它易于学习和使用,并且能够充分利用 Python 的强大功能。
- 自动文档生成:FastAPI 可以自动生成交互式 API 文档,支持 Swagger UI 和 ReDoc,这样可以方便地查看和测试 API。
- 数据验证和序列化:FastAPI 集成了 Pydantic,可以方便地进行数据验证和序列化,提供了强大的数据校验功能。
- 依赖注入系统:FastAPI 内置了依赖注入系统,可以轻松管理 API 中的依赖关系。
- 简单易用:FastAPI 设计简洁、直观,提供了易于理解的 API 开发体验,使得开发者能够快速构建出高效、稳健的 API。
总的来说,FastAPI 是一个功能强大、性能优越的 Python web 框架,适用于构建各种类型的 API 服务。它的简单易用性、高性能和标准化特性使得它成为了众多开发者的首选框架之一。
2. FastAPI常见用法
以下代码是FastAPI最常见的用法,即使用FastAPI提供的装饰器来定义接口方法
from fastapi import FastAPI
import uvicorn
# 创建 FastAPI 应用实例
app = FastAPI()
# 定义一个get方法接口
@app.get("/hello")
async def read_root():
return {"message": "Hello, World"}
# 启动服务
if __name__ == "__main__":
uvicorn.run(app, host="127.0.0.1", port=8000)
3. 使用类内方法作为接口方法
使用全局函数作为接口方法的优点是简单方便,缺点是不能很好满足面向对象的需求,所以需要用类内方法作为接口方法:
import fastapi
from fastapi.routing import APIRoute
import uvicorn
class HelloServer:
def __init__(self):
self.server = fastapi.FastAPI()
self.server.routes.append(APIRoute(path='/hello', endpoint=self.hello, methods=['POST']))
async def hello(self):
return 'hello world'
def main():
server = HelloServer()
uvicorn.run(
app=server.server,
host="0.0.0.0",
port=8080
)
if __name__ == '__main__':
main()