Esempio n. 1
0
    def do_update(self, args):
        """
        Updates a valid object by changing or creating authorized attributes.
        Usage: update <class name> <id> <attribute name> <attribute value>
        Arguments are supposed to be passed in order

        **Arguments**
            class name: class name of the object
            id: unique user id of the object
            attribute name: name of attribute to change or create
            attribute value: value of attribute
        """
        args = args.split()
        if len(args) == 0:
            print("** class name missing **")
            return
        if len(args) == 1:
            print("** instance id missing **")
            return
        if len(args) == 2:
            print("** attribute name missing **")
            return
        if len(args) == 3:
            print("** value missing **")
            return
        if args[0] not in HBNBCommand.valid_classes.keys():
            print("** class doesn't exist **")
            return
        all_objs = storage.all(args[0])
        for k, v in all_objs.items():
            if k == args[1]:
                setattr(v, args[2], args[3])
                storage.save()
                return
        print("** no instance found **")
Esempio n. 2
0
def our_cities(state_id=None):
    """ retrieves all cities in a state """

    try:
        obj = storage.all("State").pop("State." + state_id)
    except KeyError:
        abort(404)

    if request.method == 'GET':
        my_cities = [city.to_dict() for city in obj.cities]
        return (jsonify(my_cities))

    if request.method == 'POST':
        data = request.get_json(silent=True)
        if not data:
            return (jsonify({"error": 'Not a JSON'}), 400)

        if "name" not in data.keys():
            return (jsonify({"error": "Missing name"}), 400)
        city = City(**data)
        city.state_id = state_id
        storage.new(city)
        storage.save()
        return (jsonify(city.to_dict()), 201)
Esempio n. 3
0
def amenities_id(amenity_id):
    """GET request: retrieve the amenity linked to the id
    DELETE request: Delete the object linked to the id
    PUT request: Update the object linked to the id
    """
    amenity = storage.get('Amenity', amenity_id)
    if amenity is None:
        abort(404)

    if request.method == 'GET':
        return jsonify(amenity.to_dict())
    elif request.method == 'DELETE':
        storage.delete(amenity)
        storage.save()
        return jsonify({}), 200
    elif request.method == 'PUT':
        if request.is_json is False:
            return jsonify(error='Not a JSON'), 400
        new_attr = request.get_json()
        for attr in new_attr.keys():
            if attr not in ['id', 'created_at', 'updated_at']:
                setattr(amenity, attr, new_attr[attr])
        storage.save()
        return jsonify(amenity.to_dict()), 200
Esempio n. 4
0
def place(place_id):
    """Function that retrieve, delete and put a place"""
    place = storage.get(Place, place_id)
    if place:
        if request.method == "GET":
            return place.to_dict()
        elif request.method == "DELETE":
            storage.delete(place)
            storage.save()
            return {}
        elif request.method == "PUT":
            if not request.json:
                return make_response(jsonify({'error': "Not a JSON"}), 400)
            else:
                json = request.json
                for key, value in json.items():
                    if key != 'id' and key != 'user_id' and\
                       key != 'city_id' and key != 'created_at' and\
                       key != "updated_at":
                        setattr(place, key, value)
                place.updated_at = datetime.utcnow()
                storage.save()
                return make_response(place.to_dict(), 200)
    abort(404)
def create_amenities_relation(place_id, amenity_id):
    """ create a review of an specific place id"""
    places_to_search = storage.get(Place, place_id)
    amenities_to_search = storage.get(Amenity, amenity_id)
    # print(places_to_search)
    # print(amenities_to_search)
    if places_to_search is None or amenities_to_search is None:
        abort(404)
    if storage_t == 'db':
        amenity_place_asig = places_to_search.amenities
        if amenities_to_search in amenity_place_asig:
            return jsonify(amenities_to_search.to_dict()), 200
        else:
            amenity_place_asig.append(amenities_to_search)
            places_to_search.save()
            return jsonify(amenities_to_search.to_dict()), 201
    else:
        amenity_place_asig = places_to_search.amenity_ids
        if amenities_to_search in amenity_place_asig:
            return amenity_id, 200
        else:
            amenity_place_asig = amenity_id
            storage.save()
            return amenity_id, 201
Esempio n. 6
0
def create_city(state_id):
    """creates a City object"""
    error_message = ""
    state = storage.get("State", state_id)
    if state is not None:
        content = request.get_json(silent=True)
        if type(content) is dict:
            if "name" in content.keys():
                city = City(**content)
                setattr(city, "state_id", state_id)
                storage.new(city)
                storage.save()
                response = jsonify(city.to_dict())
                response.status_code = 201
                return response
            else:
                error_message = "Missing name"
        else:
            error_message = "Not a JSON"
        response = jsonify({"error": error_message})
        response.status_code = 400
        return response
    else:
        abort(404)
Esempio n. 7
0
 def do_destroy(self, line):
     """Deletes an instance based on the class name
     and id (save the change into the JSON file).
     """
     args = line.split(' ')
     if len(args) == 0:
         print("** class name missing **")
         return
     elif args[0] not in self.classes:
         print("** class doesn't exist **")
         return
     elif len(args) == 1:
         print("** instance id missing **")
         return
     else:
         all_objs = storage.all()
         k_find = args[0] + '.' + args[1]
         if k_find in all_objs:
             del all_objs[k_find]
             storage.save()
             return
         else:
             print('** no instance found **')
             pass
Esempio n. 8
0
    def do_destroy(self, args):
        '''
            Deletes an instance based on the class name and id.
        '''
        args = shlex.split(args)
        if len(args) == 0:
            print("** class name missing **")
            return
        elif len(args) == 1:
            print("** instance id missing **")
            return
        class_name = args[0]
        class_id = args[1]

        if os.getenv("HBNB_TYPE_STORAGE") != "db":
            storage = FileStorage()
            storage.reload()
            obj_dict = storage.all()
            try:
                eval(class_name)
            except NameError:
                print("** class doesn't exist **")
                return
            key = class_name + "." + class_id
            try:
                del obj_dict[key]
            except KeyError:
                print("** no instance found **")
            storage.save()
        else:
            from models import storage
            obj_dict = storage.all(eval(args[0]))
            for i in obj_dict.values():
                if i.id == class_id:
                    storage.delete(i)
                    storage.save()
Esempio n. 9
0
def link_an_amenity(place_id=None, amenity_id=None):
    """
        Links an Amenity object to a place according to
        their respective id
    """

    if place_id is None or amenity_id is None:
        return abort(404)

    my_place = storage.get(Place, place_id)
    if my_place is None:
        return abort(404)

    my_amenity = storage.get(Amenity, amenity_id)
    if my_amenity is None:
        return abort(404)

    if my_amenity in my_place.amenities:
        return make_response(jsonify(my_amenity.to_dict()), 200)

    my_place.amenities.append(my_amenity)
    storage.save()

    return make_response(jsonify(my_amenity.to_dict()), 201)
Esempio n. 10
0
def amenities_by_id(amenity_id):
    """
    Handle amenity by id
    """
    amenity = storage.get('Amenity', amenity_id)
    if amenity is None:
        abort(404, 'Not found')

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

    elif request.method == 'PUT':
        changes = dict()

        try:
            changes = request.get_json()
            if changes is None:
                abort(400, 'Not a JSON')
        except BadRequest:
            abort(400, 'Not a JSON')

        ignores = ('id', 'created_at', 'updated_at')

        for key, val in changes.items():
            if key in ignores:
                pass
            else:
                setattr(amenity, key, val)

        amenity.save()
        return make_response(jsonify(**amenity.to_dict()), 200)

    elif request.method == 'DELETE':
        storage.delete(amenity)
        storage.save()
        return make_response(jsonify({}), 200)
Esempio n. 11
0
 def do_update(self, args):
     """ update an instance by its UUID
     """
     args_l = args.split()
     if len(args_l) == 0:
         print("** class name missing **")
     elif (args_l[0] not in self.classes):
         print("** class doesn't exist **")
     elif len(args_l) == 1:
         print("** instance id missing **")
         return
     else:
         try:
             key = args_l[0] + '.' + args_l[1]
             storage.all()[key]
         except KeyError:
             print('** no instance found **')
             return
         if len(args_l) == 2:
             print("** attribute name missing **")
             return
         elif len(args_l) == 3:
             print("** value missing **")
             return
         else:
             key = args_l[0] + '.' + args_l[1]
             try:
                 if '.' in args_l[3]:
                     value = float(args_l[3])
                 else:
                     value = int(args_l[3])
             except ValueError:
                 value = str(args_l[3]).strip("\"':")
                 value = str(value)
                 setattr(storage.all()[key], args_l[2].strip("\"':"), value)
                 storage.save()
Esempio n. 12
0
def all_places(city_id):
    """ Route to GET and POST method. Should be retrieve all place objs. """
    city = storage.get('City', city_id)
    if city is None:
        abort(404)

    if request.method == 'GET':
        return jsonify([v.to_dict() for v in city.places])
    else:
        req = request.get_json()
        if req is None:
            abort(400, 'Not a JSON')
        if req.get('user_id') is None:
            abort(400, 'Missing user_id')
        user = storage.get('User', req.get('user_id'))
        if user is None:
            abort(404)
        else:
            if req.get('name') is None:
                abort(400, 'Missing name')
            else:
                new_place = Place(**(req))
                storage.save()
                return new_place.to_dict(), 201
Esempio n. 13
0
 def do_destroy(self, args):
     '''Deletes an instance based on the class name and id'''
     args = shlex.split(args)
     if len(args) == 0:
         print("** class name missing **")
         return
     elif len(args) == 1:
         print("** instance id missing **")
         return
     class_name = args[0]
     class_id = args[1]
     storage.reload()
     obj_dict = storage.all()
     try:
         eval(class_name)
     except NameError:
         print("** class doesn't exist **")
         return
     key = class_name + "." + class_id
     try:
         del obj_dict[key]
     except KeyError:
         print("** no instance found **")
     storage.save()
Esempio n. 14
0
def review(review_id):

    review = storage.get('Review', review_id)
    if review is None:
        abort(404)

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

    if request.method == 'DELETE':
        storage.delete(review)
        storage.save()
        return jsonify({}), 200

    if request.method == 'PUT':
        if not request.get_json():
            abort(400, "Not a JSON")
        for key, value in request.get_json().items():
            if key not in [
                    "id", "user_id", "place_id", "created_at", "updated_at"
            ]:
                setattr(review, key, value)
        review.save()
        return jsonify(review.to_dict()), 200
Esempio n. 15
0
def review_delete(review_id=None):
    """ Update review
    ---
    tags:
        - Review
    parameters:
      - name: review_id
        in: path
        type: string
        required: true
    responses:
      200:
        description: Review updated
      404:
        description: Resource not found
      400:
        description: Not a JSON
    """
    review = storage.get("Review", review_id)
    if review is None:
        abort(404)
    if request.method == 'DELETE':
        review.delete()
        storage.save()
        return (jsonify({}), 200)
    if request.method == 'PUT':
        if not request.is_json:
            abort(400, "Not a JSON")
        to_update = request.get_json()
        for key, value in to_update.items():
            if (key is not "id" and key is not "created_at"
                    and key is not "updated_at" and key is not "user_id"
                    and key is not "place_id"):
                setattr(review, key, value)
        review.save()
        return (jsonify(review.to_dict()), 200)
Esempio n. 16
0
    def do_destroy(self, arg):
        """ Deletes an instance passed """

        if not arg:
            print("** class name missing **")
            return

        args = arg.split(' ')

        if args[0] not in HBNBCommand.l_classes:
            print("** class doesn't exist **")
        elif len(args) == 1:
            print("** instance id missing **")
        else:
            all_objs = storage.all()
            for key, value in all_objs.items():
                ob_name = value.__class__.__name__
                ob_id = value.id
                if ob_name == args[0] and ob_id == args[1].strip('"'):
                    del value
                    del storage._FileStorage__objects[key]
                    storage.save()
                    return
            print("** no instance found **")
Esempio n. 17
0
 def do_destroy(self, arg):
     """
     Deletes an instance based on the class name and id
     (saves the changes into the JSON file)
     Structure: destroy [class name] [id]
     """
     tokens = shlex.split(arg)
     if len(tokens) == 0:
         print("** class name missing **")
         return
     if tokens[0] not in HBNBCommand.my_dict.keys():
         print("** class doesn't exist **")
         return
     if len(tokens) <= 1:
         print("** instance id missing **")
         return
     storage.reload()
     objs_dict = storage.all()
     key = tokens[0] + "." + tokens[1]
     if key in objs_dict:
         del objs_dict[key]
         storage.save()
     else:
         print("** no instance found **")
Esempio n. 18
0
    def do_destroy(self, arg):
        """ Deletes an instance based on the class name and
            id (saves the change into the JSON file).

            Ex: (hbnb) destroy BaseModel 1234-1234-1234.
        """

        args = arg.split(' ')

        if args[0] == '':
            print("** class name missing **")
        elif args[0] in {"Amenity", "BaseModel", "City", "Place", "Review",
                         "State", "User"}:
            if len(args) >= 2:
                key_id = args[0] + "." + args[1]
                if key_id in storage.all():
                    del storage.all()[key_id]
                    storage.save()
                else:
                    print("** no instance found **")
            else:
                print("** instance id missing **")
        else:
            print("** class doesn't exist **")
def place_amenity_id(place_id, amenity_id):
    """ /places/<place_id>/amenities/<amenity_id> route """
    place = storage.get(Place, place_id)
    amenity = storage.get(Amenity, amenity_id)
    if place is None or amenity is None:
        return {"error": "Not found"}, 404
    if models.storage_t != 'db':
        amenities = place.amenity_ids
    else:
        amenities = place.amenities
    if request.method == 'DELETE':
        if amenity not in amenities:
            return {"error": "Not found"}, 404
        storage.delete(amenity)
        storage.save()
        return {}, 200
    elif request.method == 'POST':
        try:
            if amenity in amenities:
                return jsonify(amenity.to_dict()), 200
            amenities.append(amenity)
            return jsonify(amenity.to_dict()), 201
        except:
            return {"error": "Not a JSON"}, 400
Esempio n. 20
0
    def do_destroy(self, arg):
        """Deletes an instance based on the class name
        and id (save the change into the JSON file).

        Usage: destroy <ClassName> <id>
        """
        args = arg.split()
        if not arg:
            print("** class name missing **")
            return
        if args[0] not in HBNBCommand.__bnb_classes:
            print("** class doesn't exist **")
            return
        if len(args) < 2:
            print("** instance id missing **")
            return
        aux_key = "{}.{}".format(args[0], args[1].replace('"', ''))
        if aux_key in storage.all():
            del storage.all()[aux_key]
            storage.save()
            return
        else:
            print("** no instance found **")
            return
def state_id(state_id):
    """ returns the state or 404 """
    state = storage.get(State, state_id)
    if state is not None:
        if request.method == 'GET':
            return jsonify(state.to_dict())
        elif request.method == 'DELETE':
            storage.delete(state)
            storage.save()
            return {}, 200
        elif request.method == 'PUT':
            try:
                new_dict = request.get_json()
                state_dict = state.to_dict()
                for key, value in new_dict.items():
                    if key not in ["id", "created_at", "updated_at"]:
                        state_dict.update({key: value})
                storage.delete(state)
                storage.new(State(**state_dict))
                storage.save()
                return jsonify(state_dict), 200
            except:
                return {"error": "Not a JSON"}, 400
    return {"error": "Not found"}, 404
def delete_amenities_relation(place_id, amenity_id):
    """Delete one review"""
    places_to_search = storage.get(Place, place_id)
    if places_to_search is None:
        abort(404)
    amenities_to_search = storage.get(Amenity, amenity_id)
    if amenities_to_search is None:
        abort(404)
    if storage_t == 'db':
        amenity_place_asig = places_to_search.amenities
        if amenities_to_search not in amenity_place_asig:
            abort(404)
        else:
            amenity_place_asig.remove(amenities_to_search)
            places_to_search.save()
            return jsonify({}), 200
    else:
        amenity_place_asig = places_to_search.amenity_ids
        if amenities_to_search in amenity_place_asig:
            abort(404)
        else:
            amenity_place_asig.remove(amenity_id)
            storage.save()
            return jsonify({}), 200
Esempio n. 23
0
 def do_update(self, line):
     """
     Updates an instance based on the class name and id by adding
     or updating attribute (save the change into the JSON file).
     Ex: $ update BaseModel 1234-1234-1234 email
     "*****@*****.**".
     Usage: update <class name> <id> <attribute name> "<attribute value>"
     A string argument with a space must be between double quote
     """
     if not line:
         print("** class name missing **")
         return
     args = shlex.split(line)
     objects = storage.all()
     if args[0] in self.classes:
         if len(args) < 2:
             print("** instance id missing **")
             return
         key = args[0] + "." + args[1]
         if key not in objects:
             print("** no instance found **")
         else:
             obj = objects[key]
             base = ["id", "created_at", "updated_at"]
             if obj:
                 arg = shlex.split(line)
                 if len(arg) < 3:
                     print("** attribute name mising **")
                 elif len(arg) < 4:
                     print("** value missing **")
                 elif arg[2] not in base:
                     obj[arg[2]] = arg[3]
                     # obj["updated_at"] = datetime.now()
                     storage.save()
     else:
         print("** class doesn't exist **")
Esempio n. 24
0
def put_amenities(amenity_id):
    """
    Update amenity
    """
    new_amenity = None
    object_list = []
    content = request.get_json()
    if content is None:
        return jsonify({"error": "Not a JSON"}), 400
    exclude = ['id', 'created_at', 'updated_at']
    for e in exclude:
        content.pop(e, None)
    json_amenities = storage.all("Amenity")
    for amenity_obj in json_amenities.values():
        object_list.append(amenity_obj)
    for amenity in object_list:
        if amenity.id == amenity_id:
            for k, v in content.items():
                setattr(amenity, k, v)
            new_amenity = amenity
    if new_amenity is None:
        return jsonify({"error": "Not found"}), 404
    storage.save()
    return jsonify(new_amenity.to_dict()), 200
Esempio n. 25
0
 def do_destroy(self, line):
     """Deletes an instance based on the class name and id (
         save the change into the JSON file). Ex: $ destroy
         BaseModel 1234-1234-1234.
     """
     arg = line.split()
     if len(arg) == 0:
         print('** class name missing **')
     elif arg[0] not in self.classes.keys():
         print('** class doesn\'t exist **')
     elif len(arg) == 1 and arg[0] in self.classes.keys():
         print('** instance id missing **')
     elif len(arg) == 2 and arg[0] in self.classes.keys():
         key = arg[0] + '.' + arg[1]
         list_obj = storage.all()
         id_counter = 0
         for obj in list_obj.keys():
             if obj == key:
                 id_counter += 1
         if id_counter > 0:
             del list_obj[key]
             storage.save()
         if id_counter == 0:
             print('** no instance found **')
def amenity_id(amenity_id):
    """ returns the amenity or 404 """
    amenity = storage.get(Amenity, amenity_id)
    if amenity is not None:
        if request.method == 'GET':
            return jsonify(amenity.to_dict())
        elif request.method == 'DELETE':
            storage.delete(amenity)
            storage.save()
            return {}, 200
        elif request.method == 'PUT':
            try:
                new_dict = request.get_json()
                amenity_dict = amenity.to_dict()
                for key, value in new_dict.items():
                    if key not in ["id", "created_at", "updated_at"]:
                        amenity_dict.update({key: value})
                storage.delete(amenity)
                storage.new(Amenity(**amenity_dict))
                storage.save()
                return jsonify(amenity_dict), 200
            except:
                return {"error": "Not a JSON"}, 400
    return {"error": "Not found"}, 404
Esempio n. 27
0
 def do_destroy(self, arg):
     """Deletes an instance based on the class name and id"""
     tf = "false"
     args = arg.split()
     if len(args) < 1:
         print("** class name missing **")
     elif args[0] in Dict:
         if len(args) < 2:
             print("** instance id missing **")
         else:
             key = args[0] + "." + args[1]
             for i in storage.all():
                 arggs = str(storage.all()[i]).split()
                 cid = arggs[1][slice(1, -1)]
                 cname = arggs[0][slice(1, -1)]
                 if cid == args[1] and cname == args[0]:
                     storage.all().pop(key, None)
                     tf = "true"
                     storage.save()
                     break
             if tf == "false":
                 print("** no instance found **")
     else:
         print("** class doesn't exist **")
Esempio n. 28
0
def put_states_id():
    """ Return status of the APP as OK """
    data = request.get_json()
    if not data:
        abort(400, 'Not a JSON')
    if 'name' not in data:
        abort(400, 'Missing name')
    if 'victims' not in data:
        abort(400, 'Missing victims')
    catch_state = storage.get(data['name'])
    if catch_state is None:
        #If the object doesnt exists, create it
        """DUDAS A ESTE PUNTO, ES NECESARIO CREAR EL STATE O YA VA A ESTAR CREADO"""
        if type(data['victims']) is int:
            new_state = State(**data)
            new_state.save()
        else:
            new_state = {}
        return jsonify(new_state.to_dict()), 201
        """HASTA ACA"""
    #If the object exists, update it
    setattr(catch_state, 'victims', data['victims'])
    storage.save()
    return jsonify(catch_state.to_dict()), 200
Esempio n. 29
0
 def do_destroy(self, line):
     """
     Deletes an instance and saves to JSON file
     """
     arg = shlex.split(line)
     if len(arg) == 0:
         print("** class name missing **")
         return
     elif arg[0] not in self.classnames:
         print("** class doesn't exist **")
         return
     elif len(arg) < 2:
         print("** instance id missing **")
         return
     else:
         instance_obj = storage.all()
         key_check = "{}.{}".format(arg[0], arg[1])
         if key_check not in instance_obj.keys():
             print("** no instance found **")
             return
         else:
             instance_obj.pop(key_check)
             storage.save()
             return
Esempio n. 30
0
def get_cities_from_state(state_id):
        """retrive cities from given state"""
        items = []
        if request.method == "GET":
                obj = storage.get("State", state_id)
                for item in storage.all(City).values():
                        if item.state_id == state_id:
                                items.append(item.to_dict())
                return jsonify(items)
        elif request.method == 'POST':
                obj = storage.get("State", state_id)
                data = request.get_json()
                if not obj:
                        abort(404)
                if data is None:
                        abort(400, "Not a JSON")
                if "name" not in data.keys():
                        abort(400, "Missing name")
                else:
                        data['state_id'] = state_id
                        newcity = City(**data)
                        storage.new(newcity)
                        storage.save()
                return make_response(jsonify(newcity.to_dict()), 201)
Esempio n. 31
0
def create_place(city_id):
    '''Creates an instance of Amenity and save it to storage'''
    city = storage.get('City', city_id)
    if city is None:
        abort(404)
    form = request.get_json(force=True)
    if form is None:
        abort(400, "Not a JSON")

    if "user_id" not in form:
        abort(404, "Missing user_id")

    user = storage.get(User, form.get("user_id"))
    if user is None:
        abort(404)

    if "name" not in form:
        abort(400, "Missing name")

    form["city_id"] = city_id
    new_place = Place(**form)
    storage.new(new_place)
    storage.save()
    return (jsonify(new_place.to_dict()), 201)