Aryan Pachani commited on
Commit
feb7cfb
Β·
verified Β·
1 Parent(s): 22e792a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +149 -29
app.py CHANGED
@@ -1,60 +1,180 @@
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/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.")
 
1
  from fastapi import FastAPI, HTTPException, Query
2
  import duckdb
3
  from contextlib import asynccontextmanager
4
+ from typing import Optional, List
5
 
6
+ # Global connection
7
+ con: Optional[duckdb.DuckDBPyConnection] = None
8
 
 
9
  @asynccontextmanager
10
  async def lifespan(app: FastAPI):
11
+ global con
12
+ try:
13
+ print("πŸ”„ DuckDB initialize ho raha hai...")
14
+ con = duckdb.connect()
15
+ con.execute("INSTALL httpfs; LOAD httpfs;")
16
+
17
+ PARQUET_URL = "https://huggingface.co/datasets/nonamearyan/Inddatainonefile/resolve/main/users_data.parquet"
18
+
19
+ con.execute(f"""
20
+ CREATE OR REPLACE VIEW users_view AS
21
+ SELECT * FROM read_parquet('{PARQUET_URL}')
22
+ """)
23
+
24
+ print("βœ… Server ready!")
25
+
26
+ except Exception as e:
27
+ print(f"❌ Startup error: {e}")
28
+ raise
29
 
 
 
 
 
30
  yield
31
+
32
+ if con:
33
+ con.close()
34
+ print("πŸ”’ Connection closed.")
35
 
36
+ app = FastAPI(
37
+ title="Search API",
38
+ description="Mobile, ID aur Email se search - Saare results dikhayega",
39
+ version="4.0.0",
40
+ lifespan=lifespan
41
+ )
42
 
43
  @app.get("/")
44
  def home():
45
+ return {
46
+ "endpoints": {
47
+ "/search/mobile": "?mobile=9876543210",
48
+ "/search/id": "?id=123456789012",
49
+ "/search/email": "?email=user@example.com"
50
+ }
51
+ }
52
 
53
+
54
+ # ============================================
55
+ # ENDPOINT 1: Mobile Se Search (All Results)
56
+ # ============================================
57
+ @app.get("/search/mobile")
58
+ async def search_by_mobile(
59
+ mobile: str = Query(..., min_length=10, max_length=15)
60
+ ):
61
+ if con is None:
62
+ raise HTTPException(status_code=503, detail="DB not connected")
63
+
64
  try:
 
65
  query = """
66
  SELECT mobile, name, fname, address, alt, circle, id, email
67
  FROM users_view
68
  WHERE mobile = ?
 
69
  """
70
 
71
+ result = con.execute(query, [mobile.strip()]).fetchall()
72
 
73
  if not result:
74
  return {
75
+ "success": False,
76
+ "data": []
77
  }
78
 
79
+ description = con.description
80
+ columns = [desc[0] for desc in description] if description else []
81
+
82
+ results = []
83
+ for row in result:
84
+ results.append(dict(zip(columns, row)))
85
+
86
+ return {
87
+ "success": True,
88
+ "data": results
89
+ }
90
+
91
+ except Exception as e:
92
+ raise HTTPException(status_code=500, detail=str(e))
93
+
94
+
95
+ # ============================================
96
+ # ENDPOINT 2: ID Se Search (All Results)
97
+ # ============================================
98
+ @app.get("/search/id")
99
+ async def search_by_id(
100
+ id: str = Query(...,
101
+ min_length=12,
102
+ max_length=12,
103
+ description="12-digit ID number")
104
+ ):
105
+ if con is None:
106
+ raise HTTPException(status_code=503, detail="DB not connected")
107
+
108
+ if not id.isdigit():
109
+ raise HTTPException(status_code=400, detail="ID sirf numbers mein honi chahiye")
110
+
111
+ try:
112
+ query = """
113
+ SELECT mobile, name, fname, address, alt, circle, id, email
114
+ FROM users_view
115
+ WHERE id = ?
116
+ """
117
+
118
+ result = con.execute(query, [id.strip()]).fetchall()
119
+
120
+ if not result:
121
+ return {
122
+ "success": False,
123
+ "data": []
124
+ }
125
+
126
+ description = con.description
127
+ columns = [desc[0] for desc in description] if description else []
128
+
129
+ results = []
130
+ for row in result:
131
+ results.append(dict(zip(columns, row)))
132
+
133
+ return {
134
+ "success": True,
135
+ "data": results
136
+ }
137
+
138
+ except Exception as e:
139
+ raise HTTPException(status_code=500, detail=str(e))
140
+
141
+
142
+ # ============================================
143
+ # ENDPOINT 3: Email Se Search (All Results)
144
+ # ============================================
145
+ @app.get("/search/email")
146
+ async def search_by_email(
147
+ email: str = Query(..., description="Email ID")
148
+ ):
149
+ if con is None:
150
+ raise HTTPException(status_code=503, detail="DB not connected")
151
+
152
+ try:
153
+ query = """
154
+ SELECT mobile, name, fname, address, alt, circle, id, email
155
+ FROM users_view
156
+ WHERE email = ?
157
+ """
158
+
159
+ result = con.execute(query, [email.strip()]).fetchall()
160
+
161
+ if not result:
162
+ return {
163
+ "success": False,
164
+ "data": []
165
+ }
166
+
167
+ description = con.description
168
+ columns = [desc[0] for desc in description] if description else []
169
+
170
+ results = []
171
+ for row in result:
172
+ results.append(dict(zip(columns, row)))
173
 
174
  return {
175
+ "success": True,
176
+ "data": results
177
  }
178
 
179
  except Exception as e:
180
+ raise HTTPException(status_code=500, detail=str(e))