Use SQLAlchemy 404 responses instead of errors

master
esensar 2018-09-19 22:51:57 +02:00
parent b5170a7c64
commit fefa8dbf77
3 changed files with 4 additions and 17 deletions

View File

@ -63,11 +63,7 @@ def get_device(device_id):
:type device_id: int :type device_id: int
:returns: Requested device :returns: Requested device
:rtype: Device :rtype: Device
:raises: ValueError if device does not exist
""" """
if not Device.exists(id=device_id):
raise ValueError("Device with id %s does not exist" % device_id)
return Device.get(id=device_id) return Device.get(id=device_id)
@ -79,23 +75,14 @@ def get_device_type(device_type_id):
:type device_type_id: int :type device_type_id: int
:returns: Requested device type :returns: Requested device type
:rtype: DeviceType :rtype: DeviceType
:raises: ValueError if device type does not exist
""" """
if not DeviceType.exists(id=device_type_id):
raise ValueError("Device type with id %s does not exist" %
device_type_id)
return DeviceType.get(id=device_type_id) return DeviceType.get(id=device_type_id)
def delete_device(device_id): def delete_device(device_id):
""" """
Tries to delete device with given parameters. Does not raise errors Tries to delete device with given parameters. Does not raise errors
""" """
if not Device.exists(id=device_id):
return
Device.get(id=device_id).delete() Device.get(id=device_id).delete()

View File

@ -76,7 +76,7 @@ class Recording(db.Model):
* raw_record (useless) * raw_record (useless)
""" """
return Recording.query.filter_by(**kwargs).first() return Recording.query.filter_by(**kwargs).first_or_404()
def __repr__(self): def __repr__(self):
return '<Recording (value=%s, recorded_at=%s)>' % ( return '<Recording (value=%s, recorded_at=%s)>' % (
@ -163,7 +163,7 @@ class Device(db.Model):
* configuration (useless) * configuration (useless)
""" """
return Device.query.filter_by(**kwargs).first() return Device.query.filter_by(**kwargs).first_or_404()
@staticmethod @staticmethod
def exists(**kwargs): def exists(**kwargs):
@ -271,7 +271,7 @@ class DeviceType(db.Model):
* id * id
* name * name
""" """
return DeviceType.query.filter_by(**kwargs).first() return DeviceType.query.filter_by(**kwargs).first_or_404()
@staticmethod @staticmethod
def exists(**kwargs): def exists(**kwargs):

View File

@ -59,7 +59,7 @@ class MqttClient:
return return
@staticmethod @staticmethod
def get_device_id(topic) -> int: def get_device_id(topic):
device_token, device_id = topic.split("/") device_token, device_id = topic.split("/")
if device_token == "device": if device_token == "device":
return int(device_id) return int(device_id)