Aryan Pachani commited on
Commit
f869bfc
·
verified ·
1 Parent(s): feb7cfb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -83
app.py CHANGED
@@ -1,180 +1,144 @@
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))
 
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
+ 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")):
 
 
 
 
 
115
  try:
116
  query = """
117
  SELECT mobile, name, fname, address, alt, circle, id, email
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.")