通过fastapi构建复杂的web api
构建复杂的 web api 通常涉及到多个方面,包括良好的架构设计、清晰的路由组织、数据验证与处理、安全措施、性能优化等。使用 fastapi 构建复杂 web api 的关键在于充分利用其提供的工具和特性,同时遵循软件工程的最佳实践。以下是一个详细的指南,帮助你使用 fastapi 构建一个复杂且高效的 web api。
1. 项目结构
为你的项目创建一个合理的文件夹结构,这有助于代码的组织和维护。例如:
my_project/ ├── app/ │ ├── __init__.py │ ├── main.py │ ├── dependencies.py │ ├── models.py │ ├── schemas.py │ ├── routers/ │ │ ├── __init__.py │ │ ├── items.py │ │ └── users.py │ ├── services/ │ │ ├── __init__.py │ │ ├── item_service.py │ │ └── user_service.py │ ├── database.py │ └── config.py └── tests/ ├── __init__.py └── test_main.py
2. 依赖管理
使用 requirements.txt
或者更现代的 poetry
来管理项目的依赖关系。确保所有开发和生产环境所需的库都被列出。
# 使用 poetry 初始化项目并添加依赖 poetry init poetry add fastapi uvicorn sqlalchemy alembic bcrypt passlib[bcrypt] pydantic email-validator
3. 配置管理
使用环境变量或配置文件来管理应用程序的不同设置(如数据库连接字符串、密钥等)。可以借助 pydantic 的 basesettings
类。
# config.py from pydantic import basesettings class settings(basesettings): app_name: str = "my complex api" admin_email: str items_per_user: int = 50 secret_key: str algorithm: str = "hs256" access_token_expire_minutes: int = 30 class config: env_file = ".env" settings = settings()
4. 数据库集成
选择合适的 orm(如 sqlalchemy)并与 fastapi 集成。创建数据库模型,并考虑使用 alembic 进行数据库迁移。
# database.py from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker sqlalchemy_database_url = "sqlite:///./test.db" engine = create_engine(sqlalchemy_database_url, connect_args={"check_same_thread": false}) sessionlocal = sessionmaker(autocommit=false, autoflush=false, bind=engine) base = declarative_base() def get_db(): db = sessionlocal() try: yield db finally: db.close()
5. 定义模型与模式
创建数据模型用于映射到数据库表,以及 pydantic 模型用于请求体和响应的验证。
# models.py from sqlalchemy import column, integer, string from .database import base class item(base): __tablename__ = "items" id = column(integer, primary_key=true, index=true) name = column(string, index=true) description = column(string, index=true) # schemas.py from pydantic import basemodel class itemcreate(basemodel): name: str description: str = none class item(basemodel): id: int name: str description: str = none class config: orm_mode = true
6. 服务层
为了保持控制器(路由处理函数)的简洁性,将业务逻辑分离到服务层中。
# services/item_service.py from typing import list from sqlalchemy.orm import session from ..models import item as itemmodel from ..schemas import itemcreate, item def get_items(db: session, skip: int = 0, limit: int = 10) -> list[item]: return db.query(itemmodel).offset(skip).limit(limit).all() def create_item(db: session, item: itemcreate) -> item: db_item = itemmodel(**item.dict()) db.add(db_item) db.commit() db.refresh(db_item) return db_item
7. 路由分组
将相关路径操作分组到不同的路由器模块中,以提高代码的可读性和可维护性。
# routers/items.py from fastapi import apirouter, depends from sqlalchemy.orm import session from ... import schemas, services from ...dependencies import get_db router = apirouter() @router.get("/", response_model=list[schemas.item]) def read_items(skip: int = 0, limit: int = 10, db: session = depends(get_db)): items = services.get_items(db, skip=skip, limit=limit) return items @router.post("/", response_model=schemas.item) def create_item(item: schemas.itemcreate, db: session = depends(get_db)): return services.create_item(db=db, item=item)
8. 主应用入口
在主应用文件中导入并包含各个路由器。
# main.py from fastapi import fastapi from .routers import items, users app = fastapi() app.include_router(items.router) app.include_router(users.router)
9. 安全性
实现身份验证和授权机制,例如使用 jwt token 进行用户认证。
# dependencies.py from datetime import datetime, timedelta from jose import jwterror, jwt from fastapi import depends, httpexception, status from fastapi.security import oauth2passwordbearer from . import models, schemas, config oauth2_scheme = oauth2passwordbearer(tokenurl="token") async def get_current_user(token: str = depends(oauth2_scheme)): credentials_exception = httpexception( status_code=status.http_401_unauthorized, detail="could not validate credentials", headers={"www-authenticate": "bearer"}, ) try: payload = jwt.decode(token, config.settings.secret_key, algorithms=[config.settings.algorithm]) username: str = payload.get("sub") if username is none: raise credentials_exception token_data = schemas.tokendata(username=username) except jwterror: raise credentials_exception user = get_user(db, username=token_data.username) if user is none: raise credentials_exception return user
10. 测试
编写单元测试和集成测试来确保你的 api 按预期工作。fastapi 提供了方便的测试客户端 testclient
。
# tests/test_main.py from fastapi.testclient import testclient from my_project.app.main import app client = testclient(app) def test_read_main(): response = client.get("/") assert response.status_code == 200 assert response.json() == {"message": "hello world"}
11. 部署
考虑使用 docker 容器化你的应用程序,并通过 ci/cd 管道自动部署到云平台或服务器上。
# dockerfile from tiangolo/uvicorn-gunicorn-fastapi:python3.9 copy ./app /app workdir /app run pip install --no-cache-dir -r requirements.txt cmd ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]
总结
通过以上步骤可以使用 fastapi 构建复杂的 web api。
fastapi支持的工具
fastapi 提供了丰富的工具和特性,使得开发高效、安全且易于维护的 web api 变得更加简单。除了核心功能外,还有一些重要的工具和特性可以帮助你构建更强大的应用程序。以下是 fastapi 的一些重要工具和特性:
1. 依赖注入系统
fastapi 内置了一个强大且灵活的依赖注入系统,这使得你可以轻松地管理和重用代码逻辑,比如身份验证、数据库连接等。
from fastapi import depends, fastapi app = fastapi() async def get_db(): db = dbsession() try: yield db finally: db.close() @app.get("/items/") async def read_items(db: session = depends(get_db)): items = db.query(item).all() return items
2. pydantic 模型
pydantic 是一个数据验证库,它允许你定义数据模型,并自动处理数据解析和验证。fastapi 使用 pydantic 来确保请求体、查询参数和其他输入符合预期格式。
from pydantic import basemodel class item(basemodel): name: str description: str = none price: float tax: float = none
3. 中间件
中间件是在请求到达路由处理函数之前或响应发送给客户端之后执行的代码。你可以使用中间件来添加通用的行为,如日志记录、身份验证、cors 处理等。
from fastapi.middleware.cors import corsmiddleware app.add_middleware( corsmiddleware, allow_origins=["*"], allow_credentials=true, allow_methods=["*"], allow_headers=["*"], )
4. 异常处理
fastapi 提供了内置的异常处理机制,并允许你自定义异常处理器来处理特定类型的错误。
from fastapi import request, status from fastapi.responses import jsonresponse from fastapi.exceptions import requestvalidationerror @app.exception_handler(requestvalidationerror) async def validation_exception_handler(request: request, exc: requestvalidationerror): return jsonresponse( status_code=status.http_422_unprocessable_entity, content={"detail": exc.errors(), "body": exc.body}, )
5. 背景任务
如果你需要在返回响应后继续执行某些操作(如发送电子邮件),可以使用背景任务。
from fastapi import backgroundtasks def write_log(message: str): with open("log.txt", mode="a") as log: log.write(message) @app.post("/send-notification/{email}") async def send_notification(email: str, background_tasks: backgroundtasks): background_tasks.add_task(write_log, f"notification sent to {email}\n") return {"message": "notification sent in the background"}
6. 静态文件和模板
fastapi 支持服务静态文件(如 html、css、javascript 文件)以及渲染模板,这对于创建完整的 web 应用程序非常有用。
from fastapi.staticfiles import staticfiles from fastapi.templating import jinja2templates app.mount("/static", staticfiles(directory="static"), name="static") templates = jinja2templates(directory="templates") @app.get("/") async def read_root(request: request): return templates.templateresponse("index.html", {"request": request})
7. websocket 支持
fastapi 支持 websocket 连接,这对于实现实时双向通信非常有用,例如聊天应用或实时更新的数据展示。
from fastapi import websocket, websocketdisconnect @app.websocket("/ws") async def websocket_endpoint(websocket: websocket): await websocket.accept() try: while true: data = await websocket.receive_text() await websocket.send_text(f"message text was: {data}") except websocketdisconnect: pass
8. 环境变量与配置管理
使用 pydantic
的 basesettings
类来管理应用程序的配置和环境变量,这有助于分离配置和代码。
from pydantic import basesettings class settings(basesettings): app_name: str = "awesome api" admin_email: str items_per_user: int = 50 class config: env_file = ".env" settings = settings()
9. 测试工具
fastapi 提供了方便的测试工具,包括测试客户端 testclient
和模拟器,帮助你在本地快速测试 api。
from fastapi.testclient import testclient client = testclient(app) def test_read_main(): response = client.get("/") assert response.status_code == 200 assert response.json() == {"message": "hello world"}
10. openapi 和 swagger ui
fastapi 自动生成 openapi 规范,并提供交互式的 api 文档界面(swagger ui 和 redoc)。这不仅方便开发者调试 api,也便于用户了解如何使用你的 api。
# 自动生成并提供交互式文档 # 访问 http://127.0.0.1:8000/docs 或 http://127.0.0.1:8000/redoc
11. 速率限制
虽然 fastapi 本身不直接提供速率限制功能,但可以通过中间件或其他扩展来实现这一特性,以防止滥用或保护服务器资源。
from fastapi import fastapi, httpexception, status from fastapi.middleware import middleware from fastapi.middleware.trustedhost import trustedhostmiddleware app = fastapi(middleware=[ middleware(trustedhostmiddleware, allowed_hosts=["example.com"]) ]) # 或者使用第三方库如 fastapi-limiter 实现速率限制
这些工具和特性共同构成了 fastapi 强大而灵活的生态系统,使得开发者能够更高效地构建现代 web api。
fastapi 路由操作
fastapi 支持所有标准的 http 方法(也称为“路由操作”或“http 动词”),这些方法定义了客户端与服务器之间的交互类型。以下是 fastapi 支持的主要路由操作:
1. get
用于请求从服务器获取信息,通常用于查询资源。
@app.get("/items/{item_id}") async def read_item(item_id: int): return {"item_id": item_id}
2. post
用于向指定资源提交数据,常用于创建新资源或发送表单数据。
@app.post("/items/") async def create_item(item: item): return item
3. put
用于更新现有资源,通常整个资源会被替换。
@app.put("/items/{item_id}") async def update_item(item_id: int, item: item): return {"item_id": item_id, "item": item}
4. delete
用于删除指定的资源。
@app.delete("/items/{item_id}") async def delete_item(item_id: int): return {"item_id": item_id}
5. patch
用于对资源进行部分更新,只修改指定字段。
@app.patch("/items/{item_id}") async def patch_item(item_id: int, item: itemupdate): return {"item_id": item_id, "item": item}
6. options
用于描述目标资源的通信选项。它返回服务器支持的方法列表。
@app.options("/items/") async def describe_options(): return {"allow": "get, post, put, delete, patch, options"}
7. head
类似于 get 请求,但不返回消息体,仅用于获取响应头信息。
@app.head("/items/{item_id}") async def head_item(item_id: int): # 处理逻辑,但不会返回响应体 pass
8. trace
用于回显服务器收到的请求,主要用于测试或诊断。
@app.trace("/trace") async def trace_request(): return {"method": "trace"}
路由参数
除了上述的 http 方法外,fastapi 还允许你定义路径参数、查询参数、请求体等,以更灵活地处理不同的请求场景。
路径参数
直接在路径中定义参数,如 /items/{item_id}
中的 item_id
。
@app.get("/items/{item_id}") async def read_item(item_id: int): return {"item_id": item_id}
查询参数
通过 url 的查询字符串传递参数,例如 /items/?skip=0&limit=10
。
@app.get("/items/") async def read_items(skip: int = 0, limit: int = 10): return {"skip": skip, "limit": limit}
请求体
使用 pydantic 模型来解析和验证 json 请求体。
from pydantic import basemodel class item(basemodel): name: str description: str = none price: float tax: float = none @app.post("/items/") async def create_item(item: item): return item
额外功能
- 路径操作函数:可以是同步函数(
def
)或异步函数(async def
),根据你的需求选择。 - 依赖注入:可以在路径操作函数中添加依赖项,以便于共享状态或执行预处理逻辑。
- 中间件:为所有请求添加额外的行为,比如日志记录、身份验证等。
- 自定义响应:你可以返回不同类型的响应,包括 jsonresponse、htmlresponse 等。
- websocket:fastapi 同样支持 websocket 连接,可以用来实现实时双向通信。
以上就是 fastapi 支持的主要路由操作。fastapi 的设计使得它不仅支持标准的 http 方法,还提供了强大的工具来帮助开发者构建现代的 web api。
总结
到此这篇关于python如何通过fastapi构建复杂的web api的文章就介绍到这了,更多相关python fastapi构建web api内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论