-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
324 lines (246 loc) · 11.7 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
import logging
import os
from aiohttp import web
from aiohttp.web import Response
from dotenv import load_dotenv
from peewee import *
from peewee import CharField, ForeignKeyField, Model, PostgresqlDatabase
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
load_dotenv()
db = PostgresqlDatabase(
os.getenv('DB_NAME'),
user=os.getenv('DB_USER'),
password=os.getenv('DB_PASSWORD'),
host=os.getenv('DB_HOST'),
port=int(os.getenv('DB_PORT'))
)
# MODELS
class ApiUser(Model):
name = CharField()
email = CharField(unique=True)
password = CharField()
class Meta:
database = db
table_name: str = 'api_user'
class Location(Model):
name = CharField()
class Meta:
database = db
table_name: str = 'location'
class Device(Model):
name = CharField()
device_type = CharField()
login = CharField()
password = CharField()
location = ForeignKeyField(Location, backref='devices')
api_user = ForeignKeyField(ApiUser, backref='devices')
class Meta:
database = db
table_name: str = 'device'
@staticmethod
def current_device_info(device: dict[str, int | str]) -> Response[dict[str, int | str]]:
return web.json_response({
'id': device.id,
'name': device.name,
'device_type': device.device_type,
'login': device.login,
'password': device.password,
'location_id': device.location.id,
'api_user_id': device.api_user.id
})
app = web.Application()
# TEST
async def hello(request) -> Response[str]:
return web.Response(text='Server is running!')
# POST (CREATE)
async def post_device(request) -> Response[dict[str, int | str]]:
data: dict[str, int | str] = await request.json()
logger.info('Received data to create device: %s', data)
try:
if not all(key in data for key in ['name', 'device_type', 'login', 'password', 'location_id', 'api_user_id']):
raise ValueError('Missing required fields!')
if not Location.select().where(Location.id == data['location_id']).exists():
raise ValueError('Invalid location_id!')
if not ApiUser.select().where(ApiUser.id == data['api_user_id']).exists():
raise ValueError('Invalid api_user_id')
device: dict[str, int | str] = Device.create(
name=data['name'],
device_type=data['device_type'],
login=data['login'],
password=data['password'],
location=data['location_id'],
api_user=data['api_user_id']
)
logger.info('Device created successfully: %s', device.id)
return Device.current_device_info(device)
except ValueError as e:
logger.error('Error creating device: %s', str(e))
return web.json_response({'error': str(e)}, status=400)
except Exception as e:
logger.error('Failed to create device: %s', str(e))
return web.json_response({'error': 'Failed to create device: {}!'.format(str(e))}, status=500)
# GET ALL (READ)
async def get_all_devices(request) -> Response[dict[str, int | str]]:
logger.info('Retrieving all devices')
try:
devices = Device.select()
devices_list: list[dict[str, int | str]] = [
{
'id': device.id,
'name': device.name,
'device_type': device.device_type,
'login': device.login,
'password': device.password,
'location_id': device.location.id,
'api_user_id': device.api_user.id
} for device in devices
]
logger.info('Retrieved %d devices', len(devices_list))
return web.json_response(devices_list)
except Exception as e:
logger.error('Failed to retrieve devices: %s', str(e))
return web.json_response({'error': 'Failed to retrieve devices!'}, status=500)
# GET by ID (READ)
async def get_device_by_id(request) -> Response[dict[str, int | str]]:
device_id: int = request.match_info.get('id')
logger.info('Retrieving device by id: %s', device_id)
try:
device: int = Device.get(Device.id == device_id)
logger.info('Device retrieved: %s', device.id)
return Device.current_device_info(device)
except Device.DoesNotExist:
logger.warning('Device not found: %s', device_id)
return web.json_response({'error': 'Device not found!'}, status=404)
# PUT by ID (major-UPDATE)
async def put_device_by_id(request) -> Response[dict[str, int | str]]:
device_id: int = request.match_info.get('id')
data: dict[str, int | str] = await request.json()
logger.info('Updating device %s with data: %s', device_id, data)
try:
if not all(key in data for key in ['name', 'device_type', 'login', 'password', 'location_id', 'api_user_id']):
raise ValueError('Missing required fields!')
if not Location.select().where(Location.id == data['location_id']).exists():
raise ValueError('Invalid location_id!')
if not ApiUser.select().where(ApiUser.id == data['api_user_id']).exists():
raise ValueError('Invalid api_user_id!')
device_query: dict[str, int | str] = Device.update(
name=data['name'],
device_type=data['device_type'],
login=data['login'],
password=data['password'],
location=data['location_id'],
api_user=data['api_user_id']
).where(Device.id == device_id)
updated: dict[str, int | str] = device_query.execute()
if updated:
updated_device: int = Device.get(Device.id == device_id)
logger.info('Device updated successfully: %s', device_id)
return Device.current_device_info(updated_device)
else:
logger.warning('Device not found for update: %s', device_id)
return web.json_response({'error': 'Device not found!'}, status=404)
except ValueError as e:
logger.error('Error updating device: %s', str(e))
return web.json_response({'error': str(e)}, status=400)
except Exception as e:
logger.error('Failed to update device: %s', str(e))
return web.json_response({'error': 'Failed to update device!'}, status=500)
# PATCH by ID (minor-UPDATE)
async def patch_device_by_id(request) -> Response[dict[str, int | str]]:
device_id: int = request.match_info.get('id')
data: dict[str, int | str] = await request.json()
logger.info('Patching device %s with data: %s', device_id, data)
try:
updates: dict = {}
if 'name' in data:
updates['name'] = data['name']
if 'device_type' in data:
updates['device_type'] = data['device_type']
if 'login' in data:
updates['login'] = data['login']
if 'password' in data:
updates['password'] = data['password']
if 'location_id' in data:
if not Location.select().where(Location.id == data['location_id']).exists():
raise ValueError('Invalid location_id!')
updates['location'] = data['location_id']
if 'api_user_id' in data:
if not ApiUser.select().where(ApiUser.id == data['api_user_id']).exists():
raise ValueError('Invalid api_user_id')
updates['api_user'] = data['api_user_id']
if not updates:
logger.warning('No fields to update for device: %s', device_id)
return web.json_response({'error': 'No fields to update!'}, status=400)
query: dict[str, int | str] = Device.update(**updates).where(Device.id == device_id)
updated = query.execute()
if updated:
updated_device: dict[str, int | str] = Device.get(Device.id == device_id)
logger.info('Device patched successfully: %s', device_id)
return Device.current_device_info(updated_device)
else:
logger.warning('Device not found for patching: %s', device_id)
return web.json_response({'error': 'Device not found!'}, status=404)
except ValueError as e:
logger.error('Error patching device: %s', str(e))
return web.json_response({'error': str(e)}, status=400)
except Exception as e:
logger.error('Failed to patch device: %s', str(e))
return web.json_response({'error': 'Failed to patch device!'}, status=500)
# DELETE by ID
async def delete_device_by_id(request) -> Response[dict[str, int | str]]:
device_id: int = request.match_info.get('id')
logger.info('Deleting device by id: %s', device_id)
try:
query: dict[str, int | str] = Device.delete().where(Device.id == device_id)
deleted: dict[str, int | str] = query.execute()
if deleted:
logger.info('Device deleted successfully: %s', device_id)
return web.json_response({'message': f'Device with id {device_id} was successfully deleted!'})
else:
logger.warning('Device not found for deletion: %s', device_id)
return web.json_response({'error': 'Device not found!'}, status=404)
except Exception as e:
logger.error('Failed to delete device: %s', str(e))
return web.json_response({'error': 'Failed to delete device: {}!'.format(str(e))}, status=500)
# ROUTERS
app.router.add_get('/', hello)
app.router.add_post('/devices/', post_device)
app.router.add_get('/devices/', get_all_devices)
app.router.add_get('/devices/{id}/', get_device_by_id)
app.router.add_put('/devices/{id}/', put_device_by_id)
app.router.add_patch('/devices/{id}/', patch_device_by_id)
app.router.add_delete('/devices/{id}/', delete_device_by_id)
# DB-SETUP
def db_setup() -> None:
api_user1 = api_user2 = None
location1 = location2 = None
with db.connection_context():
logger.info("Checking if tables exist...")
if not ApiUser.table_exists():
logger.info("ApiUser table does not exist, creating...")
db.create_tables([ApiUser])
api_user1, created = ApiUser.get_or_create(name='User1', email='[email protected]', password='password1')
api_user2, created = ApiUser.get_or_create(name='User2', email='[email protected]', password='password2')
if not Location.table_exists():
logger.info("Location table does not exist, creating...")
db.create_tables([Location])
location1, created = Location.get_or_create(name='Location1')
location2, created = Location.get_or_create(name='Location2')
if not Device.table_exists():
logger.info("Device table does not exist, creating...")
db.create_tables([Device])
logger.info("Tables checked/created successfully!")
if api_user1 and api_user2:
logger.info("Initial data created successfully: Users and Locations.")
logger.info(f"Created ApiUser: {api_user1.id}, {api_user1.name}")
logger.info(f"Created ApiUser: {api_user2.id}, {api_user2.name}")
if location1 and location2:
logger.info(f"Created Location: {location1.id}, {location1.name}")
logger.info(f"Created Location: {location2.id}, {location2.name}")
# RUN - If you want strat local develop - choice everywhere *Local*, if wont start project in Docker - choice *Docker*
if __name__ == '__main__':
db.connect()
db_setup()
web.run_app(app, host="0.0.0.0", port=8080) # Docker
# web.run_app(app, host='127.0.0.1', port=8080) # Local