Mise en cache dans FastAPI : débloquer un développement haute performance :

DDD
Libérer: 2024-10-18 11:39:02
original
363 Les gens l'ont consulté

Dans le monde numérique d'aujourd'hui, chaque action, qu'il s'agisse de naviguer sur une application de rencontres ou de finaliser un achat, repose sur des API fonctionnant efficacement en coulisses. En tant que développeurs back-end, nous savons que chaque milliseconde compte. Mais comment pouvons-nous accélérer la réponse des API ? La réponse réside dans la mise en cache.

La mise en cache est une technique qui stocke en mémoire les données fréquemment consultées, permettant aux API de répondre instantanément au lieu d'interroger à chaque fois une base de données plus lente. Pensez-y comme si vous gardiez les ingrédients clés (sel, poivre, huile) sur le plan de travail de votre cuisine au lieu de les récupérer dans le garde-manger à chaque fois que vous cuisinez : cela vous fait gagner du temps et rend le processus plus efficace. De même, la mise en cache réduit les temps de réponse des API en stockant les données fréquemment demandées dans un emplacement rapide et accessible, comme Redis.

Bibliothèques requises à installer

Pour vous connecter à Redis Cache avec FastAPI, nous avons besoin que les bibliothèques suivantes soient préinstallées.

pip install fastapi uvicorn aiocache pydantic
Copier après la connexion

Pydantic sert à créer des tables et des structures de bases de données. aiocache effectuera des opérations asynchrones sur le cache. uvicorn est responsable du fonctionnement du serveur.

Configuration et vérification de Redis :

La configuration de Redis directement dans un système Windows n'est pas possible à ce stade. Par conséquent, il doit être configuré et exécuté dans le sous-système Windows pour Linux. Les instructions pour installer WSL sont données ci-dessous

Caching in FastAPI: Unlocking High-Performance Development:

Installer WSL | Microsoft Apprendre

Installez le sous-système Windows pour Linux avec la commande wsl --install. Utilisez un terminal Bash sur votre machine Windows exécuté par votre distribution Linux préférée - Ubuntu, Debian, SUSE, Kali, Fedora, Pengwin, Alpine et bien d'autres sont disponibles.

apprendre.microsoft.com

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

sudo apt update
sudo apt install redis-server
sudo systemctl start redis
Copier après la connexion

To test Redis server connectivity, the following command is used

redis-cli
Copier après la connexion

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
Copier après la connexion

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
Copier après la connexion

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

Copier après la connexion

Step 4: Run the Application

Start your FastAPI application by running:

uvicorn main:app --reload
Copier après la connexion

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

http://127.0.0.1:8000/users/1
Copier après la connexion

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 *
Copier après la connexion

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.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:dev.to
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!