1.78bapi / app.py
tfqdeadlo's picture
Update app.py
50edf95 verified
Raw
History Blame Contribute Delete
2.11 kB
from fastapi import FastAPI, HTTPException, Query
import duckdb
from contextlib import asynccontextmanager
# Global connection object
con = duckdb.connect()
# Lifespan use karke app start hote hi heavy initialization ek baar karenge
@asynccontextmanager
async def lifespan(app: FastAPI):
print("DuckDB extensions load ho rahi hain aur View ban raha hai...")
con.execute("INSTALL httpfs; LOAD httpfs;")
# Parquet file ka correct URL
PARQUET_URL = "https://huggingface.co/datasets/tfqdeadlo/Inddatainonefile/resolve/main/users_data.parquet"
# Startup par hi Ek baar View bana kar metadata cache kar lete hain
# Isse har API request par network par load nahi padega
con.execute(f"CREATE OR REPLACE VIEW users_view AS SELECT * FROM read_parquet('{PARQUET_URL}')")
print("View taiyar hai! API requests ke liye taiyar hai.")
yield
con.close()
app = FastAPI(title="Super Fast Search API", lifespan=lifespan)
@app.get("/")
def home():
return {"message": "Fast API online hai! Use /search?mobile=YOUR_NUMBER"}
@app.get("/search")
async def search_mobile(mobile: str = Query(..., description="Enter mobile number to search")):
try:
# Ab hum direct cache kiye hue 'users_view' se data nikalenge
query = """
SELECT mobile, name, fname, address, alt, circle, id, email
FROM users_view
WHERE mobile = ?
LIMIT 1
"""
result = con.execute(query, [str(mobile)]).fetchall()
if not result:
return {
"status": "error",
"message": f"Mobile number {mobile} nahi mila."
}
# Data mapping
columns = [desc[0] for desc in con.description]
row_dict = dict(zip(columns, result[0]))
return {
"status": "success",
"data": row_dict
}
except Exception as e:
# Internal error ko secure rakhne ke liye mask kiya hai
raise HTTPException(status_code=500, detail="Query timeout ya process nahi ho payi.")