-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
49 lines (40 loc) · 1.15 KB
/
main.py
File metadata and controls
49 lines (40 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from fastapi import FastAPI
import aioredis
import os
app = FastAPI()
# Setup Redis connection
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
redis_host = os.environ["REDIS_HOST"]
redis_port = os.environ["REDIS_PORT"]
redis = None
@app.on_event("startup")
async def startup_event():
global redis
redis = aioredis.from_url(f"redis://{redis_host}:{redis_port}")
@app.on_event("shutdown")
async def shutdown_event():
await redis.close()
@app.get("/")
async def read_root():
# Example Redis command
await redis.set("mykey", "Hello from Redis!")
value = await redis.get("mykey", encoding="utf-8")
return {"message": value}
@app.get("/redis")
async def test_redis_connection():
try:
pong = await redis.ping()
if pong:
return {"status": "Connection to Redis is successful"}
else:
return {"status": "Connection to Redis failed"}
except Exception as e:
return {"status": f"error: {str(e)}"}
@app.get("/up")
async def health_check():
"""
Health check endpoint to ensure the container is running.
"""
return {"status": "OK"}