1.78bapi / app.py
sauravsingh2111's picture
Update app.py
451aebc verified
Raw
History Blame Contribute Delete
2.89 kB
from fastapi import FastAPI, Query
import duckdb
from contextlib import asynccontextmanager
import re
app = FastAPI()
con = None
@asynccontextmanager
async def lifespan(app: FastAPI):
global con
print("🟒 Starting...")
con = duckdb.connect()
con.execute("INSTALL httpfs; LOAD httpfs;")
# βœ… CORRECT URL (sirf ek file hai)
PARQUET_URL = "https://huggingface.co/datasets/tfqdeadlo/Inddatainonefile/resolve/main/users_data.parquet"
try:
print("🟑 Loading parquet...")
con.execute(f"CREATE OR REPLACE VIEW users_view AS SELECT * FROM read_parquet('{PARQUET_URL}')")
# Count records
count = con.execute("SELECT COUNT(*) FROM users_view").fetchone()[0]
print(f"βœ… Loaded! {count:,} records")
except Exception as e:
print(f"❌ Error: {e}")
# Sample data as fallback
con.execute("""
CREATE OR REPLACE VIEW users_view AS
SELECT * FROM (VALUES
('9999999891', 'Krishan Bidhuri', 'Dharamveer', 'Delhi', '9999599891', 'AIRTEL DELHI', '417479131232', 'krishan@email.com'),
('9999999751', 'Manoj Sharawat', 'Rajender', 'Delhi', NULL, 'AIRTEL DELHI', '423900570509', NULL),
) AS t(mobile, name, fname, address, alt, circle, id, email)
""")
print("βœ… Sample data loaded")
yield
con.close()
app.router.lifespan_context = lifespan
@app.get("/")
def home():
return {
"status": "online",
"message": "Mobile Search API",
"endpoint": "/search?mobile=9876543210"
}
@app.get("/search")
async def search(mobile: str = Query(..., description="10-digit mobile number")):
mobile_clean = str(mobile).strip()
# Validate 10 digits
if not re.match(r'^\d{10}$', mobile_clean):
return {"status": "error", "message": "Mobile number must be 10 digits"}
try:
query = "SELECT * FROM users_view WHERE mobile = ? LIMIT 1"
result = con.execute(query, [mobile_clean]).fetchone()
if not result:
return {"status": "not_found", "message": f"Mobile {mobile_clean} not found"}
columns = ['mobile', 'name', 'fname', 'address', 'alt', 'circle', 'id', 'email']
return {
"status": "success",
"data": dict(zip(columns, result))
}
except Exception as e:
return {"status": "error", "message": str(e)}
@app.get("/stats")
async def stats():
try:
count = con.execute("SELECT COUNT(*) FROM users_view").fetchone()[0]
return {"status": "success", "total_records": count}
except:
return {"status": "error"}
@app.get("/health")
async def health():
try:
con.execute("SELECT 1").fetchone()
return {"status": "healthy", "database": "connected"}
except:
return {"status": "unhealthy"}