import os import requests import logging from fastapi import FastAPI, Request, HTTPException from fastapi.responses import HTMLResponse # Configure logging logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) # Initialize FastAPI app app = FastAPI() # --- IP Geolocation Logic --- def get_client_ip(request: Request) -> str: """ Extracts the client's IP address from the request. Handles common proxy headers (like X-Forwarded-For) if present. """ # Check for common proxy headers first x_forwarded_for = request.headers.get("x-forwarded-for") if x_forwarded_for: # The first IP is the client's IP return x_forwarded_for.split(',')[0].strip() # Fallback to the direct client host return request.client.host def get_ip_geolocation(ip_address: str): """Fetches geolocation data for a given IP address using ipinfo.io.""" # Using a free, public IP geolocation service. # Note: For production, consider rate limits and API keys. if ip_address in ["127.0.0.1", "::1"]: logger.warning(f"Skipping IP geolocation for local address: {ip_address}") return {"ip": ip_address, "error": "Local IP address, skipping external lookup."} try: # Use a timeout to prevent hanging response = requests.get(f"https://ipinfo.io/{ip_address}/json", timeout=5) response.raise_for_status() # Raise an exception for bad status codes data = response.json() return { "ip": data.get("ip"), "city": data.get("city"), "region": data.get("region"), "country": data.get("country"), "loc": data.get("loc"), # latitude,longitude "org": data.get("org"), } except requests.exceptions.RequestException as e: logger.error(f"Error fetching IP geolocation for {ip_address}: {e}") return {"ip": ip_address, "error": "Could not fetch IP geolocation data"} # --- Frontend HTML Content (to be served at /) --- # This is a simple, non-location-related UI as requested. html_content = """
Wishing you joy & peace
December 7, 2025
Start your Sunday with positive energy and embrace the beauty of this wonderful day.
Take time to relax, reflect, and enjoy the tranquility that Sundays bring.
Create memorable moments with loved ones and celebrate the gift of togetherness.