Пример #1
0
def amenities():
    """Handle GET and POST requests to /amenities route.

    Return a list of all amenities in database in the case of a GET request.
    Create a new amenity record in the database in the case of a POST request.
    """
    # handle GET requests:
    # --------------------------------------------------------------------------
    if request.method == 'GET':
        list = ListStyle.list(Amenity.select(), request)
        return jsonify(list)

    # handle POST requests:
    # --------------------------------------------------------------------------
    elif request.method == 'POST':
        try:
            record = Amenity(name=request.form['name'])
            record.save()
            return jsonify(record.to_hash())

        # return 409 if amenity with given name already exists
        except IntegrityError:
                return json_response(
                    add_status_=False,
                    status_=409,
                    code=10003,
                    msg="Name already exists"
                )
Пример #2
0
def create_database():
    try:
         User.create_table()
    except peewee.OperationalError:
        pass

    try:
         State.create_table()
    except peewee.OperationalError:
        pass

    try:
         City.create_table()
    except peewee.OperationalError:
        pass

    try:
         Place.create_table()
    except peewee.OperationalError:
        pass

    try:
         PlaceBook.create_table()
    except peewee.OperationalError:
        pass

    try:
         Amenity.create_table()
    except peewee.OperationalError:
        pass

    try:
         PlaceAmenities.create_table()
    except peewee.OperationalError:
        pass
Пример #3
0
def create_amenity():
    try:
        new_amenity = Amenity(name=request.form['name'])
        new_amenity.save()
        return jsonify(new_amenity.to_dict())
    except:
        return jsonify({'code': 10003, 'msg': 'Name already exists'}), 409
Пример #4
0
def handle_amenity_for_place(place_id, amenity_id):
    '''Add the amenity with `amenity_id` to the place with `place_id` with a
    POST request. Delete the amenity with the id of `amenity_id` with a DELETE
    request.

    Keyword arguments:
    place_id -- The id of the place.
    amenity_id -- The id of the amenity.
    '''
    try:
        Amenity.select().where(Amenity.id == amenity_id).get()
    except Amenity.DoesNotExist:
        return jsonify(msg="Amenity does not exist."), 404
    try:
        Place.select().where(Place.id == place_id).get()
    except Place.DoesNotExist:
        return jsonify(msg="Place does not exist."), 404

    if request.method == 'POST':
        '''Save the connection in the ReviewPlace table.'''
        PlaceAmenities().create(place=place_id, amenity=amenity_id)

        return jsonify(msg="Amenity added to place successfully."), 201

    elif request.method == 'DELETE':
        (PlaceAmenities
         .delete()
         .where((PlaceAmenities.place == place_id) &
                (PlaceAmenities.amenity == amenity_id))
         .execute())

        Amenity.delete().where(Amenity.id == amenity_id).execute()

        return jsonify(msg="Amenity deleted successfully."), 200
Пример #5
0
def create_amenity():
    try:
        new_amenity = Amenity(name=request.form['name'])
        new_amenity.save()
        return jsonify(new_amenity.to_dict())
    except:
        return jsonify({'code': 10003, 'msg': 'Name already exists'}), 409
Пример #6
0
def handle_amenity_for_place(place_id, amenity_id):
    '''Add the amenity with `amenity_id` to the place with `place_id` with a
    POST request. Delete the amenity with the id of `amenity_id` with a DELETE
    request.

    Keyword arguments:
    place_id -- The id of the place.
    amenity_id -- The id of the amenity.
    '''
    try:
        Amenity.select().where(Amenity.id == amenity_id).get()
    except Amenity.DoesNotExist:
        return jsonify(msg="Amenity does not exist."), 404
    try:
        Place.select().where(Place.id == place_id).get()
    except Place.DoesNotExist:
        return jsonify(msg="Place does not exist."), 404

    if request.method == 'POST':
        '''Save the connection in the ReviewPlace table.'''
        PlaceAmenities().create(place=place_id, amenity=amenity_id)

        return jsonify(msg="Amenity added to place successfully."), 201

    elif request.method == 'DELETE':
        (PlaceAmenities.delete().where((PlaceAmenities.place == place_id) & (
            PlaceAmenities.amenity == amenity_id)).execute())

        Amenity.delete().where(Amenity.id == amenity_id).execute()

        return jsonify(msg="Amenity deleted successfully."), 200
Пример #7
0
def create_amenity():
    """
    Create a amenity
    """
    data = request.form
    try:
        if 'name' not in data:
            raise KeyError("'name'")

        check_amenity = Amenity.select(). where(Amenity.name == data['name'])
        if check_amenity:
            return {'code': 10003, 'msg': 'Name already exists'}, 409

        new = Amenity.create(
            name=data['name']
        )
        res = {}
        res['code'] = 201
        res['msg'] = "Amenity was created successfully"
        return res, 201
    except KeyError as e:
        res = {}
        res['code'] = 40000
        res['msg'] = 'missing parameters'
        return res, 400
    except Exception as error:
        response = {}
        response['code'] = 409
        response['msg'] = str(error)
        return response, 409
Пример #8
0
def app_create_delete_amenity(place_id, amenity_id):
    try:
        Place.get(Place.id == place_id)
    except Place.DoesNotExist:
        return jsonify({"code": 409, "msg": "place id does not exist"}), 409
    try:
        Amenity.get(Amenity.id == amenity_id)
    except Amenity.DoesNotExist:
        return jsonify({"code": 409, "msg": "amenity id does not exist"}), 409

    if request.method == "POST":
        if PlaceAmenities.select().where(
                PlaceAmenities.place == place_id,
                PlaceAmenities.amenity == amenity_id).exists():
            return jsonify({
                "code": 409,
                "msg": "Place already has this amenity"
            }), 409

        PlaceAmenities.create(place=place_id, amenity=amenity_id)
        return jsonify({"code": 200, "msg": "success"}), 200

    elif request.method == "DELETE":
        try:
            query = PlaceAmenities.select().where(
                PlaceAmenities.place == place_id,
                PlaceAmenities.amenity == amenity_id).get()
            query.delete_instance()
            return jsonify({"code": 200, "msg": "success"}), 200
        except:
            return jsonify({"code": 404, "msg": "not found"}), 404
Пример #9
0
def get_amenity(amenity_id):
    """
    Get the given amenity
    Return the given amenity in the database.
    ---
    tags:
        - Amenity
    parameters:
        -
            in: path
            name: amenity_id
            type: string
            required: True
            description: ID of the amenity
    responses:
        200:
            description: Amenity returned successfully
            schema:
                id: Amenity
                required:
                    - name
                    - id
                    - created_at
                    - updated_at
                properties:
                    name:
                        type: string
                        description: Name of the amenity
                        default: "Swimming Pool"
                    id:
                        type: number
                        description: id of the amenity
                        default: 1
                    created_at:
                        type: datetime string
                        description: date and time the amenity was created in the database
                        default: '2016-08-11 20:30:38'
                    updated_at:
                        type: datetime string
                        description: date and time the amenity was updated in the database
                        default: '2016-08-11 20:30:38'
        404:
            description: Amenity was not found
        500:
            description: Request could not be processed
    """
    try:
        ''' Check if amenity exists '''
        query = Amenity.select().where(Amenity.id == amenity_id)
        if not query.exists():
            raise LookupError('amenity_id')

        ''' Return amenity data '''
        amenity = Amenity.get(Amenity.id == amenity_id)
        return amenity.to_dict(), 200
    except LookupError as e:
        abort(404)
    except Exception as e:
        abort(500)
Пример #10
0
def amenity_id(amenity_id):
    if request.method == 'GET':
        amenity = Amenity.get(Amenity.id == amenity_id)
        return jsonify(amenity.to_hash())

    elif request.method == 'DELETE':
        amenity = Amenity.get(Amenity.id == amenity_id)
        amenity.delete_instance()
        return 'Amenity %s deleted \n' % place_id
Пример #11
0
    def createAmenityViaPeewee(self):
        """
        Create an amenity record using the API's database/Peewee models.

        createAmenityViaPeewee returns the Peewee object for the record. This
        method will not work if the database models are not written correctly.
        """
        record = Amenity(name='amenity_name')
        record.save()
        return record
Пример #12
0
def create_amenities():
    data = request.form
    check_amenity =  Amenity.select(). where(Amenity.name == data['name'])
    if check_amenity:
        return {'code': 10003, 'msg': 'Name already exists'}, 409

    amenity = Amenity.create(
        name = data['name']
    )
    return {'code': 201, 'msg': 'Amenity created successfully'}, 201
Пример #13
0
    def createAmenityViaPeewee(self):
        """
        Create an amenity record using the API's database/Peewee models.

        createAmenityViaPeewee returns the Peewee object for the record. This
        method will not work if the database models are not written correctly.
        """
        record = Amenity(name= 'amenity_name')
        record.save()
        return record
Пример #14
0
def amenities():
	if request.method == 'GET':
		list_amenities = Amenity.select()
		return json_dumps(list_amenities.to_hash())

	elif request.method == 'POST':
		data = request.data
		name = data['name']

		entry = Amenity.insert(name=name)
		entry.execute()
Пример #15
0
def create_asdfstate():
    content = request.get_json()
    if not all(param in content.keys() for param in ["name"]):
        #ERROR
        return "Failed: bad input"
    try:
        amenity = Amenity()
        amenity.name = content["name"]
        amenity.save()
    except Exception as e:
        return "Failed"
    return "Success"
Пример #16
0
def delete_amenity(amenity_id):
    """
    Delete the given amenity
    Deletes the given amenity in the database.
    ---
    tags:
        - Amenity
    parameters:
        -
            in: path
            name: amenity_id
            type: string
            required: True
            description: ID of the amenity
    responses:
        200:
            description: Amenity deleted successfully
            schema:
                id: delete_200
                required:
                    - code
                    - msg
                properties:
                    code:
                        type: integer
                        description: Response code from the API
                        default: 200
                    msg:
                        type: string
                        description: Message about record deletion
                        default: "deleted successfully"
        404:
            description: Amenity was not found
        500:
            description: Request could not be processed
    """
    try:
        ''' Check if amenity exists '''
        query = Amenity.select().where(Amenity.id == amenity_id)
        if not query.exists():
            raise LookupError('amenity_id')

        ''' Delete the amenity '''
        amenity = Amenity.delete().where(Amenity.id == amenity_id)
        amenity.execute()
        res = {}
        res['code'] = 200
        res['msg'] = "Amenity was deleted successfully"
        return res, 200
    except LookupError as e:
        abort(404)
    except Exception as e:
        abort(500)
Пример #17
0
def create_amenity():
    """
    Create an amenity
    Creates an amenity based on post parameters.
    ---
    tags:
      - amenity
    parameters:
      - name: name
        in: query
        type: string
        description: name of the amenity to create
    responses:
      200:
        description: Success message
        schema:
          id: success_message
          properties:
            status:
              type: number
              description: status code
              default: 200
            msg:
              type: string
              description: Status message
              default: 'Success'
      400:
          description: Error message
          schema:
            id: error_message
            properties:
              status:
                type: number
                description: status code
                default: 40000
              msg:
                type: string
                description: Status message
                default: 'Missing parameters'
    """
    content = request.get_json(force=True)
    if not content: return error_msg(400, 400, "Error")
    if not all(param in content.keys() for param in ["name"]):
        #ERROR
        return error_msg(400, 40000, "Missing parameters")
    try:
        amenity = Amenity()
        amenity.name = content["name"]
        amenity.save()
    except Exception as e:
        return error_msg(400, 400, "Error")
    return error_msg(200, 200, "Success")
Пример #18
0
def delete_amenity(amenity_id):
    """
    Delete amenity with id as amenity_id
    """
    try:
        amenity = Amenity.get(Amenity.id == amenity_id)
    except Exception:
        return {'code': 404, 'msg': 'Amenity not found'}, 404
    amenity = Amenity.delete().where(Amenity.id == amenity_id)
    amenity.execute()
    res = {}
    res['code'] = 201
    res['msg'] = "Amenity was deleted successfully"
    return res, 201
Пример #19
0
def delete_amenity(amenity_id):
    try:
        amenity = Amenity.get(Amenity.id == amenity_id)
        amenity.delete_instance()
        return jsonify({'msg': 'Deleted amenity!'})
    except:
        return jsonify({'code': 404, 'msg': 'not found'}), 404
Пример #20
0
def delete_amenity(amenity_id):
    try:
        amenity = Amenity.get(Amenity.id == amenity_id)
        amenity.delete_instance()
        return jsonify({'msg': 'Deleted amenity!'})
    except:
        return jsonify({'code': 404, 'msg': 'not found'}), 404
Пример #21
0
def place_amenity_id(place_id, amenity_id):
	query = Place.select().where(Place.id == place_id)

	if query.wrapped_count() < 1:
		return json_response(status_=404, msg="that place does not exist")

	query = Amenity.select().where(Amenity.id == amenity_id)

	if query.wrapped_count() < 1:
		return json_response(status_=404, msg="that amenity does not exist")

	query = PlaceAmenities.select().where(PlaceAmenities.amenity == amenity_id, PlaceAmenities.place == place_id)

	if query.wrapped_count() > 0:
		return json_response(status_=404, msg="amenity already set for given place")

	if request.method == "POST":
		insert = PlaceAmenities(place=place_id, amenity=amenity_id)
		insert.save()
		return jsonify(insert.to_dict()), 201

	elif request.method == "DELETE":
		amenity = PlaceAmenities.get(PlaceAmenities.amenity == amenity_id, PlaceAmenities.place == place_id)
		amenity.delete_instance()
		amenity.save()
		return json_response(status_=200, msg="amentiy delete for given place")
Пример #22
0
def get_place_amenities(place_id):
    """
    Get amenities for place
    Return a list of all amenities for a place
    ---
    tags:
        - Amenity
    parameters:
        -
            in: path
            name: place_id
            type: string
            required: True
            description: ID of the place
    responses:
        200:
            description: List of all amenities for the place
            schema:
                $ref: '#/definitions/get_amenities_get_Amenities'
    """
    try:
        ''' Check if the place exists '''
        query = Place.select().where(Place.id == place_id)
        if not query.exists():
            raise LookupError('place_id')

        ''' Return amenities for the given place '''
        data = Amenity.select().join(PlaceAmenities).where(PlaceAmenities.place == place_id)
        return ListStyle.list(data, request), 200
    except LookupError as e:
        abort(404)
    except Exception as e:
        abort(500)
Пример #23
0
def amenity_id(amenity_id):
    """Handle GET, PUT & DELETE requests to /amenities/<amenity_id> route.

    Return a hash of the appropriate record in the case of a GET request.
    Delete appropriate record in case of DELETE request.
    """
    # check whether resource exists:
    # --------------------------------------------------------------------------
    try:
        record = Amenity.get(Amenity.id == amenity_id)

    # return 404 not found if it does not
    except Amenity.DoesNotExist:
        return json_response(
            add_status_=False,
            status_=404,
            code=404,
            msg="not found"
        )

    # if exception does not arise:
    # --------------------------------------------------------------------------
    # handle GET requests
    if request.method == 'GET':
        return jsonify(record.to_hash())

    # handle PUT requests
    elif request.method == "DELETE":
        record.delete_instance()
        record.save()
        return 'deleted booking\n'
Пример #24
0
def amenity_id(amenity_id):
    """Handle GET, PUT & DELETE requests to /amenities/<amenity_id> route.

    Return a hash of the appropriate record in the case of a GET request.
    Delete appropriate record in case of DELETE request.
    """
    # check whether resource exists:
    # --------------------------------------------------------------------------
    try:
        record = Amenity.get(Amenity.id == amenity_id)

    # return 404 not found if it does not
    except Amenity.DoesNotExist:
        return json_response(add_status_=False,
                             status_=404,
                             code=404,
                             msg="not found")

    # if exception does not arise:
    # --------------------------------------------------------------------------
    # handle GET requests
    if request.method == 'GET':
        return jsonify(record.to_hash())

    # handle PUT requests
    elif request.method == "DELETE":
        record.delete_instance()
        record.save()
        return 'deleted booking\n'
Пример #25
0
def amenities_in_places(place_id):
    if request.method == 'GET':
        amenities_list = []
        amenities = Amenity.select().join(Place).where(Place.id == place_id)
        for amenity in amenities:
            amenities_list.append(amenity.to_hash())
        return jsonify(amenities_list)
Пример #26
0
def app_amenities_id(amenity_id):
    if request.method == "GET":
        try:
            query = Amenity.get(Amenity.id == amenity_id)
            return ListStyles.list(query, request), 200
        except:
            return jsonify({"code": 404, "msg": "not found"}), 404

    elif request.method == "DELETE":
        try:
            query = Amenity.get(Amenity.id == amenity_id)
            query.delete_instance()

            return jsonify({"code": 200, "msg": "success"}), 200
        except:
            return jsonify({"code": 404, "msg": "not found"}), 404
Пример #27
0
def get_amenities():
    amenities = []
    query = Amenity.select()
    for i in query:
        amenities.append(i.to_hash())

    return jsonify(amenities)
Пример #28
0
def app_amenities():
    if request.method == "GET":
        try:
            query = Amenity.select()
            if not query.exists():
                return jsonify({"code": 404, "msg": "not found"}), 404
            return ListStyles.list(query, request), 200
        except:
            return jsonify({"code": 404, "msg": "not found"}), 404

    elif request.method == "POST":
        try:
            new = Amenity.create(name=request.form['name'])
            return jsonify(new.to_dict()), 201
        except:
            return jsonify({"code": 10003, "msg": "Name already exists"}), 409
Пример #29
0
    def subtest_createWithAllParams(self):
        """
        Test proper creation of an amenity record upon POST request to the API
        with all parameters provided.
        """
        POST_request1 = self.createAmenityViaAPI()
        self.assertEqual(POST_request1.status[:3], '200')

        now = datetime.now().strftime('%d/%m/%Y %H:%M')

        self.assertEqual(Amenity.get(Amenity.id == 1).name, 'amenity_name')
        self.assertEqual(Amenity.get(Amenity.id == 1).created_at.strftime('%d/%m/%Y %H:%M'), now)
        self.assertEqual(Amenity.get(Amenity.id == 1).updated_at.strftime('%d/%m/%Y %H:%M'), now)

        # test that placebook ID for sole record in database is correct
        self.assertEqual(Amenity.select().get().id, 1)
Пример #30
0
def get_amenity_by_place(id):
    amenities = []
    query = Amenity.select().where(Place.id == id)
    for i in query:
        amenities.append(i.to_hash())

    return jsonify(amenities)
Пример #31
0
def get_amenity(id):
    try:
        amenity = Amenity.get(Amenity.id == id)
    except Exception:
        return {'code': 404, 'msg': 'Amenity not found'}, 404

    return amenity.to_hash(), 200
Пример #32
0
def delete_amenity(id):
    try:
        amenity = Amenity.get(Amenity.id == id)
    except Exception:
        return {'code': 404, 'msg': 'Amenity not found'}, 404

    amenity.delete_instance()
    return {'code': 200, 'msg': 'Deleted successfully'}, 200
Пример #33
0
def app_amenities_place(place_id):
    if request.method == "GET":
        try:
            query = Amenity.select().join(PlaceAmenities).where(
                PlaceAmenities.place == place_id)
            return ListStyles.list(query, request), 200
        except:
            return jsonify({"code": 404, "msg": "not found"}), 404
Пример #34
0
def del_amenity(amenity_id):
    try:
        query = Amenity.get(Amenity.id == amenity_id)
    except Amenity.DoesNotExist:
        return {"code":404, "msg": "not found"}, 404
    out_dict = query.to_dict()
    query.delete_instance()
    return out_dict
Пример #35
0
def amenities_id(amenity_id):

	amenity = Amenity.select().where(id=amenity_id).get()
	if request.method == 'GET':
		return amenity.to_hash()

	elif request.method == 'DELETE':
		amenity.delete_instance()
Пример #36
0
def get_statdasfde_by_id(amen_id):
    amens = Amenity.select().where(Amenity.id == int(amen_id))
    amen = None
    for u in amens:
        amen = u
    if amen == None:
        return "Failed"
    return jsonify(amen.to_hash())
Пример #37
0
def amenities_place(place_id):
	if request.method == "GET":
		try:
			query = Amenity.select().join(PlaceAmenities).where(PlaceAmenities.place == place_id)
			return ListStyle.list(query, request), 200

		except:
			return json_response(status_=404, msg="Not found")
Пример #38
0
def get_staasedfazte_by_id(amen_id):
    amens = Amenity.select().where(Amenity.id == int(amen_id))
    amen = None
    for u in amens:
        amen = u
    if amen == None:
        return "Failed"
    amen.delete_instance()
    return "Success"
Пример #39
0
def get_amenity(amenity_id):
    """
    Get a amenity with id as amenity_id
    """
    try:
        amenity = Amenity.get(Amenity.id == amenity_id)
    except Exception:
        return {'code': 404, 'msg': 'Amenity not found'}, 404
    return amenity.to_dict(), 200
Пример #40
0
def create_amenity():
    post_data = request.values
    if 'name' not in post_data:
        return {"code":404, "msg": "not found"}, 404
    
    new_amenity, created = Amenity.get_or_create(name = post_data['name'])
    if not created:
        out = {'code': 10003, 'msg': 'Name already exists'}
        return out, 409
    return new_amenity.to_dict()
Пример #41
0
def handle_amenity_id(amenity_id):
    '''Returns a JSON object of the amenity with the id passed as parameter
    with a GET request method. Removes an amenity with DELETE request method.

    Keyword arguments:
    amenity_id: The id of the amenity.
    '''
    try:
        amenity = Amenity.select().where(Amenity.id == amenity_id).get()
    except Amenity.DoesNotExist:
        raise Exception("There is no amenity with this id.")

    if request.method == 'GET':
        return jsonify(amenity.to_dict()), 200

    elif request.method == 'DELETE':
        amenity = Amenity.delete().where(Amenity.id == amenity_id)
        amenity.execute()
        return jsonify(msg="Amenity deleted successfully."), 200
Пример #42
0
def handle_amenity_id(amenity_id):
    '''Returns a JSON object of the amenity with the id passed as parameter
    with a GET request method. Removes an amenity with DELETE request method.

    Keyword arguments:
    amenity_id: The id of the amenity.
    '''
    try:
        amenity = Amenity.select().where(Amenity.id == amenity_id).get()
    except Amenity.DoesNotExist:
        raise Exception("There is no amenity with this id.")

    if request.method == 'GET':
        return jsonify(amenity.to_dict()), 200

    elif request.method == 'DELETE':
        amenity = Amenity.delete().where(Amenity.id == amenity_id)
        amenity.execute()
        return jsonify(msg="Amenity deleted successfully."), 200
Пример #43
0
def amenities_id(amenity_id):
	if request.method == 'GET':
		try:
			amenity = Amenity.select().where(Amenity.id == amenity_id)

		except Amenity.DoesNotExist:
			return json_response(status_=404, msg="Not found")

		return jsonify(amenity.to_dict()), 200

	elif request.method == 'DELETE':
		try:
			amenity = Amenity.get(Amenity.id == amenity_id)

		except Amenity.DoesNotExist:
			return json_response(status_=404, msg="Not found")

		amenity.delete_instance()
		amenity.save()
		return json_response(status_=200, msg="Amenity deleted")
Пример #44
0
def handle_amenity():
    '''Returns all amenities as JSON objects in an array with a GET request.
    Adds an amenity with a POST request.
    '''
    if request.method == 'GET':
        list = ListStyle().list(Amenity.select(), request)
        return jsonify(list), 200

    elif request.method == 'POST':
        try:
            Amenity.select().where(Amenity.name == request.form['name']).get()
            return jsonify(code=10003, msg="Name already exists"), 409
        except Amenity.DoesNotExist:
            '''Check that all the required parameters are made in request.'''
            required = set(["name"]) <= set(request.values.keys())
            if required is False:
                return jsonify(msg="Missing parameter."), 400

            amenity = Amenity.create(name=request.form['name'])
            return jsonify(amenity.to_dict()), 200
Пример #45
0
    def subtest_createWithAllParams(self):
        """
        Test proper creation of an amenity record upon POST request to the API
        with all parameters provided.
        """
        POST_request1 = self.createAmenityViaAPI()
        self.assertEqual(POST_request1.status[:3], '200')

        now = datetime.now().strftime('%d/%m/%Y %H:%M')

        self.assertEqual(Amenity.get(Amenity.id == 1).name, 'amenity_name')
        self.assertEqual(
            Amenity.get(Amenity.id == 1).created_at.strftime('%d/%m/%Y %H:%M'),
            now)
        self.assertEqual(
            Amenity.get(Amenity.id == 1).updated_at.strftime('%d/%m/%Y %H:%M'),
            now)

        # test that placebook ID for sole record in database is correct
        self.assertEqual(Amenity.select().get().id, 1)
Пример #46
0
def place_amenities(place_id):
    # need to test and correct this request handler
    query = (Amenity.select().join(
        PlaceAmenities, on=(Amenity.id == PlaceAmenities.amenity)).join(
            Place, on=(Place.id == PlaceAmenities.place)).where(
                Place.id == place_id).get())

    for record in query:
        hash = record.to_hash()
        list.append(hash)
    return jsonify(list)
Пример #47
0
def handle_amenity():
    '''Returns all amenities as JSON objects in an array with a GET request.
    Adds an amenity with a POST request.
    '''
    if request.method == 'GET':
        list = ListStyle().list(Amenity.select(), request)
        return jsonify(list), 200

    elif request.method == 'POST':
        try:
            Amenity.select().where(Amenity.name == request.form['name']).get()
            return jsonify(code=10003, msg="Name already exists"), 409
        except Amenity.DoesNotExist:
            '''Check that all the required parameters are made in request.'''
            required = set(["name"]) <= set(request.values.keys())
            if required is False:
                return jsonify(msg="Missing parameter."), 400

            amenity = Amenity.create(name=request.form['name'])
            return jsonify(amenity.to_dict()), 200
Пример #48
0
def list_select_amenities(place_id):
    try:
        Place.get(Place.id == place_id)
    except Place.DoesNotExist:
        return jsonify({'code': 404, 'msg': ' place not found'}), 404

    list = ListStyle.list(
        Amenity.select().join(PlaceAmenities).where(
            Amenity.id == PlaceAmenities.amenity).where(
                PlaceAmenities.place == place_id), request)

    return jsonify(list)
Пример #49
0
def list_select_amenities(place_id):
    try:
        Place.get(Place.id == place_id)
    except Place.DoesNotExist:
        return jsonify({'code': 404, 'msg': ' place not found'}), 404

    list = ListStyle.list(Amenity.select()
                          .join(PlaceAmenities)
                          .where(Amenity.id == PlaceAmenities.amenity)
                          .where(PlaceAmenities.place == place_id), request)

    return jsonify(list)
Пример #50
0
def amenities():
    """Handle GET and POST requests to /amenities route.

    Return a list of all amenities in database in the case of a GET request.
    Create a new amenity record in the database in the case of a POST request.
    """
    # handle GET requests:
    # --------------------------------------------------------------------------
    if request.method == 'GET':
        list = []
        for record in Amenity.select():
            hash = record.to_hash()
            list.append(hash)
        return jsonify(list)

    # handle POST requests:
    # --------------------------------------------------------------------------
    elif request.method == 'POST':
        try:
            record = Amenity(name=request.form['name'])
            record.save()
            return jsonify(record.to_hash())

        # return 409 if amenity with given name already exists
        except IntegrityError:
            return json_response(add_status_=False,
                                 status_=409,
                                 code=10003,
                                 msg="Name already exists")
Пример #51
0
def amenities():
    if request.method == 'GET':
        amenities_list = []
        amenities = Amenity.select()
        for amenity in amenities:
            amenities_list.append(amenity.to_hash())
        return jsonify(amenities_list)

    elif request.method == 'POST':
        amenities = Amenity.select()
        for amenity in amenities:
            if amenity.name == request.form['name']:
                message = {
                    'code': 10003,
                    'msg': 'Amenity already exists',
                }
                res = jsonify(message)
                res.status_code = 409
                return res

        else:
            new_amenity = Amenity.create(name=request.form['name'])
            return jsonify(new_amenity.to_hash())
Пример #52
0
def update(place_id, amenity_id):
    # Checking if place exist
    try:
        Place.get(Place.id == place_id)
    except Place.DoesNotExist:
        return jsonify({'code': 404, 'msg': 'Place not found'}), 404

    # Checking is Amenity exist
    try:
        Amenity.get(Amenity.id == amenity_id)
    except Amenity.DoesNotExist:
        return jsonify({'code': 404, 'msg': 'Amenity not found'}), 404

    if request.method == "POST":
        new_place_amenity = PlaceAmenities(place=place_id, amenity=amenity_id)
        new_place_amenity.save()
        return jsonify(new_place_amenity.amenity.to_dict())

    elif request.method == "DELETE":
        get_place_a = PlaceAmenities.get(
            PlaceAmenities.place == place_id
            and PlaceAmenities.amenity == amenity_id)
        get_place_a.delete_instance
        return "amenity deleted"
Пример #53
0
def handle_place_id_amenity(place_id):
    '''Returns all amenities of the place_id as JSON objects in an array with a
    GET request.

    Keyword arguments:
    place_id: The id of the amenity.
    '''
    try:
        PlaceAmenities.select().where(PlaceAmenities.place == place_id).get()
    except PlaceAmenities.DoesNotExist:
        return jsonify(msg="Amenity does not exist."), 404

    if request.method == 'GET':
        '''Use a join statement to get the instances in the amenity table.'''
        list = ListStyle().list((Amenity.select().join(
            PlaceAmenities, on=PlaceAmenities.amenity).where(
                PlaceAmenities.place == place_id)), request)

        return jsonify(list), 200
Пример #54
0
def amenities():
	if request.method == 'GET':
		amenities = Amenity.select()
		return ListStyle.list(amenities, request), 200

	elif request.method == 'POST':
		try:
			if "name" not in request.form:
				return json_response(status_=400, msg="missing parameters", code=40000)
				
			test = Amenity.select().where(Amenity.name == request.form["name"])

			if test.wrapped_count() > 0:
				return json_response(status_=409, code=10002, msg="place already exists with this name")

			amenity = Amenity(name=request.form["name"])
			amenity.save()
			return jsonify(amenity.to_dict()), 201

		except IntegrityError:
			return json_response(status_=409,
								msg="Name already exists",
								code=10003)
Пример #55
0
def find_amenity(amenity_id):
    try:
        list = Amenity.get(Amenity.id == amenity_id)
        return jsonify(list.to_dict())
    except:
        return jsonify({'code': 404, 'msg': 'not found'}), 404
Пример #56
0
def list_amenities():
    try:
        list = ListStyle.list(Amenity.select(), request)
        return jsonify(list)
    except:
        return jsonify({'code': 404, 'msg': 'not found'}), 404
Пример #57
0
def get_amenities():
    """
    Get all amenities
    """
    data = Amenity.select()
    return ListStyle.list(data, request), 200