百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

高级 FastAPI 模式:使用 Python 构建可用于生产的 API

itomcoil 2025-03-14 18:07 14 浏览

FastAPI 以其现代的异步优先方法彻底改变了 Python API 开发。我花了大量时间研究 FastAPI,我将分享在生产环境中行之有效的高级模式。

依赖注入

FastAPI 中的依赖注入提供了清晰的关注点分离和高效的资源管理。以下是数据库依赖项的实际实现:

from fastapi import Depends
from sqlalchemy.orm import Session
from contextlib import contextmanager

class Database:
    def __init__(self):
        self.session = None

    @contextmanager
    def get_session(self):
        session = Session()
        try:
            yield session
        finally:
            session.close()

db = Database()

async def get_db():
    with db.get_session() as session:
        yield session

@app.get("/users/{user_id}")
async def get_user(user_id: int, db: Session = Depends(get_db)):
    return db.query(User).filter(User.id == user_id).first()

响应缓存

实现 Redis 缓存可显著提高 API 性能。以下是一个强大的缓存实现:

from fastapi_cache import FastAPICache
from fastapi_cache.backends.redis import RedisBackend
import pickle

class CustomRedisBackend(RedisBackend):
    async def get(self, key: str):
        value = await self.redis.get(key)
        if value:
            return pickle.loads(value)
        return None

    async def set(self, key: str, value: any, expire: int = None):
        value = pickle.dumps(value)
        await self.redis.set(key, value, expire)

@app.on_event("startup")
async def startup():
    redis = aioredis.Redis(host='localhost', port=6379)
    FastAPICache.init(CustomRedisBackend(redis), prefix="fastapi-cache:")

@app.get("/products/{product_id}")
@FastAPICache.cache(expire=300)
async def get_product(product_id: int):
    return {"product_id": product_id}

后台任务

有效地管理长时间运行的操作至关重要。以下是处理后台任务的模式:

from fastapi import BackgroundTasks
from celery import Celery

celery_app = Celery('tasks', broker='redis://localhost:6379/0')

@celery_app.task
def process_video(video_id: int):
    # Video processing logic
    pass

@app.post("/videos/")
async def upload_video(
    video: UploadFile,
    background_tasks: BackgroundTasks
):
    video_id = save_video(video)
    background_tasks.add_task(process_video.delay, video_id)
    return {"status": "processing"}

速率限制

保护 API 资源需要有效的速率限制。以下是基于 Redis 的实现:

from fastapi import HTTPException
import time

class RateLimiter:
    def __init__(self, redis_client, limit: int, window: int):
        self.redis = redis_client
        self.limit = limit
        self.window = window

    async def is_allowed(self, key: str) -> bool:
        current = int(time.time())
        window_start = current - self.window

        async with self.redis.pipeline() as pipe:
            pipe.zremrangebyscore(key, 0, window_start)
            pipe.zadd(key, {str(current): current})
            pipe.zcard(key)
            pipe.expire(key, self.window)
            results = await pipe.execute()

        return results[2] <= self.limit

@app.get("/api/resource")
async def get_resource(
    redis: Redis = Depends(get_redis),
    user: User = Depends(get_current_user)
):
    rate_limiter = RateLimiter(redis, limit=100, window=3600)
    if not await rate_limiter.is_allowed(f"rate_limit:{user.id}"):
        raise HTTPException(status_code=429, detail="Rate limit exceeded")
    return {"data": "resource"}

自定义中间件

中间件提供了强大的请求/响应修改功能:

from fastapi import Request
from fastapi.middleware.base import BaseHTTPMiddleware
import time

class TimingMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        start_time = time.time()
        response = await call_next(request)
        process_time = time.time() - start_time
        response.headers["X-Process-Time"] = str(process_time)
        return response

app.add_middleware(TimingMiddleware)

API 版本控制

维护 API 版本对于向后兼容性至关重要:

from fastapi import APIRouter

v1_router = APIRouter(prefix="/v1")
v2_router = APIRouter(prefix="/v2")

@v1_router.get("/users/{user_id}")
async def get_user_v1(user_id: int):
    return {"version": "1", "user_id": user_id}

@v2_router.get("/users/{user_id}")
async def get_user_v2(user_id: int):
    return {"version": "2", "user_id": user_id}

app.include_router(v1_router)
app.include_router(v2_router)

错误处理

一致的错误处理提高了 API 的可靠性:

from fastapi import HTTPException
from fastapi.responses import JSONResponse

class CustomException(Exception):
    def __init__(self, message: str, code: str):
        self.message = message
        self.code = code

@app.exception_handler(CustomException)
async def custom_exception_handler(request, exc):
    return JSONResponse(
        status_code=400,
        content={
            "error": {
                "code": exc.code,
                "message": exc.message
            }
        }
    )

@app.get("/items/{item_id}")
async def get_item(item_id: int):
    if item_id < 0:
        raise CustomException(
            message="Invalid item ID",
            code="INVALID_ID"
        )
    return {"item_id": item_id}

测试

全面的测试确保API的可靠性:

from fastapi.testclient import TestClient
import pytest

client = TestClient(app)

@pytest.fixture
def test_db():
    # Setup test database
    db = Database()
    yield db
    # Cleanup

def test_read_item():
    response = client.get("/items/1")
    assert response.status_code == 200
    assert response.json() == {"item_id": 1}

def test_create_item():
    response = client.post(
        "/items/",
        json={"name": "Test Item"}
    )
    assert response.status_code == 201

生产部署

对于生产部署,请考虑以下配置:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import uvicorn

app = FastAPI(
    title="Production API",
    description="Production-ready FastAPI application",
    version="1.0.0",
    docs_url="/documentation",
    redoc_url=None
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://allowed-domain.com"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        workers=4,
        log_level="info",
        reload=False
    )

这些模式构成了强大的 FastAPI 应用程序的基础。异步功能与适当的资源管理和错误处理相结合,可创建高性能 API。定期测试和监控可确保生产环境中的可靠性。

请记住根据特定要求和规模调整这些模式。FastAPI 的灵活性允许自定义,同时保持性能和代码清晰度。

相关推荐

CentOS7服务器,这样搭建Tensorflow很快!我可以提前去吃饭了

CentOS7搭建Tensorflow框架凡是我相信的,我都做了;凡是我做了的事,都是全身心地投入去做的。WhateverIbelieved,Idid;andwhateverIdid,...

python2.0和python3.0的区别(python2.7和3.7哪个好)

Python3.0是Python语言的一次重大升级,与Python2.x系列存在许多不兼容的改动。以下是两者核心区别的全面总结,按重要性和使用频率排序:一、最关键的破坏性变更特性Pyth...

体验无GIL的自由线程Python:Python 3.13 新特征之一

全局解释器锁(GIL,GlobalInterpreterLock)是Python中备受争议的特性之一。它的主要作用是确保Python是一种线程安全的编程语言,防止多个线程同时访问和修改同一...

Python 3.8异步并发编程指南(python异步调用)

有效的提高程序执行效率的两种方法是异步和并发,Golang,node.js之所以可以有很高执行效率主要是他们的协程和异步并发机制。实际上异步和并发是每一种现代语言都在追求的特性,当然Python也不例...

Python测试框架pytest入门基础(pytest框架搭建)

Pytest简介Pytestisamaturefull-featuredPythontestingtoolthathelpsyouwritebetterprograms.T...

Python学不会来打我(8)字符串string类型深度解析

2025年全球开发者调查显示,90%的Python项目涉及字符串处理,而高效使用字符串可提升代码效率40%。本文系统拆解字符串核心操作,涵盖文本处理、数据清洗、模板生成等八大场景,助你掌握字符串编程精...

windows使用pyenv安装多python版本环境

官方的介绍。pyenvletsyoueasilyswitchbetweenmultipleversionsofPython.It’ssimple,unobtrusive,an...

Python 中 base64 编码与解码(Python 中 base64 编码与解码生成)

base64是经常使用的一种加密方式,在Python中有专门的库支持。本文主要介绍在Python2和Python3中的使用区别:在Python2环境:Python2.7.16(d...

Python项目整洁的秘诀:深入理解__init__.py文件

当你发现项目中import语句越来越混乱时,问题可能出在缺少这个关键文件上作为一名Python开发者,我曾深陷项目结构混乱的困境。直到真正理解了__init__.py文件的价值,我的代码世界才变得井然...

如何把一个Python应用程序装进Docker

准备容器无处不在,但是如何在Docker容器中运行Python应用程序呢?这篇文章将告诉你怎么做!如果您想知道,这些示例需要Python3.x。在深入讨论容器之前,让我们进一步讨论一下我们想要封装的...

python中数值比较大小的8种经典比较方法,不允许你还不知道

在Python中比较数值大小是基础但重要的操作。以下是8种经典比较方法及其应用场景,从基础到进阶的完整指南:1.基础比较运算符Python提供6种基础比较运算符:a,b=5,3...

Python程序员必看3分钟掌握if语句10个神技,第5个99%的人不知道

同事因为写错一个if被开除?全网疯传的Python避坑指南,看完我连夜改了代码!一、新手必踩的3大天坑(附救命代码)技巧1:缩进踩坑事件ifTrue:print("这样写必报错!...

为什么Python里遍历字符串比列表慢?3个底层原因揭秘

用字符串处理文本时,你可能正悄悄浪费性能。在日常Python开发中,我们经常需要遍历字符串和列表。但你是否注意过,当处理海量数据时,遍历字符串的速度明显比列表慢?这背后隐藏着Python设计的深层逻辑...

记录Python3.7.4更新到Python.3.7.8

Python官网Python安装包下载下载文件名称运行后选择升级选项等待安装安装完毕打开IDLE使用Python...

Python3中最常用的5种线程锁你会用吗

前言本章节将继续围绕threading模块讲解,基本上是纯理论偏多。对于日常开发者来讲很少会使用到本章节的内容,但是对框架作者等是必备知识,同时也是高频的面试常见问题。私信小编01即可获取大量Pyth...