File size: 3,241 Bytes
71fdb6d
7c71548
71fdb6d
 
9995fd4
 
 
71fdb6d
 
 
 
 
 
 
 
 
7c71548
 
 
9995fd4
7c71548
 
 
 
9995fd4
 
 
7c71548
 
9995fd4
 
 
 
 
 
 
7c71548
 
9995fd4
7c71548
9995fd4
7c71548
 
9995fd4
7c71548
 
 
 
 
9995fd4
 
7c71548
 
 
71fdb6d
7c71548
 
71fdb6d
9995fd4
7c71548
 
 
 
 
 
71fdb6d
7c71548
 
 
9995fd4
7c71548
 
 
 
9995fd4
7c71548
 
 
 
 
9995fd4
 
7c71548
 
9995fd4
7c71548
 
9995fd4
 
 
7c71548
9995fd4
 
7c71548
 
 
 
71fdb6d
7c71548
 
 
 
 
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
from fastapi import FastAPI, HTTPException, Depends
from fastapi.middleware.cors import CORSMiddleware
from typing import Dict, Any
import logging
from config import get_settings
from services import storage_service
import json

settings = get_settings()

# Configure logging
logging.basicConfig(
    level=logging.DEBUG if settings.DEBUG else logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)

app = FastAPI(title="Profile API", description="API to retrieve profile information")

# Enable CORS - Enhanced for better external access
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Allow all origins
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    allow_headers=["*"],
    expose_headers=["Content-Type", "X-Total-Count"],
)

# Add health check endpoint
@app.get("/health")
async def health_check():
    """
    Health check endpoint to verify the API server is running
    """
    return {"status": "ok", "message": "API server is running"}

@app.get("/api/profile/{profile_id}")
async def get_profile(profile_id: int) -> Dict[str, Any]:
    """
    Retrieve a profile by its ID
    
    Args:
        profile_id: The ID of the profile
        
    Returns:
        The profile document if found
    """
    try:
        # Retrieve the profile from SQLite
        profile = storage_service.get_profile(profile_id)
        
        # Check if profile exists
        if not profile:
            logger.warning(f"Profile not found: {profile_id}")
            raise HTTPException(status_code=404, detail=f"Profile with ID {profile_id} not found")
        
        logger.debug(f"Retrieved profile: {profile_id}")
        return profile
        
    except HTTPException:
        # Re-raise HTTP exceptions
        raise
    except Exception as e:
        # Handle any other exceptions
        logger.error(f"Error retrieving profile {profile_id}: {e}")
        raise HTTPException(status_code=500, detail=f"Error retrieving profile: {str(e)}")

@app.get("/api/profile/{profile_id}/image")
async def get_profile_image(profile_id: int) -> Dict[str, Any]:
    """
    Retrieve just the profile image for a given profile ID
    
    Args:
        profile_id: The ID of the profile
        
    Returns:
        JSON object with the profile image data
    """
    try:
        # Retrieve the profile from SQLite
        profile = storage_service.get_profile(profile_id)
        
        if not profile:
            logger.warning(f"Profile not found: {profile_id}")
            raise HTTPException(status_code=404, detail=f"Profile with ID {profile_id} not found")
        
        profile_img = profile.get("profileImg")
        
        if not profile_img:
            return {"profileImg": None}
        
        return {"profileImg": profile_img}
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error retrieving profile image {profile_id}: {e}")
        raise HTTPException(status_code=500, detail=f"Error retrieving profile image: {str(e)}")

if __name__ == "__main__":
    import uvicorn
    uvicorn.run("api:app", host="0.0.0.0", port=8000, reload=True)