コード例 #1
0
def read_one(id_device):
    """
    This function responds to a request for /api/device/{id_user}
    with one matching user from settings

    :param id_user:   Id of user to find
    :return:            user matching id
    """
    # Get the person requested
    query = Device.query.filter(Device.id == id_device).one_or_none()

    # Did we find a person?
    if query is not None:

        # Serialize the data for the response
        schema = DeviceSchema()
        data = schema.dump(query).data
        return data

    # Otherwise, nope, didn't find that person
    else:
        abort(
            404,
            "Device not found for Id: {id_user}".format(id_user=id_user),
        )
コード例 #2
0
def update(device_id, device):
    """
    This function updates an existing device in the devices structure
    Throws an error if a device with the name we want to update to
    already exists in the database.
    :param device_id:   Id of the device to update in the people structure
    :param device:      device to update
    :return:            updated device structure
    """
    update_device = Device.query\
        .filter(Device.device_id == device_id).one_or_none()
    model_num = device.get("model_num")
    manufacturer = device.get("manufacturer")
    existing_device = Device.query\
        .filter(Device.model_num == model_num)\
        .filter(Device.manufacturer == manufacturer)\
        .one_or_none()
    if update_device is None:
        abort(404, f"Device not found for Id: {device_id}")
    elif (existing_device is not None
          and existing_device.device_id != device_id):
        abort(409, f"Device {model_num} {manufacturer} exists already")
    else:
        schema = DeviceSchema()
        new_device = schema.load(device, session=db.session).data
        new_device.device_id = update_device.device_id
        db.session.merge(new_device)
        db.session.commit()
        data = schema.dump(update_device).data
        return data, 200
コード例 #3
0
def read_all():
    """
    This function responds to a request for /api/devices
    with the complete lists of devices
    :return:        json string of list of devices
    """
    devices = Device.query.order_by(Device.manufacturer).all()
    device_schema = DeviceSchema(many=True)
    data = device_schema.dump(devices).data
    return data
コード例 #4
0
def read_one(device_id):
    """
    This function responds to a request for /api/devices/{device_id}
    with one matching device from devices
    :param device_id:   Id of device to find
    :return:            device matching id
    """
    device = Device.query.filter(Device.device_id == device_id).one_or_none()
    if device is not None:
        device_schema = DeviceSchema()
        data = device_schema.dump(device).data
        return data
    else:
        abort(404, f"Device not found for Id: {device_id}")
コード例 #5
0
def read_all():
    """
    This function responds to a request for /api/device
    with the complete lists of users

    :return:        json string of list of devices
    """
    # Create the list of people from our data
    query = Device.query.order_by(Device.id_user).all()

    # Serialize the data for the response
    schema = DeviceSchema(many=True)
    data = schema.dump(query).data
    return data
コード例 #6
0
def create(device):
    """
    This function creates a new device in the devices structure
    based on the passed in device data
    :param device:  device to create in devices structure
    :return:        201 on success, 406 on device exists
    """
    model_num = device.get("model_num")
    manufacturer = device.get("manufacturer")
    existing_device = (Device.query.filter(
        Device.model_num == model_num).filter(
            Device.manufacturer == manufacturer).one_or_none())
    if existing_device is None:
        schema = DeviceSchema()
        new_device = schema.load(device, session=db.session).data
        db.session.add(new_device)
        db.session.commit()
        data = schema.dump(new_device).data
        return data, 201
    else:
        abort(409, f"Device {model_num} {manufacturer} exists already")
コード例 #7
0
def update(id_device, device):
    """
    This function updates an existing user in the structure

    :param id_device:   id of the device to update in the default structure
    :param device:   device to update
    :return:       updated device structure
    """
    # Get the person requested from the db into session
    update_device = Device.query.filter(Device.id == id_device).one_or_none()

    # Did we find a device?
    if update_device is not None:
        update_device.updated = datetime.utcnow()
        update_device.bucket = device['bucket']
        update_device.frame_rate = device['frame_rate']
        update_device.high_threshold = device['high_threshold']
        update_device.id_user = device['id_user']
        update_device.image = device['image']
        update_device.location = device['location']
        update_device.low_threshold = device['low_threshold']
        update_device.name = device['name']
        update_device.notes = device['notes']
        update_device.prediction = device['prediction']
        update_device.refresh_rate = device['refresh_rate']
        update_device.type = device['type']

        db.session.commit()

        schema = DeviceSchema()
        data = schema.dump(update_device).data

        return data, 200

    # Otherwise, nope, didn't find that person
    else:
        abort(
            404,
            "Device not found for Id: {id_device}".format(id_device=id_device),
        )
コード例 #8
0
    def update_db_device_status(self):
        """Override this to change database storage behavior"""
        device_status = DeviceStatus(self.node)
        device_status = DeviceSchema().dump(device_status)

        _logger.debug(device_status)
        db_id = device_status["_id"]

        # Update local DB
        with get_local_db() as db:
            if db_id in db:
                # Update item if it exists
                local_db_doc = db[db_id]

                # Don't do any database updates if the value has not changed
                if local_db_doc["value"] != device_status["value"]:
                    local_db_doc.update(device_status)
                    local_db_doc.save()

            else:
                # Create item if it doesn't exist
                local_db_doc = db.create_document(device_status)

        # Update AWS DB
        aws_table = get_aws_table()
        try:
            # Update item if it exists
            current_doc = aws_table.get(db_id)
            if current_doc.value != device_status["value"]:
                actions = [
                    # name should never change
                    # aws_table.name.set(device_status["name"]),
                    aws_table.value.set(device_status["value"]),
                    aws_table.year.set(device_status["year"]),
                    aws_table.month.set(device_status["month"]),
                    aws_table.day.set(device_status["day"]),
                    aws_table.hour.set(device_status["hour"]),
                    aws_table.minute.set(device_status["minute"]),
                    aws_table.microsecond.set(device_status["microsecond"])
                ]
                current_doc.update(actions=actions)
        except aws_table.DoesNotExist:
            # Create item if it doesn't exist
            new_doc = dict(**device_status)
            new_doc.pop("_id")
            item = aws_table(db_id, **new_doc)
            item.save()

        return local_db_doc
コード例 #9
0
def create(device):
    """
    This function creates a new entry in the device structure
    based on the passed in user id data

    :param user_name:  user name to create in user structure
    :param display_name:  display name for the user
    :param company:  the user company
    :param thumbnail:  string url to the thumbnail image

    :return:        201 on success, 406 on default exists
    """
    # Create a person instance using the schema and the passed in person
    schema = DeviceSchema()
    devices = schema.load(device, session=db.session).data

    # Add the person to the database
    db.session.add(devices)
    db.session.commit()

    # Serialize and return the newly created person in the response
    data = schema.dump(devices).data

    return data, 201
コード例 #10
0
ファイル: views.py プロジェクト: packituz-gttz/mixtli-iot
from flask import abort
from models import Device, db, DeviceSchema, Product, ProductSchema
from sqlalchemy.exc import OperationalError
from connexion import NoContent

device_schema = DeviceSchema()
device_schemas = DeviceSchema(many=True)

product_schema = ProductSchema()
product_schemas = ProductSchema(many=True)


def get_devices():
    """
    :return: List of devices
    """
    try:
        devices_list = Device.query.all()
        result = device_schemas.dump(devices_list)
    except TimeoutError:
        abort(408, "Timeout error, please try again")
    except Exception:
        abort(500)

    return result


def get_device(device_id):
    """
    :param device_id: Unique Id for device
    :return: Device info
コード例 #11
0
ファイル: api.py プロジェクト: eduardoagreda/api_iot
from flask_restful import Resource
from app import app, api, db, auth, cross_origin #, users
from flask import request, jsonify, session
from models import User, UserSchema, Device, DeviceSchema, Sample, SampleSchema, Relay, RelaySchema

#Inicializamos los Schema, para el manejo de datos tipo json
user_schema = UserSchema()
device_schema = DeviceSchema()
sample_schema = SampleSchema()
relay_schema = RelaySchema()

#creamos las vistas basadas en clases para el envío y consulta de listas de datos
class Index(Resource):
    def get(self):
        result = 'Hello, %s!' %auth.username
        message = {'result':result}
        return jsonify(message)

class UserList(Resource):
    #decorators = [auth.login_required]
    def get(self):
        all_user = User.query.all()
        if all_user:
            message = user_schema.dump(all_user, many=True)
        else:
            message = {'result': 'No hay usuarios en la base de datos'}
        return jsonify(message)

    def post(self):
        data = request.get_json()
        name = data['name']