在快节奏的 Web 开发世界中,性能至关重要。高效的缓存机制可以通过减少冗余计算和数据库查询来显着增强 API 的响应能力。在本文中,我们将探讨如何使用 SQLModel 和 Redis 将 py-cachify 库集成到 FastAPI 应用程序中,以实现缓存和并发控制。
目录:
- 简介
- 项目设置
- 使用 SQLModel 创建数据库模型
- 构建 FastAPI 端点
- 缓存端点结果
- 锁定更新端点的执行
- 运行应用程序
- 结论
介绍
缓存是一种强大的技术,通过存储昂贵操作的结果并从快速访问存储中提供它们来提高 Web 应用程序的性能。借助 py-cachify,我们可以无缝地将缓存添加到 FastAPI 应用程序中,并利用 Redis 进行存储。此外,py-cachify 提供并发控制工具,防止关键操作期间出现竞争情况。
在本教程中,我们将逐步在 FastAPI 应用程序中设置 py-cachify 库,并使用用于 ORM 的 SQLModel 和用于缓存的 Redis。
项目设置
让我们从设置项目环境开始。
先决条件
- Python 3.12
- 诗歌(您可以使用任何您喜欢的包管理器)
- 本地运行或远程访问的Redis服务器
安装依赖项
通过诗歌开始一个新项目:
# create new project poetry new --name app py-cachify-fastapi-demo # enter the directory cd py-cachify-fastapi-demo # point poetry to use python3.12 poetry env use python3.12 # add dependencies poetry add "fastapi[standard]" sqlmodel aiosqlite redis py-cachify
- FastAPI:用于构建 API 的 Web 框架。
- SQLModel aiosqlite:结合 SQLAlchemy 和 Pydantic 进行 ORM 和数据验证。
- Redis:用于与 Redis 交互的 Python 客户端。
- py-cachify:缓存和锁定实用程序。
初始化 py-cachify
在使用 py-cachify 之前,我们需要使用 Redis 客户端对其进行初始化。我们将使用 FastAPI 的寿命参数来完成此操作。
# app/main.py from contextlib import asynccontextmanager from fastapi import FastAPI from py_cachify import init_cachify from redis.asyncio import from_url @asynccontextmanager async def lifespan(_: FastAPI): init_cachify( # Replace with your redis url if it differs async_client=from_url('redis://localhost:6379/0'), ) yield app = FastAPI(lifespan=lifespan)
在生命周期内,我们:
- 创建异步 Redis 客户端。
- 使用此客户端初始化 py-cachify。
使用 SQLModel 创建数据库模型
我们将创建一个简单的用户模型来与我们的数据库交互。
# app/db.py from sqlmodel import Field, SQLModel class User(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) name: str email: str
设置数据库引擎并在生命周期函数中创建表:
# app/db.py # Adjust imports from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine # Add the following at the end of the file sqlite_file_name = 'database.db' sqlite_url = f'sqlite+aiosqlite:///{sqlite_file_name}' engine = create_async_engine(sqlite_url, echo=True) session_maker = async_sessionmaker(engine) # app/main.py # Adjust imports and lifespan function from sqlmodel import SQLModel from .db import engine @asynccontextmanager async def lifespan(_: FastAPI): init_cachify( async_client=from_url('redis://localhost:6379/0'), ) # Create SQL Model tables async with engine.begin() as conn: await conn.run_sync(SQLModel.metadata.create_all) yield
注意:为了简单起见,我们使用 SQLite,但您可以使用 SQLAlchemy 支持的任何数据库。
构建 FastAPI 端点
让我们创建端点来与我们的用户模型交互。
# create new project poetry new --name app py-cachify-fastapi-demo # enter the directory cd py-cachify-fastapi-demo # point poetry to use python3.12 poetry env use python3.12 # add dependencies poetry add "fastapi[standard]" sqlmodel aiosqlite redis py-cachify
缓存端点结果
现在,让我们缓存 read_user 端点的结果,以避免不必要的数据库查询。
端点代码将如下所示:
# app/main.py from contextlib import asynccontextmanager from fastapi import FastAPI from py_cachify import init_cachify from redis.asyncio import from_url @asynccontextmanager async def lifespan(_: FastAPI): init_cachify( # Replace with your redis url if it differs async_client=from_url('redis://localhost:6379/0'), ) yield app = FastAPI(lifespan=lifespan)
使用@cached装饰器:
- 我们使用 user_id 指定一个唯一的键。
- 将 TTL(生存时间)设置为 5 分钟(300 秒)。
- 5 分钟内使用相同 user_id 调用此端点将返回缓存的结果。
更新时重置缓存
当用户的数据更新时,我们需要重置缓存以确保客户端收到最新的信息。为了实现这一点,让我们修改 update_user 端点。
# app/db.py from sqlmodel import Field, SQLModel class User(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) name: str email: str
通过调用 read_user.reset(user_id=user_id),我们:
- 清除特定user_id的缓存数据。
- 确保后续 GET 请求从数据库获取新数据。
在下面,缓存的装饰器动态包装您的函数,添加 .reset 方法。此方法模仿函数的签名和类型,这样根据原始函数,它将是同步或异步的,并且将接受相同的参数。
.reset 方法使用缓存装饰器中定义的相同密钥生成逻辑来识别要使哪个缓存条目无效。例如,如果您的缓存键模式是 user-{user_id},则调用await read_user.reset(user_id=123) 将专门定位并删除 user_id=123 的缓存条目。
锁定更新端点的执行
为了防止更新期间的竞争条件,我们将使用一次装饰器来锁定更新端点的执行。
# app/db.py # Adjust imports from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine # Add the following at the end of the file sqlite_file_name = 'database.db' sqlite_url = f'sqlite+aiosqlite:///{sqlite_file_name}' engine = create_async_engine(sqlite_url, echo=True) session_maker = async_sessionmaker(engine) # app/main.py # Adjust imports and lifespan function from sqlmodel import SQLModel from .db import engine @asynccontextmanager async def lifespan(_: FastAPI): init_cachify( async_client=from_url('redis://localhost:6379/0'), ) # Create SQL Model tables async with engine.begin() as conn: await conn.run_sync(SQLModel.metadata.create_all) yield
曾经:
- 我们根据user_id锁定功能。
- 如果另一个请求尝试同时更新同一用户,它将立即返回带有 226 IM 已使用 状态代码的响应。
- 这可以防止同时更新导致数据不一致。
(可选)您可以配置 @once 以引发异常或在已获取锁的情况下返回特定值。
运行应用程序
现在是时候运行和测试我们的应用程序了!
1) 启动 Redis 服务器:
确保您的 Redis 服务器在本地运行或可远程访问。您可以使用 Docker 启动本地 Redis 服务器:
# app/main.py # Adjust imports from fastapi import Depends, FastAPI from sqlalchemy.ext.asyncio import AsyncSession from .db import User, engine, session_maker # Database session dependency async def get_session(): async with session_maker() as session: yield session app = FastAPI(lifespan=lifespan) @app.post('/users/') async def create_user(user: User, session: AsyncSession = Depends(get_session)) -> User: session.add(user) await session.commit() await session.refresh(user) return user @app.get('/users/{user_id}') async def read_user(user_id: int, session: AsyncSession = Depends(get_session)) -> User | None: return await session.get(User, user_id) @app.put('/users/{user_id}') async def update_user(user_id: int, new_user: User, session: AsyncSession = Depends(get_session)) -> User | None: user = await session.get(User, user_id) if not user: return None user.name = new_user.name user.email = new_user.email session.add(user) await session.commit() await session.refresh(user) return user
2) 运行 FastAPI 应用程序:
一切设置完毕后,您可以使用 Poetry 启动 FastAPI 应用程序。导航到项目的根目录并执行以下命令:
# app/main.py # Add the import from py_cachify import cached @app.get('/users/{user_id}') @cached('read_user-{user_id}', ttl=300) # New decorator async def read_user(user_id: int, session: AsyncSession = Depends(get_session)) -> User | None: return await session.get(User, user_id)
3) 测试和使用缓存和锁定:
缓存: 在 read_user 函数中添加延迟(例如,使用 asyncio.sleep)以模拟长时间运行的计算。观察结果缓存后响应时间如何显着改善。
示例:
# create new project poetry new --name app py-cachify-fastapi-demo # enter the directory cd py-cachify-fastapi-demo # point poetry to use python3.12 poetry env use python3.12 # add dependencies poetry add "fastapi[standard]" sqlmodel aiosqlite redis py-cachify
并发和锁定:同样,在 update_user 函数中引入延迟,以观察并发更新尝试时锁的行为。
示例:
# app/main.py from contextlib import asynccontextmanager from fastapi import FastAPI from py_cachify import init_cachify from redis.asyncio import from_url @asynccontextmanager async def lifespan(_: FastAPI): init_cachify( # Replace with your redis url if it differs async_client=from_url('redis://localhost:6379/0'), ) yield app = FastAPI(lifespan=lifespan)
这些延迟可以帮助您了解缓存和锁定机制的有效性,因为由于缓存,后续读取应该更快,并且应该通过锁定有效管理对同一资源的并发写入。
现在,您可以使用 Postman 等工具或访问 http://127.0.0.1:8000/docs(当应用程序运行时!)来测试端点,并观察性能改进和并发控制的实际情况。
享受使用增强型 FastAPI 应用程序进行实验的乐趣!
结论
通过将 py-cachify 集成到我们的 FastAPI 应用程序中,我们释放了众多优势,增强了 API 的性能和可靠性。
让我们回顾一下一些关键优势:
- 增强的性能:缓存重复的函数调用可以减少冗余计算和数据库命中,从而大大缩短响应时间。
- 并发控制:通过内置锁定机制,py-cachify 可以防止竞争条件并确保数据一致性 - 对于高并发访问的应用程序至关重要。
- 灵活性:无论您使用同步还是异步操作,py-cachify 都能无缝适应,使其成为现代 Web 应用程序的多功能选择。
- 易于使用:该库与 FastAPI 等流行的 Python 框架顺利集成,让您可以轻松上手。
- 完整类型注释: py-cachify 具有完全类型注释,有助于以最小的努力编写更好、更易于维护的代码。
- 最小设置: 如本教程所示,添加 py-cachify 只需要在现有设置之上添加几行即可充分利用其功能。
对于那些渴望进一步探索的人,请查看py-cachify 的 GitHub 存储库和官方文档以获取更深入的指导、教程和示例。
您可以在 GitHub 此处访问本教程的完整代码。请随意克隆存储库并尝试实现以满足您项目的需求。
如果您发现 py-cachify 有益,请考虑在 GitHub 上给它一颗星来支持该项目!您的支持有助于推动进一步的改进和新功能。
编码愉快!
以上是最大限度地提高 FastAPI 效率:使用 py-cachify 极快地实现缓存和锁定的详细内容。更多信息请关注PHP中文网其他相关文章!

Python不是严格的逐行执行,而是基于解释器的机制进行优化和条件执行。解释器将代码转换为字节码,由PVM执行,可能会预编译常量表达式或优化循环。理解这些机制有助于优化代码和提高效率。

可以使用多种方法在Python中连接两个列表:1.使用 操作符,简单但在大列表中效率低;2.使用extend方法,效率高但会修改原列表;3.使用 =操作符,兼具效率和可读性;4.使用itertools.chain函数,内存效率高但需额外导入;5.使用列表解析,优雅但可能过于复杂。选择方法应根据代码上下文和需求。

有多种方法可以合并Python列表:1.使用 操作符,简单但对大列表不内存高效;2.使用extend方法,内存高效但会修改原列表;3.使用itertools.chain,适用于大数据集;4.使用*操作符,一行代码合并小到中型列表;5.使用numpy.concatenate,适用于大数据集和性能要求高的场景;6.使用append方法,适用于小列表但效率低。选择方法时需考虑列表大小和应用场景。

CompiledLanguagesOffersPeedAndSecurity,而interneterpretledlanguages provideeaseafuseanDoctability.1)commiledlanguageslikec arefasterandSecureButhOnderDevevelmendeclementCyclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesandentency.2)cransportedeplatectentysenty

Python中,for循环用于遍历可迭代对象,while循环用于条件满足时重复执行操作。1)for循环示例:遍历列表并打印元素。2)while循环示例:猜数字游戏,直到猜对为止。掌握循环原理和优化技巧可提高代码效率和可靠性。

要将列表连接成字符串,Python中使用join()方法是最佳选择。1)使用join()方法将列表元素连接成字符串,如''.join(my_list)。2)对于包含数字的列表,先用map(str,numbers)转换为字符串再连接。3)可以使用生成器表达式进行复杂格式化,如','.join(f'({fruit})'forfruitinfruits)。4)处理混合数据类型时,使用map(str,mixed_list)确保所有元素可转换为字符串。5)对于大型列表,使用''.join(large_li

pythonuseshybridapprace,ComminingCompilationTobyTecoDeAndInterpretation.1)codeiscompiledtoplatform-Indepententbybytecode.2)bytecodeisisterpretedbybythepbybythepythonvirtualmachine,增强效率和通用性。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

禅工作室 13.0.1
功能强大的PHP集成开发环境

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中