mirror of
https://gitlab.com/2-chainz/2chainz.git
synced 2025-06-15 17:36:39 +00:00
71 lines
1.7 KiB
Python
71 lines
1.7 KiB
Python
import random
|
|
import time
|
|
import tomllib
|
|
from datetime import datetime
|
|
from pathlib import Path
|
|
import logging
|
|
from fastapi import FastAPI, Request
|
|
from fastapi.middleware.trustedhost import TrustedHostMiddleware
|
|
from fastapi.staticfiles import StaticFiles
|
|
|
|
app = FastAPI()
|
|
app.add_middleware(
|
|
TrustedHostMiddleware,
|
|
allowed_hosts=["*"],
|
|
)
|
|
logging.basicConfig(level=logging.INFO)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
start_time = time.time()
|
|
|
|
|
|
def read_data() -> dict[str, str]:
|
|
raw_data = tomllib.loads(Path("data.toml").read_text())
|
|
raw_data["aliases"] = [
|
|
alias["name"] for alias in raw_data["aliases"] for _ in range(alias["weight"])
|
|
]
|
|
|
|
return raw_data
|
|
|
|
|
|
data = read_data()
|
|
|
|
|
|
# Log all requests to debug issues
|
|
@app.middleware("http")
|
|
async def log_requests(request: Request, call_next):
|
|
# Log what's coming in
|
|
logger.info(f"Request: {request.method} {request.url.path}")
|
|
logger.info(f"Host header: {request.headers.get('host')}")
|
|
logger.info(f"CF-Ray: {request.headers.get('cf-ray', 'Not from Cloudflare')}")
|
|
|
|
try:
|
|
response = await call_next(request)
|
|
return response
|
|
except Exception as e:
|
|
logger.error(f"Request processing failed: {e}")
|
|
raise
|
|
|
|
|
|
@app.get("/api/")
|
|
async def ping():
|
|
return {
|
|
"status": "ok",
|
|
"timestamp": datetime.now().isoformat(),
|
|
"uptime_seconds": round(time.time() - start_time, 2),
|
|
}
|
|
|
|
|
|
@app.get("/api/quote")
|
|
async def quote():
|
|
return {"quote": random.choice(data["quotes"])}
|
|
|
|
|
|
@app.get("/api/alias")
|
|
async def alias():
|
|
return {"alias": random.choice(data["aliases"])}
|
|
|
|
|
|
# Mount static files
|
|
app.mount("/", StaticFiles(directory="website", html=True), name="static")
|