blob: 9c86309bd97e454a9dbf3e49f904be2d6374eaeb (
plain)
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
|
from fastapi import APIRouter, HTTPException
from sqlalchemy import select
from ..database import SessionLocal
from ..models import SensorDevice, Station
from ..schemas.sensor import PostSensor
from datetime import datetime
router = APIRouter(
prefix='/sensors',
tags=['sensors']
)
@router.get('/')
async def get_sensors():
dc = {'sensors': []}
session = SessionLocal()
stmt = select(SensorDevice)
devices = session.execute(stmt)
for device in devices.scalars():
dev = {
'id': device.id,
'name': device.name,
'installation_date': device.installation_date,
'station_id': device.station_id,
'is_active': device.is_active
}
dc['sensors'].append(dev)
dc['size'] = len(dc['sensors'])
session.close()
return dc
@router.post('/')
async def post_sensor(sensor: PostSensor):
session = SessionLocal()
station = session.get(Station, sensor.station_id)
if not station:
session.close()
raise HTTPException(
status_code=404,
detail=f"Não existe estação com id {sensor.station_id}"
)
if not sensor.installation_date:
installation_date = station.installation_date
else:
installation_date = datetime.fromtimestamp(sensor.installation_date)
session.add(SensorDevice(name=sensor.name, installation_date=installation_date, station_id=sensor.station_id, is_active=True))
session.commit()
session.close()
return {'msg': 'Sensor criado com sucesso.'}
|