Skip to content

Instantly share code, notes, and snippets.

@thibaultserti
Last active May 31, 2024 12:23
Show Gist options
  • Save thibaultserti/a24d6e6f5f544766f583b5c480e8a5bb to your computer and use it in GitHub Desktop.
Save thibaultserti/a24d6e6f5f544766f583b5c480e8a5bb to your computer and use it in GitHub Desktop.
FastAPI + Redis

Le code a été conçu pour python 3.11 et redis v5.

from fastapi import FastAPI
import redis
import os
app = FastAPI()
REDIS_HOST = os.getenv("REDIS_HOST", "localhost")
redis_client = redis.StrictRedis(host=REDIS_HOST, port=6379, db=0)
@app.get("/")
def status():
return {"status": "OK"}
@app.get("/get_data_from_redis/{key}")
def read_item(key: str):
value = redis_client.get(key)
if value:
return {"key": key, "value": value.decode('utf-8')}
else:
return {"key": key, "value": "Key not found"}
@app.post("/set_item/{key}/{value}")
def set_item(key: str, value: str):
redis_client.set(key, value)
return {"message": "Item set successfully", "key": key, "value": value}
fastapi==0.95
redis==5.0.1
uvicorn==0.24.0
@thibaultserti
Copy link
Author

thibaultserti commented May 31, 2024

Pour installer les dépendances
pip3 install -r requirements.txt

Pour lancer l'application
uvicorn main:app --host 0.0.0.0

L'API est disponible sur port 8000 par défaut et le Swagger est disponible sur /docs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment