Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException, Query
|
| 2 |
+
import duckdb
|
| 3 |
+
from contextlib import asynccontextmanager
|
| 4 |
+
|
| 5 |
+
# Global connection object
|
| 6 |
+
con = duckdb.connect()
|
| 7 |
+
|
| 8 |
+
# Lifespan use karke app start hote hi heavy initialization ek baar karenge
|
| 9 |
+
@asynccontextmanager
|
| 10 |
+
async def lifespan(app: FastAPI):
|
| 11 |
+
print("DuckDB extensions load ho rahi hain aur View ban raha hai...")
|
| 12 |
+
con.execute("INSTALL httpfs; LOAD httpfs;")
|
| 13 |
+
|
| 14 |
+
# Parquet file ka correct URL
|
| 15 |
+
PARQUET_URL = "https://huggingface.co/datasets/tfqdeadlo/Inddatainonefile/resolve/main/users_data.parquet"
|
| 16 |
+
|
| 17 |
+
# Startup par hi Ek baar View bana kar metadata cache kar lete hain
|
| 18 |
+
# Isse har API request par network par load nahi padega
|
| 19 |
+
con.execute(f"CREATE OR REPLACE VIEW users_view AS SELECT * FROM read_parquet('{PARQUET_URL}')")
|
| 20 |
+
print("View taiyar hai! API requests ke liye taiyar hai.")
|
| 21 |
+
yield
|
| 22 |
+
con.close()
|
| 23 |
+
|
| 24 |
+
app = FastAPI(title="Super Fast Search API", lifespan=lifespan)
|
| 25 |
+
|
| 26 |
+
@app.get("/")
|
| 27 |
+
def home():
|
| 28 |
+
return {"message": "Fast API online hai! Use /search?mobile=YOUR_NUMBER"}
|
| 29 |
+
|
| 30 |
+
@app.get("/search")
|
| 31 |
+
async def search_mobile(mobile: str = Query(..., description="Enter mobile number to search")):
|
| 32 |
+
try:
|
| 33 |
+
# Ab hum direct cache kiye hue 'users_view' se data nikalenge
|
| 34 |
+
query = """
|
| 35 |
+
SELECT mobile, name, fname, address, alt, circle, id, email
|
| 36 |
+
FROM users_view
|
| 37 |
+
WHERE mobile = ?
|
| 38 |
+
LIMIT 1
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
result = con.execute(query, [str(mobile)]).fetchall()
|
| 42 |
+
|
| 43 |
+
if not result:
|
| 44 |
+
return {
|
| 45 |
+
"status": "error",
|
| 46 |
+
"message": f"Mobile number {mobile} nahi mila."
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
# Data mapping
|
| 50 |
+
columns = [desc[0] for desc in con.description]
|
| 51 |
+
row_dict = dict(zip(columns, result[0]))
|
| 52 |
+
|
| 53 |
+
return {
|
| 54 |
+
"status": "success",
|
| 55 |
+
"data": row_dict
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
except Exception as e:
|
| 59 |
+
# Internal error ko secure rakhne ke liye mask kiya hai
|
| 60 |
+
raise HTTPException(status_code=500, detail="Query timeout ya process nahi ho payi.")
|