搜尋
首頁後端開發Python教學FastAPI 中的快取:解鎖高效能開發:

在當今的數位世界中,每項操作(無論是在約會應用程式上滑動還是完成購買)都依賴在幕後高效工作的 API。作為後端開發人員,我們知道每一毫秒都很重要。但如何才能讓API反應更快呢?答案在於快取。

快取是一種將經常存取的資料儲存在記憶體中的技術,允許 API 立即回應,而不是每次都查詢速度較慢的資料庫。可以將其想像為將關鍵成分(鹽、胡椒、油)放在廚房檯面上,而不是每次烹飪時從食品儲藏室取出它們,這樣可以節省時間並使過程更加高效。同樣,快取透過將常用請求的資料儲存在快速、可存取的位置(例如 Redis)來減少 API 回應時間。

需要安裝的庫

要使用FastAPI連接Redis緩存,我們需要預先安裝以下程式庫。

pip install fastapi uvicorn aiocache pydantic

Pydantic 用於建立資料庫表和結構。 aiocache會對Cache進行非同步操作。 uvicorn負責伺服器的運作。

Redis 設定與驗證:

目前還無法在 Windows 系統中直接設定 Redis。因此,它必須在適用於 Linux 的 Windows 子系統中安裝和運作。下面給出了安裝 WSL 的說明

Caching in FastAPI: Unlocking High-Performance Development:

安裝 WSL |微軟學習

使用指令 wsl --install 安裝適用於 Linux 的 Windows 子系統。在您首選的 Linux 發行版運行的 Windows 電腦上使用 Bash 終端機 - Ubuntu、Debian、SUSE、Kali、Fedora、Pengwin、Alpine 等都可用。

學習微軟網站

Post installing WSL, the following commands are required to install Redis

sudo apt update
sudo apt install redis-server
sudo systemctl start redis

To test Redis server connectivity, the following command is used

redis-cli

After this command, it will enter into a virtual terminal of port 6379. In that terminal, the redis commands can be typed and tested.

Setting Up the FastAPI Application

Let’s create a simple FastAPI app that retrieves user information and caches it for future requests. We will use Redis for storing cached responses.

Step 1: Define the Pydantic Model for User Data

We’ll use Pydantic to define our User model, which represents the structure of the API response.

from pydantic import BaseModel

class User(BaseModel):
    id: int
    name: str
    email: str
    age: int

Step 2: Create a Caching Decorator

To avoid repeating the caching logic for each endpoint, we’ll create a reusable caching decorator using the aiocache library. This decorator will attempt to retrieve the response from Redis before calling the actual function.

import json
from functools import wraps
from aiocache import Cache
from fastapi import HTTPException

def cache_response(ttl: int = 60, namespace: str = "main"):
    """
    Caching decorator for FastAPI endpoints.

    ttl: Time to live for the cache in seconds.
    namespace: Namespace for cache keys in Redis.
    """
    def decorator(func):
        @wraps(func)
        async def wrapper(*args, **kwargs):
            user_id = kwargs.get('user_id') or args[0]  # Assuming the user ID is the first argument
            cache_key = f"{namespace}:user:{user_id}"

            cache = Cache.REDIS(endpoint="localhost", port=6379, namespace=namespace)

            # Try to retrieve data from cache
            cached_value = await cache.get(cache_key)
            if cached_value:
                return json.loads(cached_value)  # Return cached data

            # Call the actual function if cache is not hit
            response = await func(*args, **kwargs)

            try:
                # Store the response in Redis with a TTL
                await cache.set(cache_key, json.dumps(response), ttl=ttl)
            except Exception as e:
                raise HTTPException(status_code=500, detail=f"Error caching data: {e}")

            return response
        return wrapper
    return decorator

Step 3: Implement a FastAPI Route for User Details

We’ll now implement a FastAPI route that retrieves user information based on a user ID. The response will be cached using Redis for faster access in subsequent requests.

from fastapi import FastAPI

app = FastAPI()

# Sample data representing users in a database
users_db = {
    1: {"id": 1, "name": "Alice", "email": "alice@example.com", "age": 25},
    2: {"id": 2, "name": "Bob", "email": "bob@example.com", "age": 30},
    3: {"id": 3, "name": "Charlie", "email": "charlie@example.com", "age": 22},
}

@app.get("/users/{user_id}")
@cache_response(ttl=120, namespace="users")
async def get_user_details(user_id: int):
    # Simulate a database call by retrieving data from users_db
    user = users_db.get(user_id)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")

    return user

Step 4: Run the Application

Start your FastAPI application by running:

uvicorn main:app --reload

Now, you can test the API by fetching user details via:

http://127.0.0.1:8000/users/1

The first request will fetch the data from the users_db, but subsequent requests will retrieve the data from Redis.

Testing the Cache

You can verify the cache by inspecting the keys stored in Redis. Open the Redis CLI:

redis-cli
KEYS *

You will get all keys that have been stored in the Redis till TTL.

How Caching Works in This Example

First Request

: When the user data is requested for the first time, the API fetches it from the database (users_db) and stores the result in Redis with a time-to-live (TTL) of 120 seconds.

Subsequent Requests:

Any subsequent requests for the same user within the TTL period are served directly from Redis, making the response faster and reducing the load on the database.

TTL (Time to Live):

After 120 seconds, the cache entry expires, and the data is fetched from the database again on the next request, refreshing the cache.

Conclusion

In this tutorial, we’ve demonstrated how to implement Redis caching in a FastAPI application using a simple user details example. By caching API responses, you can significantly improve the performance of your application, particularly for data that doesn't change frequently.

Please do upvote and share if you find this article useful.

以上是FastAPI 中的快取:解鎖高效能開發:的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何解決Linux終端中查看Python版本時遇到的權限問題?如何解決Linux終端中查看Python版本時遇到的權限問題?Apr 01, 2025 pm 05:09 PM

Linux終端中查看Python版本時遇到權限問題的解決方法當你在Linux終端中嘗試查看Python的版本時,輸入python...

我如何使用美麗的湯來解析HTML?我如何使用美麗的湯來解析HTML?Mar 10, 2025 pm 06:54 PM

本文解釋瞭如何使用美麗的湯庫來解析html。 它詳細介紹了常見方法,例如find(),find_all(),select()和get_text(),以用於數據提取,處理不同的HTML結構和錯誤以及替代方案(SEL)

如何使用TensorFlow或Pytorch進行深度學習?如何使用TensorFlow或Pytorch進行深度學習?Mar 10, 2025 pm 06:52 PM

本文比較了Tensorflow和Pytorch的深度學習。 它詳細介紹了所涉及的步驟:數據準備,模型構建,培訓,評估和部署。 框架之間的關鍵差異,特別是關於計算刻度的

Python中的數學模塊:統計Python中的數學模塊:統計Mar 09, 2025 am 11:40 AM

Python的statistics模塊提供強大的數據統計分析功能,幫助我們快速理解數據整體特徵,例如生物統計學和商業分析等領域。無需逐個查看數據點,只需查看均值或方差等統計量,即可發現原始數據中可能被忽略的趨勢和特徵,並更輕鬆、有效地比較大型數據集。 本教程將介紹如何計算平均值和衡量數據集的離散程度。除非另有說明,本模塊中的所有函數都支持使用mean()函數計算平均值,而非簡單的求和平均。 也可使用浮點數。 import random import statistics from fracti

哪些流行的Python庫及其用途?哪些流行的Python庫及其用途?Mar 21, 2025 pm 06:46 PM

本文討論了諸如Numpy,Pandas,Matplotlib,Scikit-Learn,Tensorflow,Tensorflow,Django,Blask和請求等流行的Python庫,並詳細介紹了它們在科學計算,數據分析,可視化,機器學習,網絡開發和H中的用途

如何使用Python創建命令行接口(CLI)?如何使用Python創建命令行接口(CLI)?Mar 10, 2025 pm 06:48 PM

本文指導Python開發人員構建命令行界面(CLIS)。 它使用Typer,Click和ArgParse等庫詳細介紹,強調輸入/輸出處理,並促進用戶友好的設計模式,以提高CLI可用性。

在Python中如何高效地將一個DataFrame的整列複製到另一個結構不同的DataFrame中?在Python中如何高效地將一個DataFrame的整列複製到另一個結構不同的DataFrame中?Apr 01, 2025 pm 11:15 PM

在使用Python的pandas庫時,如何在兩個結構不同的DataFrame之間進行整列複製是一個常見的問題。假設我們有兩個Dat...

解釋Python中虛擬環境的目的。解釋Python中虛擬環境的目的。Mar 19, 2025 pm 02:27 PM

文章討論了虛擬環境在Python中的作用,重點是管理項目依賴性並避免衝突。它詳細介紹了他們在改善項目管理和減少依賴問題方面的創建,激活和利益。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。