예제 #1
0
    def post(self, name):
        # if next(filter(lambda x: x["name"] == name, items), None) is not None:
        if ItemModel.find_by_name(name):
            return (
                {
                    "message": f"An item with name {name} already exists."
                },
                400,
            )  # 400: request problem

        data = Item.parser.parse_args()

        item = ItemModel(name, **data)

        try:
            item.save_to_db()
        except:
            return (
                {
                    "message": "An error occured inserting the item."
                },
                500,
            )  # 500: server problem

        return item.json(), 201
예제 #2
0
    def post(self, name):

        data = Item.parser.parse_args()
        returned_item = ItemModel.find_by_name(name, data['store_id'])
        if returned_item:
            return ({"message": "Item already exists"})
        item = ItemModel(name, data['price'], data['store_id'])
        item.save_to_db()
        return (item.json())
예제 #3
0
    def put(self, name):

        data = Item.parser.parse_args()
        item = ItemModel.find_by_name(name, data['store_id'])
        if item is None:
            item = ItemModel(name, data['price'], data['store_id'])
        else:
            item.price = data['price']
        item.save_to_db()

        return (item.json())
예제 #4
0
    def put(self, name):
        data = Item.parser.parse_args()

        item = ItemModel.findItemByName(name)

        if item is None:
            # item=ItemModel(name,data['price'],data['store_id'])
            '''way2'''
            item = ItemModel(name, **data)
        else:
            item.price = data['price']

        item.save_to_db()

        return item.json()
예제 #5
0
    def put(self):
        name = request.args.get('name') 
        data = Item.parser.parse_args()

        item = ItemModel.find_by_name(name)

        if item:
            item.name = data['name']
            item.price = data['price']
        else:
            item = ItemModel(**data)

        item.save_to_db()

        return item.json()
예제 #6
0
    def post(self):
        if 'name' in request.form.keys():
            name = request.form['name']
            comment = request.form['comment']
        else:
            request_data = json.loads(request.data)
            name = request_data['name']
            comment = request_data['comment']

        errors = validate(item_name=name, item_comment=comment)

        if len(errors) > 0:
            return {"errors": [error.to_json() for error in errors]}, 422
        item = ItemModel(name, comment)
        item.save_to_db()
        return item.to_json(), 201
예제 #7
0
    def post(self, name):
        if ItemModel.find_by_name(name):
            return {
                'message':
                "An item with name '{}' already exists.".format(name)
            }

        data = Item.parser.parse_args()

        item = ItemModel(name, data['price'], data['store_id'])

        try:
            item.save_to_db()
        except:
            return {"message": "An error occurred inserting the item."}, 500

        return item.json(), 201
예제 #8
0
    def post(self, name):
        if ItemModel.find_by_name(name):
            return {
                'message': 'An item with name {} already exists'.format(name)
            }, 400
        data = Item.parser.parse_args()

        item = ItemModel(name, **data)

        try:
            item.save_to_db()
        except:
            return {
                "message": "An error occurred inserting the item"
            }, 500  # internal server error

        return item.json(), 201
예제 #9
0
    def post(self):
        claims = get_jwt()

        if not claims['admin']:
            return {'message': 'You need admin privileges'}, 401

        data = Item.parser.parse_args()
        if ItemModel.find_by_name(data['name']):
            return {'message': "An item with name '{}' already exists.".format(name)}, 400


        item = ItemModel(**data)

        try:
            item.save_to_db()
        except:
            return {"message": "An error occurred inserting the item."}, 500

        return item.json(), 201
예제 #10
0
    def post(self, name):
        if next(filter(lambda x: x['name'] == name, items), None) is not None:
            return {
                'message':
                "An item with name '{}' already exists.".format(name)
            }

        data = Item.parser.parse_args()

        item = ItemModel(name, data['price'])

        try:
            item.insert()
            #items.append(item)
        except:
            return {'messege': "something wrong probably item already exist"}

        #sql postres try
        return {'messege': "item insert into the data base"}
예제 #11
0
    def post(self, name):
        if ItemModel.findItemByName(name):
            return {
                "message":
                "an item with name {} already exists in the itemList.".format(
                    name)
            }

        data = Item.parser.parse_args()

        # item=ItemModel(name,data['price'],data['store_id'])
        '''way2'''
        item = ItemModel(name, **data)
        # print(item.name)
        try:
            # print(item.name)
            item.save_to_db()
        except:
            return {"message": "An error occured inserting the item"}, 500

        return item.json(), 201
예제 #12
0
    def put(self, name):
        # data = request.get_json()
        data = Item.parser.parse_args()
        # item = next(filter(lambda x: x["name"] != name, items), None)
        item = ItemModel.find_by_name(name)
        # updated_item = ItemModel(name, data["price"])
        if item is None:
            item = ItemModel(name, **data)
            # try:
            #     updated_item.insert()
            # except:
            #     return {"message": "An error occured inserting the item."}, 500
        else:
            item.price = data['price']
            item.store = data['store']
            # try:
            #     updated_item.update()
            # except:
            #     return {"message": "An error occured inserting the item."}, 500

        item.save_to_db()
        return item.json()
예제 #13
0
def seed():
    print('Seeding...')
    db.init_app(app)
    if not ItemModel.find_by_id(1):
        items = []

        # START CREATING ITEMS
        print('Creating items...')
        items.append(ItemModel('Heating', 'comment'))
        items.append(
            UsageModel(1, 1, UsageTypeEnum.KILOWATT, 5,
                       '127.0.0.1:5000/item/1', 'PERCENTAGE', 0, 1))

        items.append(ItemModel('staande_lamp_1', 'staande lamp = beste lamp'))
        items.append(
            UsageModel(2, 2, UsageTypeEnum.KILOWATT, 1,
                       '127.0.0.1:5000/item/5', 'TOGGLE', 0, 1))

        items.append(ItemModel('staande_lamp_2', 'staande lamp = beste lamp'))
        items.append(
            UsageModel(3, 3, UsageTypeEnum.KILOWATT, 1,
                       '127.0.0.1:5000/item/3', 'TOGGLE', 0, 1))

        items.append(
            ItemModel('slaapkamer_verlichting',
                      'verlichting in de slaapkamer'))
        items.append(
            UsageModel(4, 4, UsageTypeEnum.KILOWATT, 1,
                       '127.0.0.1:5000/item/4', 'TOGGLE', 0, 1))

        items.append(ItemModel('lamp_nachtkastje', 'lamp op nachtkastje'))
        items.append(
            UsageModel(5, 5, UsageTypeEnum.KILOWATT, 1,
                       '127.0.0.1:5000/item/5', 'TOGGLE', 0, 1))

        items.append(ItemModel('toilet', 'toilet in badkamer'))
        items.append(
            UsageModel(6, 6, UsageTypeEnum.WATER_PER_USAGE, 9,
                       '127.0.0.1:5000/item/6', 'TOGGLE', 0, 1))

        items.append(ItemModel('douche', 'douche'))
        items.append(
            UsageModel(7, 7, UsageTypeEnum.WATER_PER_HOUR, 9,
                       '127.0.0.1:5000/item/7', 'TOGGLE', 0, 1))

        items.append(ItemModel('vaatwasser', ''))
        items.append(
            UsageModel(8, 8, UsageTypeEnum.WATER_PER_USAGE, 10,
                       '127.0.0.1:5000/item/8', 'TOGGLE', 0, 1))

        items.append(ItemModel('wasmachine', ''))
        items.append(
            UsageModel(9, 9, UsageTypeEnum.WATER_PER_USAGE, 13,
                       '127.0.0.1:5000/item/9', 'TOGGLE', 0, 1))

        items.append(ItemModel('droger', ''))
        items.append(
            UsageModel(10, 10, UsageTypeEnum.KILOWATT, 9,
                       '127.0.0.1:5000/item/10', 'TOGGLE', 0, 1))

        items.append(ItemModel('badkamer verlichting', ''))
        items.append(
            UsageModel(11, 11, UsageTypeEnum.KILOWATT, 1,
                       '127.0.0.1:5000/item/11', 'TOGGLE', 0, 1))

        # START CREATING GROUPS
        print('Creating groups...')
        items.append(GroupModel('Huiskamer', True))
        items.append(GroupModel('Slaapkamer', True))
        items.append(GroupModel('Badkamer', True))
        items.append(GroupModel('Verlichting', False))

        # START ADDING ITEMS TO GROUPS
        print('Assigning items to groups...')
        items.append(ItemGroupModel(2, 1))
        items.append(ItemGroupModel(3, 1))
        items.append(ItemGroupModel(8, 1))
        items.append(ItemGroupModel(4, 2))
        items.append(ItemGroupModel(5, 2))
        items.append(ItemGroupModel(6, 3))
        items.append(ItemGroupModel(7, 3))
        items.append(ItemGroupModel(9, 3))
        items.append(ItemGroupModel(10, 3))
        items.append(ItemGroupModel(11, 3))
        items.append(ItemGroupModel(2, 4))
        items.append(ItemGroupModel(3, 4))
        items.append(ItemGroupModel(4, 4))
        items.append(ItemGroupModel(5, 4))
        items.append(ItemGroupModel(11, 4))

        # START CREATING GRAPHS
        items.append(
            GraphModel('AVERAGE_TEMPERATURE', DataTypeEnum.TEMPERATURE))
        items.append(
            GraphModel('AVERAGE_WATER_USAGE', DataTypeEnum.WATER_USAGE))

        # START CREATING EVENTS
        print('Creating events')
        till_date = datetime.now().timestamp()
        about_one_month = (60 * 60 * 24 * 30)
        from_date = till_date - about_one_month

        # make sure the timestamps are never in the future
        limit_time = lambda timestamp: timestamp if timestamp < till_date else till_date

        keep_going = True
        while keep_going:
            for i in range(0, random.randint(1, 4)):
                toilet_break_timestamp = (
                    datetime.fromtimestamp(from_date) +
                    timedelta(hours=random.randint(5, 12),
                              minutes=random.randint(0, 60),
                              seconds=random.randint(0, 60))).timestamp()
                items.append(
                    EventModel(6, 'True', limit_time(toilet_break_timestamp),
                               2))

            for i in range(0, 4):
                daily_shower_start_timestamp = (
                    datetime.fromtimestamp(from_date) +
                    timedelta(hours=random.randint(5, 12),
                              minutes=random.randint(0, 60),
                              seconds=random.randint(0, 60))).timestamp()
                items.append(
                    EventModel(7, 'True',
                               limit_time(daily_shower_start_timestamp), 2))
                daily_shower_end_timestamp = (
                    datetime.fromtimestamp(daily_shower_start_timestamp) +
                    timedelta(minutes=random.randint(5, 15),
                              seconds=random.randint(0, 60))).timestamp()
                items.append(
                    EventModel(7, 'False',
                               limit_time(daily_shower_end_timestamp), 2))
            for i in range(0, 24):
                if not keep_going:
                    break

                for y in range(0, 10):
                    if from_date > till_date:
                        keep_going = False
                        break
                    temp = 0
                    if i in [1, 2, 3, 4, 5, 15]:
                        temp = 15
                    elif i in [0, 14]:
                        temp = 16
                    elif i in [6, 12, 24, 13]:
                        temp = 18
                    elif i in [7, 8, 9, 17, 18, 19, 20, 21, 22]:
                        temp = 21
                    elif i in [10, 23]:
                        temp = 20
                    elif i in [11, 16]:
                        temp = 19

                    items.append(
                        EventModel(1, temp * random.uniform(0.9, 1.1),
                                   from_date, 1))
                    from_date += 6 * 60

        print('inserting data into db, this may take a while...')
        current = 1
        total = len(items)

        # one last flush of the toilet at the current timestamp
        items.append(EventModel(6, 'True', till_date, 2))
        for item in items:
            print('{} out of {}'.format(current, total))
            item.save_to_db()
            current += 1
예제 #14
0
def seed_test_data():
    # @todo this doesn't work yet
    print('Seeding...')
    if not ItemModel.find_by_id(1):
        items = []

        # START CREATING ITEMS
        print('Creating items...')
        items.append(ItemModel('Heating', 'comment'))
        items.append(UsageModel(1, UsageTypeEnum.KILOWATT, 5, '127.0.0.1:5000/item/1', UnitEnum(UnitEnum.TOGGLE), 0, 1))

        items.append(ItemModel('staande_lamp_1', 'staande lamp = beste lamp'))
        items.append(UsageModel(2, UsageTypeEnum.KILOWATT, 1, '127.0.0.1:5000/item/2', UnitEnum(UnitEnum.TOGGLE), 0, 1))

        items.append(ItemModel('staande_lamp_2', 'staande lamp = beste lamp'))
        items.append(UsageModel(3, UsageTypeEnum.KILOWATT, 1, '127.0.0.1:5000/item/3', UnitEnum(UnitEnum.TOGGLE), 0, 1))

        items.append(ItemModel('slaapkamer_verlichting', 'verlichting in de slaapkamer'))
        items.append(UsageModel(4, UsageTypeEnum.KILOWATT, 1, '127.0.0.1:5000/item/4', UnitEnum(UnitEnum.TOGGLE), 0, 1))

        items.append(ItemModel('lamp_nachtkastje', 'lamp op nachtkastje'))
        items.append(UsageModel(5, UsageTypeEnum.KILOWATT, 1, '127.0.0.1:5000/item/5', UnitEnum(UnitEnum.TOGGLE), 0, 1))

        items.append(ItemModel('toilet', 'toilet in badkamer'))
        items.append(UsageModel(6, UsageTypeEnum.WATER_PER_USAGE, 9,
                                '127.0.0.1:5000/item/6', UnitEnum(UnitEnum.TOGGLE), 0, 1))

        items.append(ItemModel('douche', 'douche'))
        items.append(UsageModel(7, UsageTypeEnum.WATER_PER_HOUR, 9,
                                '127.0.0.1:5000/item/7', UnitEnum(UnitEnum.TOGGLE), 0, 1))

        items.append(ItemModel('vaatwasser', ''))
        items.append(UsageModel(8, UsageTypeEnum.WATER_PER_USAGE, 10,
                                '127.0.0.1:5000/item/8', UnitEnum(UnitEnum.TOGGLE), 0, 1))

        items.append(ItemModel('wasmachine', ''))
        items.append(UsageModel(9, UsageTypeEnum.WATER_PER_USAGE, 13,
                                '127.0.0.1:5000/item/9', UnitEnum(UnitEnum.TOGGLE), 0, 1))

        items.append(ItemModel('droger', ''))
        items.append(UsageModel(10, UsageTypeEnum.KILOWATT, 9,
                                '127.0.0.1:5000/item/10', UnitEnum(UnitEnum.TOGGLE), 0, 1))

        items.append(ItemModel('badkamer verlichting', ''))
        items.append(UsageModel(11, UsageTypeEnum.KILOWATT, 1,
                                '127.0.0.1:5000/item/11', UnitEnum(UnitEnum.TOGGLE), 0, 1))

        # START CREATING GROUPS
        print('Creating groups...')
        items.append(GroupModel('Huiskamer', True))
        items.append(GroupModel('Slaapkamer', True))
        items.append(GroupModel('Badkamer', True))
        items.append(GroupModel('Verlichting', False))

        # START ADDING ITEMS TO GROUPS
        print('Assigning items to groups...')
        items.append(ItemGroupModel(2, 1))
        items.append(ItemGroupModel(3, 1))
        items.append(ItemGroupModel(8, 1))
        items.append(ItemGroupModel(4, 2))
        items.append(ItemGroupModel(5, 2))
        items.append(ItemGroupModel(6, 3))
        items.append(ItemGroupModel(7, 3))
        items.append(ItemGroupModel(9, 3))
        items.append(ItemGroupModel(10, 3))
        items.append(ItemGroupModel(11, 3))
        items.append(ItemGroupModel(2, 4))
        items.append(ItemGroupModel(3, 4))
        items.append(ItemGroupModel(4, 4))
        items.append(ItemGroupModel(5, 4))
        items.append(ItemGroupModel(11, 4))

        items.append(GraphModel('AVERAGE_TEMPERATURE', DataTypeEnum(DataTypeEnum.TEMPERATURE)))
        items.append(GraphModel('AVERAGE_WATER_USAGE', DataTypeEnum(DataTypeEnum.WATER_USAGE)))

        print('inserting data into db, this may take a while...')
        current = 1
        total = len(items)
        for item in items:
            print('{} out of {}'.format(current, total))
            current += 1
            item.save_to_db()
예제 #15
0
def test_item_resource():
    print("####################   TESTING ITEM RESOURCE   ####################")

    # GETTING ALL ITEMS
    print("TEST_1 --- GETTING ALL ITEMS")
    uri = "items"
    expected_result = {
        "items": []
    }
    expected_status = 200
    test_get(uri, expected_result, expected_status)

    # POSTING ONE ITEM
    print("TEST_2 --- POSTING ONE ITEM")
    item_1_name = 'Z04 Gang lamp (SW)'
    item_1_comment = 'ETS import'
    item_1 = ItemModel(item_1_name, item_1_comment)
    body = {
        "name": item_1_name,
        "comment": item_1_comment
    }
    item_1_json = item_1.to_json()
    item_1_json['id'] = 1
    item_1_json['url'] = "127.0.0.1:5000/api/v1/items/1"
    expected_result = item_1_json
    expected_status = 201
    uri = "items"
    test_post(uri, body, expected_result, expected_status)

    # GETTING ALL ITEMS
    print("TEST_3 --- GETTING ALL ITEMS")
    uri = "items"
    expected_result = {
        "items": [item_1_json]
    }
    expected_status = 200
    test_get(uri, expected_result, expected_status)

    # GETTING ONE ITEM
    print("TEST_4 --- GETTING ONE ITEM")
    uri = "items/1"
    expected_result = item_1_json
    expected_status = 200
    test_get(uri, expected_result, expected_status)

    # UPDATING ONE ITEM
    print("TEST_5 --- UPDATING ONE ITEM")
    uri = 'items/1'
    expected_result = item_1_json
    expected_result['comment'] = 'new_comment'
    body = {
        'name': item_1.name,
        'comment': 'new_comment'
    }
    expected_status = 200
    test_put(uri, body, expected_result, expected_status)
    item_1_json['comment'] = 'new_comment'

    # GETTING ONE ITEM
    print("TEST_6 --- GETTING UPDATED ITEM")
    uri = 'items/1'
    expected_result = item_1_json
    expected_status = 200
    test_get(uri, expected_result, expected_status)

    # POSTING ONE ITEM
    print("TEST_7 --- POSTING ONE ITEM - BAD REQUEST")
    item_1_name = 'Z04 Gang lamp (SW)_______________________________________________________________' \
                  '_________________________________________________________________________________' \
                  '_________________________________________________________________________________' \
                  '_________________________________________________________________________________'
    item_1_comment = 'ETS import'
    item_1 = ItemModel(item_1_name, item_1_comment)
    body = {
        "name": item_1_name,
        "comment": item_1_comment
    }
    item_1_json = item_1.to_json()
    item_1_json['id'] = 2
    expected_result = {"errors": [
        Error(
            "Name cannot be longer than 255 characters.",
            "Name parameter cannot be longer than 255 characters.",
            400,
            "https://en.wikipedia.org/wiki/HTTP_400").to_json()
    ]}
    expected_status = 422
    uri = "items"
    test_post(uri, body, expected_result, expected_status)

    # POSTING ONE ITEM
    print("TEST_8 --- POSTING ONE ITEM - BAD REQUEST")
    item_1_name = 'Z04 Gang lamp (SW)'
    item_1_comment = 'ETS import_______________________________________________________________' \
                     '_________________________________________________________________________________' \
                     '_________________________________________________________________________________' \
                     '_________________________________________________________________________________'
    item_1 = ItemModel(item_1_name, item_1_comment)
    body = {
        "name": item_1_name,
        "comment": item_1_comment
    }
    item_1_json = item_1.to_json()
    item_1_json['id'] = 2
    expected_result = {"errors": [
        Error(
            "Comment cannot be longer than 255 characters.",
            "Name parameter cannot be longer than 255 characters.",
            400,
            "https://en.wikipedia.org/wiki/HTTP_400").to_json()
    ]}
    expected_status = 422
    uri = "items"
    test_post(uri, body, expected_result, expected_status)

    # POSTING ONE ITEM
    print("TEST_9 --- POSTING ONE ITEM")
    item_2_name = 'Z04 Eetkamer lamp (SW)'
    item_2_comment = 'ETS import'
    item_2 = ItemModel(item_2_name, item_2_comment)
    body = {
        "name": item_2_name,
        "comment": item_2_comment
    }
    item_2_json = item_2.to_json()
    item_2_json['id'] = 2
    item_2_json['url'] = "127.0.0.1:5000/api/v1/items/2"
    expected_result = item_2_json
    expected_status = 201
    uri = "items"
    test_post(uri, body, expected_result, expected_status)