国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁 后端開發(fā) Python教程 最大限度地提高 FastAPI 效率:使用 py-cachify 極快地實現(xiàn)緩存和鎖定

最大限度地提高 FastAPI 效率:使用 py-cachify 極快地實現(xiàn)緩存和鎖定

Dec 05, 2024 am 05:47 AM

Maximize Your FastAPI Efficiency: Blazingly Fast Implementation of Caching and Locking with py-cachify

在快節(jié)奏的 Web 開發(fā)世界中,性能至關重要。高效的緩存機制可以通過減少冗余計算和數(shù)據(jù)庫查詢來顯著增強 API 的響應能力。在本文中,我們將探討如何使用 SQLModel 和 Redis 將 py-cachify 庫集成到 FastAPI 應用程序中,以實現(xiàn)緩存和并發(fā)控制。

目錄:

  • 簡介
  • 項目設置
  • 使用 SQLModel 創(chuàng)建數(shù)據(jù)庫模型
  • 構建 FastAPI 端點
  • 緩存端點結果
  • 鎖定更新端點的執(zhí)行
  • 運行應用程序
  • 結論

介紹

緩存是一種強大的技術,通過存儲昂貴操作的結果并從快速訪問存儲中提供它們來提高 Web 應用程序的性能。借助 py-cachify,我們可以無縫地將緩存添加到 FastAPI 應用程序中,并利用 Redis 進行存儲。此外,py-cachify 提供并發(fā)控制工具,防止關鍵操作期間出現(xiàn)競爭情況。

在本教程中,我們將逐步在 FastAPI 應用程序中設置 py-cachify 庫,并使用用于 ORM 的 SQLModel 和用于緩存的 Redis。

項目設置

讓我們從設置項目環(huán)境開始。

先決條件

  • 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 和數(shù)據(jù)驗證。
  • Redis:用于與 Redis 交互的 Python 客戶端。
  • py-cachify:緩存和鎖定實用程序。

初始化 py-cachify

在使用 py-cachify 之前,我們需要使用 Redis 客戶端對其進行初始化。我們將使用 FastAPI 的壽命參數(shù)來完成此操作。

# 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)

在生命周期內(nèi),我們:

  • 創(chuàng)建異步 Redis 客戶端。
  • 使用此客戶端初始化 py-cachify。

使用 SQLModel 創(chuàng)建數(shù)據(jù)庫模型

我們將創(chuàng)建一個簡單的用戶模型來與我們的數(shù)據(jù)庫交互。

# 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

設置數(shù)據(jù)庫引擎并在生命周期函數(shù)中創(chuàng)建表:

# 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 支持的任何數(shù)據(jù)庫。

構建 FastAPI 端點

讓我們創(chuàng)建端點來與我們的用戶模型交互。

# 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

緩存端點結果

現(xiàn)在,讓我們緩存 read_user 端點的結果,以避免不必要的數(shù)據(jù)庫查詢。

端點代碼將如下所示:

# 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 分鐘內(nèi)使用相同 user_id 調(diào)用此端點將返回緩存的結果。

更新時重置緩存

當用戶的數(shù)據(jù)更新時,我們需要重置緩存以確??蛻舳耸盏阶钚碌男畔ⅰ榱藢崿F(xiàn)這一點,讓我們修改 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

通過調(diào)用 read_user.reset(user_id=user_id),我們:

  • 清除特定user_id的緩存數(shù)據(jù)。
  • 確保后續(xù) GET 請求從數(shù)據(jù)庫獲取新數(shù)據(jù)。

在下面,緩存的裝飾器動態(tài)包裝您的函數(shù),添加 .reset 方法。此方法模仿函數(shù)的簽名和類型,這樣根據(jù)原始函數(shù),它將是同步或異步的,并且將接受相同的參數(shù)。

.reset 方法使用緩存裝飾器中定義的相同密鑰生成邏輯來識別要使哪個緩存條目無效。例如,如果您的緩存鍵模式是 user-{user_id},則調(diào)用await read_user.reset(user_id=123) 將專門定位并刪除 user_id=123 的緩存條目。

鎖定更新端點的執(zhí)行

為了防止更新期間的競爭條件,我們將使用一次裝飾器來鎖定更新端點的執(zhí)行。

# 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

曾經(jīng):

  • 我們根據(jù)user_id鎖定功能。
  • 如果另一個請求嘗試同時更新同一用戶,它將立即返回帶有 226 IM 已使用 狀態(tài)代碼的響應。
  • 這可以防止同時更新導致數(shù)據(jù)不一致。

(可選)您可以配置 @once 以引發(fā)異?;蛟谝勋@取鎖的情況下返回特定值。

運行應用程序

現(xiàn)在是時候運行和測試我們的應用程序了!

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 應用程序。導航到項目的根目錄并執(zhí)行以下命令:

# 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 函數(shù)中添加延遲(例如,使用 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

并發(fā)和鎖定:同樣,在 update_user 函數(shù)中引入延遲,以觀察并發(fā)更新嘗試時鎖的行為。

示例:

# 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)

這些延遲可以幫助您了解緩存和鎖定機制的有效性,因為由于緩存,后續(xù)讀取應該更快,并且應該通過鎖定有效管理對同一資源的并發(fā)寫入。

現(xiàn)在,您可以使用 Postman 等工具或訪問 http://127.0.0.1:8000/docs(當應用程序運行時?。﹣頊y試端點,并觀察性能改進和并發(fā)控制的實際情況。

享受使用增強型 FastAPI 應用程序進行實驗的樂趣!

結論

通過將 py-cachify 集成到我們的 FastAPI 應用程序中,我們釋放了眾多優(yōu)勢,增強了 API 的性能和可靠性。

讓我們回顧一下一些關鍵優(yōu)勢:

  • 增強的性能:緩存重復的函數(shù)調(diào)用可以減少冗余計算和數(shù)據(jù)庫命中,從而大大縮短響應時間。
  • 并發(fā)控制:通過內(nèi)置鎖定機制,py-cachify 可以防止競爭條件并確保數(shù)據(jù)一致性 - 對于高并發(fā)訪問的應用程序至關重要。
  • 靈活性:無論您使用同步還是異步操作,py-cachify 都能無縫適應,使其成為現(xiàn)代 Web 應用程序的多功能選擇。
  • 易于使用:該庫與 FastAPI 等流行的 Python 框架順利集成,讓您可以輕松上手。
  • 完整類型注釋: py-cachify 具有完全類型注釋,有助于以最小的努力編寫更好、更易于維護的代碼。
  • 最小設置: 如本教程所示,添加 py-cachify 只需要在現(xiàn)有設置之上添加幾行即可充分利用其功能。

對于那些渴望進一步探索的人,請查看py-cachify 的 GitHub 存儲庫官方文檔以獲取更深入的指導、教程和示例。

您可以在 GitHub 此處訪問本教程的完整代碼。請隨意克隆存儲庫并嘗試實現(xiàn)以滿足您項目的需求。

如果您發(fā)現(xiàn) py-cachify 有益,請考慮在 GitHub 上給它一顆星來支持該項目!您的支持有助于推動進一步的改進和新功能。

編碼愉快!

以上是最大限度地提高 FastAPI 效率:使用 py-cachify 極快地實現(xiàn)緩存和鎖定的詳細內(nèi)容。更多信息請關注PHP中文網(wǎng)其他相關文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻,版權歸原作者所有,本站不承擔相應法律責任。如您發(fā)現(xiàn)有涉嫌抄襲侵權的內(nèi)容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動的應用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機

Video Face Swap

Video Face Swap

使用我們完全免費的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

Python類中的多態(tài)性 Python類中的多態(tài)性 Jul 05, 2025 am 02:58 AM

多態(tài)是Python面向?qū)ο缶幊讨械暮诵母拍?,指“一種接口,多種實現(xiàn)”,允許統(tǒng)一處理不同類型的對象。1.多態(tài)通過方法重寫實現(xiàn),子類可重新定義父類方法,如Animal類的speak()方法在Dog和Cat子類中有不同實現(xiàn)。2.多態(tài)的實際用途包括簡化代碼結構、增強可擴展性,例如圖形繪制程序中統(tǒng)一調(diào)用draw()方法,或游戲開發(fā)中處理不同角色的共同行為。3.Python實現(xiàn)多態(tài)需滿足:父類定義方法,子類重寫該方法,但不要求繼承同一父類,只要對象實現(xiàn)相同方法即可,這稱為“鴨子類型”。4.注意事項包括保持方

如何在Python中產(chǎn)生隨機字符串? 如何在Python中產(chǎn)生隨機字符串? Jun 21, 2025 am 01:02 AM

要生成隨機字符串,可以使用Python的random和string模塊組合。具體步驟為:1.導入random和string模塊;2.定義字符池如string.ascii_letters和string.digits;3.設定所需長度;4.調(diào)用random.choices()生成字符串。例如代碼包括importrandom與importstring、設置length=10、characters=string.ascii_letters string.digits并執(zhí)行''.join(random.c

我如何寫一個簡單的'你好,世界!” Python的程序? 我如何寫一個簡單的'你好,世界!” Python的程序? Jun 24, 2025 am 12:45 AM

"Hello,World!"程序是用Python編寫的最基礎示例,用于展示基本語法并驗證開發(fā)環(huán)境是否正確配置。1.它通過一行代碼print("Hello,World!")實現(xiàn),運行后會在控制臺輸出指定文本;2.運行步驟包括安裝Python、使用文本編輯器編寫代碼、保存為.py文件、在終端執(zhí)行該文件;3.常見錯誤有遺漏括號或引號、誤用大寫Print、未保存為.py格式以及運行環(huán)境錯誤;4.可選工具包括本地文本編輯器 終端、在線編輯器(如replit.com)

Python中的算法是什么?為什么它們很重要? Python中的算法是什么?為什么它們很重要? Jun 24, 2025 am 12:43 AM

AlgorithmsinPythonareessentialforefficientproblem-solvinginprogramming.Theyarestep-by-stepproceduresusedtosolvetaskslikesorting,searching,anddatamanipulation.Commontypesincludesortingalgorithmslikequicksort,searchingalgorithmslikebinarysearch,andgrap

什么是python的列表切片? 什么是python的列表切片? Jun 29, 2025 am 02:15 AM

ListslicinginPythonextractsaportionofalistusingindices.1.Itusesthesyntaxlist[start:end:step],wherestartisinclusive,endisexclusive,andstepdefinestheinterval.2.Ifstartorendareomitted,Pythondefaultstothebeginningorendofthelist.3.Commonusesincludegetting

python`@classmethod'裝飾師解釋了 python`@classmethod'裝飾師解釋了 Jul 04, 2025 am 03:26 AM

類方法是Python中通過@classmethod裝飾器定義的方法,其第一個參數(shù)為類本身(cls),用于訪問或修改類狀態(tài)。它可通過類或?qū)嵗{(diào)用,影響的是整個類而非特定實例;例如在Person類中,show_count()方法統(tǒng)計創(chuàng)建的對象數(shù)量;定義類方法時需使用@classmethod裝飾器并將首參命名為cls,如change_var(new_value)方法可修改類變量;類方法與實例方法(self參數(shù))、靜態(tài)方法(無自動參數(shù))不同,適用于工廠方法、替代構造函數(shù)及管理類變量等場景;常見用途包括從

如何使用CSV模塊在Python中使用CSV文件? 如何使用CSV模塊在Python中使用CSV文件? Jun 25, 2025 am 01:03 AM

Python的csv模塊提供了讀寫CSV文件的簡單方法。1.讀取CSV文件時,可使用csv.reader()逐行讀取,并將每行數(shù)據(jù)作為字符串列表返回;若需通過列名訪問數(shù)據(jù),則可用csv.DictReader(),它將每行映射為字典。2.寫入CSV文件時,使用csv.writer()并調(diào)用writerow()或writerows()方法寫入單行或多行數(shù)據(jù);若要寫入字典數(shù)據(jù),則使用csv.DictWriter(),需先定義列名并通過writeheader()寫入表頭。3.處理邊緣情況時,模塊自動處理

Python函數(shù)參數(shù)和參數(shù) Python函數(shù)參數(shù)和參數(shù) Jul 04, 2025 am 03:26 AM

參數(shù)(parameters)是定義函數(shù)時的占位符,而傳參(arguments)是調(diào)用時傳入的具體值。1.位置參數(shù)需按順序傳遞,順序錯誤會導致結果錯誤;2.關鍵字參數(shù)通過參數(shù)名指定,可改變順序且提高可讀性;3.默認參數(shù)值在定義時賦值,避免重復代碼,但應避免使用可變對象作為默認值;4.args和*kwargs可處理不定數(shù)量的參數(shù),適用于通用接口或裝飾器,但應謹慎使用以保持可讀性。

See all articles