user_profile.py
2.09 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
50
51
52
53
54
55
56
57
58
import sys
from pathlib import Path
import time
# Add the project root to Python path
current_dir = Path(__file__).parent
project_root = current_dir.parent.parent
sys.path.append(str(project_root))
sys.path.append(str(project_root / 'snapshot_pb/generated'))
from typing import Optional
import redis
from config.app_config import REDIS_CONFIG
from config.logging_config import get_app_logger
from user_profile_pb2 import UserProfile
logger = get_app_logger(__name__)
class UserProfileManager:
def __init__(self):
self.redis_client = redis.Redis(
host=REDIS_CONFIG['host'],
port=REDIS_CONFIG['port'],
db=REDIS_CONFIG['snapshot_db'],
password=REDIS_CONFIG['password'],
decode_responses=False
)
def get_user_profile(self, uid: str) -> Optional[UserProfile]:
"""Get user profile from Redis"""
logger.debug(f"Fetching user profile for uid: {uid}")
profile_key = f"user_profile:{uid}"
if not self.redis_client.exists(profile_key):
logger.debug(f"No profile data found for uid: {uid}")
return None
# Measure Redis fetch time
fetch_start = time.time()
profile_data = self.redis_client.get(profile_key)
fetch_time = time.time() - fetch_start
if not profile_data:
logger.debug(f"No profile data found for uid: {uid}")
return None
try:
# Measure deserialization time
deserialize_start = time.time()
profile = UserProfile()
profile.ParseFromString(profile_data)
deserialize_time = time.time() - deserialize_start
logger.info(f"REDIS_COST_TIME: key: {profile_key}, Response size: {len(profile_data)//1024}KB, Redis fetch: {fetch_time*1000:.2f}ms, Deserialization: {deserialize_time*1000:.2f}ms for uid: {uid}")
return profile
except Exception as e:
logger.error(f"Error deserializing profile data for uid {uid}: {str(e)}")
return None