@lru_cache 装饰器实现全局配置

在 FastAPI 项目里,配置对象通常只需要加载一次。用 @lru_cache 装饰依赖函数,可以在不引入全局变量的前提下,实现「单例式」的配置访问,测试时也方便覆盖。

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from functools import lru_cache

from fastapi import Depends, FastAPI
from typing_extensions import Annotated

from . import config

app = FastAPI()


@lru_cache
def get_settings():
return config.Settings()


@app.get("/info")
async def info(settings: Annotated[config.Settings, Depends(get_settings)]):
return {
"app_name": settings.app_name,
"admin_email": settings.admin_email,
"items_per_user": settings.items_per_user,
}

工作原理

@lru_cache 装饰的函数,第一次调用时正常执行并缓存返回值;后续调用直接返回缓存结果,不再重新执行函数体。

get_settings() 来说,函数没有参数,所以永远返回同一个 Settings 实例——行为上接近全局变量,但通过依赖注入暴露,测试时可以替换 get_settings 的返回值。

技术细节

@lru_cache 会按参数组合分别缓存。有参数的函数,每种参数组合只执行一次;无参数的函数则始终返回同一对象。

functools.lru_cache 是 Python 标准库的一部分,详见 官方文档

Notice: 正常情况下,这里会有一个基于utteranc.es的留言系统,如果看不到,可能要想想办法才能看到。

Powered by Hexo and Hexo-theme-hiker

Copyright © 2012 - 2026 tiaobug.com All Rights Reserved.

鲁ICP备2024124237号-1