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

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

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

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 的灵活性允许自定义,同时保持性能和代码清晰度。

相关推荐

编程学子看过来,竞赛刷题网站推荐

2022年编程竞赛已经公布,想要在今年取得竞赛成绩的学生,一定要把握寒假时间,学习知识的同时通过刷题,巩固所学知识,提升解题能力。小编为大家推荐几个刷题网站,想要竞赛的学生一定不要错过。USACO美国...

给大家推荐些好的c语言代码的网站

C语言,那就来推荐几个吧,部分含有C++:1、TheLinuxKernelArchives(kernel.org)Linux内核源码,仅限于C,但内核庞大,不太适合新手;2、redis(redi...

推荐几个编程入门学习网站_比较好的编程自学网站

有一些刚上大学的朋友和想对编程感兴趣的朋友经常会让我推荐学习网站,下面几个是我认为零基础学编程比较好的网站,希望大家都有收获!1.W3schoolhttp://www.w3school.com.c...

10个最值得收藏的编程学习网站_有什么学编程的网站

程序员是一个需要不断学习的职业。幸运的是,在这个互联网时代,知识就在那里,等着我们去获取。以下我列举一些免费的编程学习网站包含多个开发语言Java、php、html、javascript等多个。1、h...

6个超酷的练习算法,学习编程的网站

在不了解算法的前提下,您无法通过Google或Facebook的采访。那么为什么不现在学习。我是一位拥有15年以上经验的程序员。从高中开始的第一年,我在算法上学习和工作很多。在我毕业之前,我一直...

在线 python 编程的网站_python3在线编程,python3在线编译器,在线编辑器

以下是一些提供在线Python编程环境的网站:1.Repl.it:Repl.it提供了一个多语言在线编程平台,您可以使用它在任何地方编写、运行、共享代码。Repl.it支持多种编程语言,包括Pyth...

推荐 7 个能过招全球程序员的编程挑战网站,欢迎挑战!

作为程序员的你,是不是经常估不准自己的编程水平?下面推荐7个能过招全球程序员的编程挑战网站,助你磨练技巧,提升技能,最终问鼎代码江湖!1.HackerRank你可以参加各种编码竞赛,比如算法、数学...

盘点 20 个编程学习教程网站,建议收藏

欢迎关注@程序员柠檬橙私信回复「1024」获取海量编程学习资源!如果你想学习编程,现在互联网这么方便,不用着急报名培训班,有很多高质量的编程学习资源网站可供你学习,程序员日常浏览的技术教程网站有哪些...

Flask 数据可视化_flourish数据可视化

数据可视化是数据处理中的重要部分,前面我们了解了Flask的开发和部署,如何用Flask做数据可视化呢?今天我们来了解一下。Python语言极富表达力,并且拥有众多的数据分析库和框架,是数据...

【python 工具】selenium 浏览器操作

selenium的安装步骤:1.安装selenium,打开cmd控制台pipinstallselenium2.安装驱动程序(我这里安装的是chromedriver),用来启动chrome浏览器...

可视化爬虫工具,EasySpider软件体验

现在提起爬虫,大家可能会联想到Python语言,然后就是各种使用无头浏览器去网页上爬取数据,使用Python的过程相较于使用其他语言来说,简单了不少。但毕竟是编程语言,也需要去学习来适配各种网...

cursor+mcp+playwright,让AI给你推荐五一旅游胜地

阅读本文前提当你已了解mcp是什么,若不知,猛击:https://github.com/modelcontextprotocol/servers。最近有个小需求,根据用户输入内容,使用大模型来理解用户...

Cursor+Claude+Playwright:AI 让自动化测试效率暴涨,快到飞起!

一、引言随着AI时代的到来,软件测试变得越来越复杂,如何高效、准确地进行自动化测试成了每一个开发团队必须面对的问题。在日常工作中,测试工作常常面临各种挑战,比如功能复杂、需求频繁变更、时间紧迫等。传统...

推荐一个检测 JS 内存泄漏的神器_js内存泄漏的几种情况

大家好,我是Echa哥。作为一名Web应用程序开发者,排查和修复JavaScript代码的内存泄漏一直是最困扰我的问题之一。最近,Meta开源了一款检测JavaScript代码内存泄漏...

Python+Playwright自动化实战:高效爬虫全攻略

一、为什么选择Playwright?在信息爆炸的时代,数据获取能力直接决定内容生产效率。Playwright作为微软开源的新型自动化工具,凭借以下优势成为技术创作者的新宠:支持Chromium/Web...