Aryan Pachani commited on
Commit
dddde97
·
verified ·
1 Parent(s): 13593b2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -121
app.py CHANGED
@@ -1,7 +1,6 @@
1
  from fastapi import FastAPI, HTTPException, Query
2
  import duckdb
3
  from contextlib import asynccontextmanager
4
- import sys
5
 
6
  # Global connection object
7
  con = duckdb.connect()
@@ -9,142 +8,53 @@ con = duckdb.connect()
9
  # Lifespan use karke app start hote hi heavy initialization ek baar karenge
10
  @asynccontextmanager
11
  async def lifespan(app: FastAPI):
12
- print("🔄 DuckDB extensions load ho rahi hain aur View ban raha hai...")
13
- try:
14
- con.execute("INSTALL httpfs; LOAD httpfs;")
15
-
16
- # Parquet file ka correct URL
17
- PARQUET_URL = "https://huggingface.co/datasets/nonamearyan/Inddatainonefile/resolve/main/users_data.parquet"
18
-
19
- # Startup par hi Ek baar View bana kar metadata cache kar lete hain
20
- con.execute(f"CREATE OR REPLACE VIEW users_view AS SELECT * FROM read_parquet('{PARQUET_URL}')")
21
- print("✅ View taiyar hai! API requests ke liye taiyar hai.")
22
-
23
- except Exception as e:
24
- print(f"❌ Startup error: {e}")
25
- print("⚠️ Server continue karega, lekin data nahi milega")
26
- # Fail silent, but server continue
27
  yield
28
  con.close()
29
 
30
- app = FastAPI(
31
- title="Super Fast Search API",
32
- description="3 endpoints - Mobile, ID, Email se search karein",
33
- version="2.0.0",
34
- lifespan=lifespan
35
- )
36
 
37
  @app.get("/")
38
  def home():
39
- return {
40
- "status": "online",
41
- "message": "🚀 API ready hai!",
42
- "endpoints": {
43
- "/search/mobile": {"method": "GET", "params": "mobile=YOUR_NUMBER"},
44
- "/search/id": {"method": "GET", "params": "id=YOUR_ID"},
45
- "/search/email": {"method": "GET", "params": "email=YOUR_EMAIL"}
46
- }
47
- }
48
 
49
- # ============================================
50
- # Helper Function - Response Build
51
- # ============================================
52
- def build_response(result, query_field, query_value):
53
- """Response build karne ka helper function"""
54
- if not result:
55
- return {
56
- "status": "error",
57
- "message": f"{query_field} '{query_value}' nahi mila.",
58
- "data": []
59
- }
60
-
61
- columns = [desc[0] for desc in con.description] if con.description else []
62
- results = []
63
- for row in result:
64
- results.append(dict(zip(columns, row)))
65
-
66
- return {
67
- "status": "success",
68
- "message": f"{len(results)} result(s) found",
69
- "data": results
70
- }
71
-
72
- # ============================================
73
- # ENDPOINT 1: Mobile Se Search
74
- # ============================================
75
- @app.get("/search/mobile")
76
- async def search_mobile(mobile: str = Query(..., min_length=10, max_length=15, description="Enter mobile number to search")):
77
  try:
 
78
  query = """
79
  SELECT mobile, name, fname, address, alt, circle, id, email
80
  FROM users_view
81
  WHERE mobile = ?
 
82
  """
83
- result = con.execute(query, [str(mobile.strip())]).fetchall()
84
- return build_response(result, "Mobile number", mobile)
85
 
86
- except Exception as e:
87
- print(f"❌ Mobile search error: {e}")
88
- return {
89
- "status": "error",
90
- "message": "Search failed. Please try again.",
91
- "data": []
92
- }
93
-
94
-
95
- # ============================================
96
- # ENDPOINT 2: ID Se Search (Integer)
97
- # ============================================
98
- @app.get("/search/id")
99
- async def search_id(id: int = Query(..., description="Enter ID to search (numeric)")):
100
- try:
101
- query = """
102
- SELECT mobile, name, fname, address, alt, circle, id, email
103
- FROM users_view
104
- WHERE id = ?
105
- """
106
- result = con.execute(query, [id]).fetchall()
107
- return build_response(result, "ID", str(id))
108
 
109
- except Exception as e:
110
- print(f"❌ ID search error: {e}")
111
  return {
112
- "status": "error",
113
- "message": "Search failed. Please try again.",
114
- "data": []
115
  }
116
-
117
-
118
- # ============================================
119
- # ENDPOINT 3: Email Se Search
120
- # ============================================
121
- @app.get("/search/email")
122
- async def search_email(email: str = Query(..., description="Enter email to search")):
123
- try:
124
- query = """
125
- SELECT mobile, name, fname, address, alt, circle, id, email
126
- FROM users_view
127
- WHERE email = ?
128
- """
129
- result = con.execute(query, [str(email.strip())]).fetchall()
130
- return build_response(result, "Email", email)
131
 
132
  except Exception as e:
133
- print(f"❌ Email search error: {e}")
134
- return {
135
- "status": "error",
136
- "message": "Search failed. Please try again.",
137
- "data": []
138
- }
139
-
140
-
141
- # ============================================
142
- # Health Check Endpoint
143
- # ============================================
144
- @app.get("/health")
145
- async def health_check():
146
- try:
147
- con.execute("SELECT 1").fetchone()
148
- return {"status": "healthy", "message": "Database connected"}
149
- except:
150
- return {"status": "unhealthy", "message": "Database not connected"}
 
1
  from fastapi import FastAPI, HTTPException, Query
2
  import duckdb
3
  from contextlib import asynccontextmanager
 
4
 
5
  # Global connection object
6
  con = duckdb.connect()
 
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/nonamearyan/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.")