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 = """ Seasons Greeting
✨ Season's Greetings ✨

Happy Beautiful Sunday!

Wishing you joy & peace

December 7, 2025

☀️

Bright Beginnings

Start your Sunday with positive energy and embrace the beauty of this wonderful day.

💙

Peaceful Moments

Take time to relax, reflect, and enjoy the tranquility that Sundays bring.

🌟

Joyful Celebrations

Create memorable moments with loved ones and celebrate the gift of togetherness.

May Your Day Be Filled With Wonder

On this beautiful Sunday, may you find peace in every moment, joy in every smile, and love in every heartbeat. Let the warmth of this season remind you of all the blessings that surround you.

Share The Joy
""" # --- FastAPI Endpoints --- @app.get("/", response_class=HTMLResponse) async def read_root(request: Request): """ Serves the HTML frontend and performs IP geolocation, logging the result. """ client_ip = get_client_ip(request) # 1. Perform IP Geolocation ip_geo_data = get_ip_geolocation(client_ip) # 2. Log IP Geolocation data to the console logger.info("--- IP Geolocation Data (Backend Only) ---") logger.info(f"Client IP: {client_ip}") for key, value in ip_geo_data.items(): logger.info(f"{key.capitalize()}: {value}") logger.info("-----------------------------------------") # Return the HTML content to the client return HTMLResponse(content=html_content, status_code=200)