abdullah9873 commited on
Commit
7efb19e
·
verified ·
1 Parent(s): 65f4f15

Upload engine.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. engine.py +196 -0
engine.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import uuid
3
+ import json
4
+ from datetime import datetime
5
+ from typing import Dict, Any, List, Optional
6
+ from faker import Faker
7
+ from sqlalchemy.orm import Session
8
+ from database import SessionLocal, MockApiSchema, init_db
9
+
10
+ fake = Faker()
11
+
12
+ class MockApiEngine:
13
+ """
14
+ Engine to dynamically handle CRUD requests and persist fake data
15
+ to a SQL database.
16
+ """
17
+ def __init__(self):
18
+ # Ensure tables exist
19
+ init_db()
20
+
21
+ def _get_api(self, db: Session, api_id: str) -> Optional[MockApiSchema]:
22
+ return db.query(MockApiSchema).filter(MockApiSchema.id == api_id).first()
23
+
24
+ def delete_api_data(self, api_id: str):
25
+ """Clears all data associated with an api_id."""
26
+ with SessionLocal() as db:
27
+ api = self._get_api(db, api_id)
28
+ if api:
29
+ db.delete(api)
30
+ db.commit()
31
+
32
+ def generate_fake_data(self, fields: Dict[str, str], count: int = 5) -> List[Dict[str, Any]]:
33
+ """Generates realistic fake data based on the provided field types and names."""
34
+ data = []
35
+ for i in range(count):
36
+ item = {}
37
+ for field, f_type in fields.items():
38
+ if field == "id":
39
+ item[field] = i + 1 if f_type == "number" else str(uuid.uuid4())
40
+ continue
41
+
42
+ f_type_lower = str(f_type).lower()
43
+ field_lower = str(field).lower()
44
+
45
+ if f_type_lower == "number":
46
+ if any(word in field_lower for word in ["price", "cost", "amount"]):
47
+ item[field] = fake.random_int(min=500, max=50000) / 100.0
48
+ else:
49
+ item[field] = fake.random_int(min=1, max=1000)
50
+ elif f_type_lower == "boolean":
51
+ item[field] = fake.boolean()
52
+ elif f_type_lower == "string":
53
+ if "email" in field_lower:
54
+ item[field] = fake.email()
55
+ elif any(word in field_lower for word in ["user", "name"]):
56
+ item[field] = fake.name()
57
+ elif "phone" in field_lower:
58
+ item[field] = fake.phone_number()
59
+ elif "address" in field_lower:
60
+ item[field] = fake.address()
61
+ elif any(word in field_lower for word in ["date", "time"]):
62
+ item[field] = fake.iso8601()
63
+ elif any(word in field_lower for word in ["url", "image", "avatar"]):
64
+ item[field] = f"https://picsum.photos/seed/{uuid.uuid4().hex[:8]}/400/300"
65
+ elif any(word in field_lower for word in ["price", "cost", "amount"]):
66
+ item[field] = f"${fake.random_int(min=500, max=50000) / 100.0}"
67
+ elif any(word in field_lower for word in ["description", "bio"]):
68
+ item[field] = fake.sentence()
69
+ elif any(word in field_lower for word in ["category", "tag"]):
70
+ item[field] = fake.word().capitalize()
71
+ else:
72
+ item[field] = fake.word()
73
+ else:
74
+ item[field] = fake.word()
75
+ data.append(item)
76
+ return data
77
+
78
+ def load_from_schema(self, api_id: str, schema_dict: Dict[str, Any], user_id: str, expires_at: datetime) -> List[str]:
79
+ """Parses a schema and initializes data in the database."""
80
+ entities = schema_dict.get("entities", [])
81
+ routes = []
82
+
83
+ mock_data = {}
84
+
85
+ for entity in entities:
86
+ name = entity.get("name")
87
+ fields = entity.get("fields", {})
88
+ if name and fields:
89
+ mock_data[name] = self.generate_fake_data(fields)
90
+ base_path = f"/mock/{api_id}/{name}"
91
+ routes.extend([
92
+ f"GET {base_path}",
93
+ f"GET {base_path}/{{id}}",
94
+ f"POST {base_path}",
95
+ f"PUT {base_path}/{{id}}",
96
+ f"DELETE {base_path}/{{id}}"
97
+ ])
98
+
99
+ with SessionLocal() as db:
100
+ new_api = MockApiSchema(
101
+ id=api_id,
102
+ name=schema_dict.get("name", "Generated API"),
103
+ user_id=user_id,
104
+ expires_at=expires_at,
105
+ mock_data=mock_data
106
+ )
107
+ db.merge(new_api)
108
+ db.commit()
109
+
110
+ return routes
111
+
112
+ async def handle_request(self, api_id: str, path: str, method: str, body: Any = None) -> Any:
113
+ """Processes an incoming request against the persisted data."""
114
+ with SessionLocal() as db:
115
+ api = self._get_api(db, api_id)
116
+ if not api:
117
+ return None
118
+
119
+ parts = path.strip("/").split("/")
120
+ entity_name = parts[0]
121
+
122
+ if not entity_name:
123
+ entities = list(api.mock_data.keys())
124
+ return {
125
+ "mock_id": api_id,
126
+ "message": "Specify an entity to access data.",
127
+ "available_entities": entities,
128
+ "example_url": f"/mock/{api_id}/{entities[0]}" if entities else None
129
+ }
130
+
131
+ item_id = parts[1] if len(parts) > 1 else None
132
+ records = api.mock_data.get(entity_name)
133
+
134
+ if records is None:
135
+ return None
136
+
137
+ if method == "GET":
138
+ if item_id:
139
+ for item in records:
140
+ if str(item.get("id")) == str(item_id):
141
+ return item
142
+ return {"error": "Item not found"}
143
+ return records
144
+
145
+ if method == "POST":
146
+ item = body or {}
147
+ if "id" not in item:
148
+ item["id"] = str(uuid.uuid4())
149
+ updated_records = list(records)
150
+ updated_records.append(item)
151
+
152
+ new_data = dict(api.mock_data)
153
+ new_data[entity_name] = updated_records
154
+ api.mock_data = new_data
155
+ db.add(api)
156
+ db.commit()
157
+ return item
158
+
159
+ if method == "PUT" and item_id:
160
+ updated_records = list(records)
161
+ found = False
162
+ for i, item in enumerate(updated_records):
163
+ if str(item.get("id")) == str(item_id):
164
+ updated = body or {}
165
+ updated["id"] = item["id"]
166
+ updated_records[i] = updated
167
+ found = True
168
+ break
169
+
170
+ if found:
171
+ new_data = dict(api.mock_data)
172
+ new_data[entity_name] = updated_records
173
+ api.mock_data = new_data
174
+ db.add(api)
175
+ db.commit()
176
+ return updated
177
+ return {"error": "Item not found"}
178
+
179
+ if method == "DELETE" and item_id:
180
+ updated_records = list(records)
181
+ deleted_data = None
182
+ for i, item in enumerate(updated_records):
183
+ if str(item.get("id")) == str(item_id):
184
+ deleted_data = updated_records.pop(i)
185
+ break
186
+
187
+ if deleted_data:
188
+ new_data = dict(api.mock_data)
189
+ new_data[entity_name] = updated_records
190
+ api.mock_data = new_data
191
+ db.add(api)
192
+ db.commit()
193
+ return {"status": "deleted", "data": deleted_data}
194
+ return {"error": "Item not found"}
195
+
196
+ return {"error": "Method not allowed"}