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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -82
app.py CHANGED
@@ -1,6 +1,7 @@
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,107 +9,114 @@ 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
- con.execute(f"CREATE OR REPLACE VIEW users_view AS SELECT * FROM read_parquet('{PARQUET_URL}')")
19
- print("View taiyar hai! API requests ke liye taiyar hai.")
 
 
 
 
 
 
20
  yield
21
  con.close()
22
 
23
- app = FastAPI(title="Super Fast Search API", lifespan=lifespan)
 
 
 
 
 
24
 
25
  @app.get("/")
26
  def home():
27
  return {
28
- "message": "Fast API online hai!",
 
29
  "endpoints": {
30
- "/search/mobile": "?mobile=YOUR_NUMBER",
31
- "/search/id": "?id=YOUR_ID",
32
- "/search/email": "?email=YOUR_EMAIL"
33
  }
34
  }
35
 
36
  # ============================================
37
- # ENDPOINT 1: Mobile Se Search (Saare Results)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  # ============================================
39
  @app.get("/search/mobile")
40
- async def search_mobile(mobile: str = Query(..., description="Enter mobile number to search")):
41
  try:
42
  query = """
43
  SELECT mobile, name, fname, address, alt, circle, id, email
44
  FROM users_view
45
  WHERE mobile = ?
46
  """
47
- # LIMIT 1 HATAYA - Saare results
48
-
49
- result = con.execute(query, [str(mobile)]).fetchall()
50
-
51
- if not result:
52
- return {
53
- "status": "error",
54
- "message": f"Mobile number {mobile} nahi mila."
55
- }
56
-
57
- columns = [desc[0] for desc in con.description]
58
-
59
- # Saare results ko list mein convert karo
60
- results = []
61
- for row in result:
62
- results.append(dict(zip(columns, row)))
63
 
 
 
64
  return {
65
- "status": "success",
66
- "data": results
 
67
  }
68
-
69
- except Exception as e:
70
- raise HTTPException(status_code=500, detail="Query timeout ya process nahi ho payi.")
71
 
72
 
73
  # ============================================
74
- # ENDPOINT 2: ID Se Search (Saare Results)
75
  # ============================================
76
  @app.get("/search/id")
77
- async def search_id(id: str = Query(..., description="Enter ID to search")):
78
  try:
79
  query = """
80
  SELECT mobile, name, fname, address, alt, circle, id, email
81
  FROM users_view
82
  WHERE id = ?
83
  """
84
- # LIMIT 1 HATAYA - Saare results
85
-
86
- result = con.execute(query, [str(id)]).fetchall()
87
-
88
- if not result:
89
- return {
90
- "status": "error",
91
- "message": f"ID {id} nahi mila."
92
- }
93
-
94
- columns = [desc[0] for desc in con.description]
95
-
96
- # Saare results ko list mein convert karo
97
- results = []
98
- for row in result:
99
- results.append(dict(zip(columns, row)))
100
 
 
 
101
  return {
102
- "status": "success",
103
- "data": results
 
104
  }
105
-
106
- except Exception as e:
107
- raise HTTPException(status_code=500, detail="Query timeout ya process nahi ho payi.")
108
 
109
 
110
  # ============================================
111
- # ENDPOINT 3: Email Se Search (Saare Results)
112
  # ============================================
113
  @app.get("/search/email")
114
  async def search_email(email: str = Query(..., description="Enter email to search")):
@@ -118,27 +126,25 @@ async def search_email(email: str = Query(..., description="Enter email to searc
118
  FROM users_view
119
  WHERE email = ?
120
  """
121
- # LIMIT 1 HATAYA - Saare results
122
-
123
- result = con.execute(query, [str(email)]).fetchall()
124
-
125
- if not result:
126
- return {
127
- "status": "error",
128
- "message": f"Email {email} nahi mila."
129
- }
130
-
131
- columns = [desc[0] for desc in con.description]
132
-
133
- # Saare results ko list mein convert karo
134
- results = []
135
- for row in result:
136
- results.append(dict(zip(columns, row)))
137
 
 
 
138
  return {
139
- "status": "success",
140
- "data": results
 
141
  }
142
-
143
- except Exception as e:
144
- raise HTTPException(status_code=500, detail="Query timeout ya process nahi ho payi.")
 
 
 
 
 
 
 
 
 
 
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
  # 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")):
 
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"}