def cities_by_statess(): """List all cities by states""" states = storage.all("State").values() cities = storage.all("City").values() result = [[state, [city for city in cities if city.state_id == state.id]] for state in states] result.sort(key=lambda x: x[0].name) return render_template("8-cities_by_states.html", Query_name="States", result=result)
def hbnb_filters(): states = storage.all("State").values() result = [] for state in sorted(states, key=lambda x: x.name): result.append([state, state.cities]) amenities = storage.all("Amenity").values() return render_template("10-hbnb_filters.html", amenities=amenities, result=result)
def hbnb(): states = storage.all("State").values() amenities = storage.all("Amenity").values() places_tmp = storage.all("Place").values() owners = storage.all("User") places = [] for k, v in owners.items(): for place in places_tmp: if k == place.user_id: places.append(["{} {}".format( v.first_name, v.last_name), place]) places.sort(key=lambda x: x[1].name) return render_template("100-hbnb.html", amenities=amenities, result=states, places=places)
def class_exec(self, cls_name, args): """Wrapper function for <class name>.action()""" if args[:6] == '.all()': self.do_all(cls_name) elif args[:6] == '.show(': self.do_show(cls_name + ' ' + args[7:-2]) elif args[:8] == ".count()": all_objs = {k: v for (k, v) in storage.all().items() if isinstance(v, eval(cls_name))} print(len(all_objs)) elif args[:9] == '.destroy(': self.do_destroy(cls_name + ' ' + args[10:-2]) elif args[:8] == '.update(': if '{' in args and '}' in args: new_arg = args[8:-1].split('{') new_arg[1] = '{' + new_arg[1] else: new_arg = args[8:-1].split(',') if len(new_arg) == 3: new_arg = " ".join(new_arg) new_arg = new_arg.replace("\"", "") new_arg = new_arg.replace(" ", " ") self.do_update(cls_name + ' ' + new_arg) elif len(new_arg) == 2: try: dict = eval(new_arg[1]) except: return for j in dict.keys(): self.do_update(cls_name + ' ' + new_arg[0][1:-3] + ' ' + str(j) + ' ' + str(dict[j])) else: return else: print("Not a valid command")
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 **")
def do_destroy(self, args): """ Destroys an instance Usage: destroy <ClassName> <id> Order of arguments is not checked **Arguments** ClassName: name of class id: unique user id of instance """ args = args.split() if len(args) == 0: print("** class name missing **") return if len(args) == 1: print("** instance id missing **") return if args[0] not in HBNBCommand.valid_classes.keys(): print("** class doesn't exist **") return all_objs = storage.all() for k, v in all_objs.items(): if k == args[1] and args[0] == v.__class__.__name__: storage.delete(v) return print("** no instance found **")
def do_show(self, args): """ Shows the __dict__ of an instance. Usage: show <ClassName> <id> Arguments are supposed to be in order **Arguments** ClassName: name of class id: unique user id of instance """ args = args.split() if len(args) == 0: print("** class name missing **") return if len(args) == 1: print("** instance id missing **") return if args[0] not in HBNBCommand.valid_classes: print("** class doesn't exist **") return all_objs = storage.all() for objs_id in all_objs.keys(): if objs_id == args[1] and args[0] in str(type(all_objs[objs_id])): print(all_objs[objs_id]) return print("** no instance found **")
def cities_by_states(): """List all cities by states""" states = storage.all("State").values() result = [] for state in sorted(states, key=lambda x: x.name): result.append([state, state.cities]) return render_template("8-cities_by_states.html", Query_name="States", result=result)
def do_all(self, ClassName=""): """ Prints all objects or all objects for a class Usage: all [<ClassName>] **Arguments** ClassName: not required, a valid class name """ if not ClassName: for instance in storage.all().values(): print(instance) else: if ClassName not in HBNBCommand.valid_classes.keys(): print("** class doesn't exist **") return else: for instance in storage.all(ClassName).values(): print(instance)
def test_getstates_empty_db(self): """test listing all states in empty db""" s = storage.all("State").values() for e in s: storage.delete(e) rv = self.app.get('{}/states/'.format(self.path)) self.assertEqual(rv.status_code, 200) self.assertEqual(rv.headers.get("Content-Type"), "application/json") json_format = getJson(rv) self.assertTrue(type(json_format), list) self.assertEqual(json_format, [])
def cities_by_states(id_d="all"): states = storage.all("State") if id_d == "all": return render_template("9-states.html", state="all", Query_name="States", states=states.values()) else: flag = False for k, v in states.items(): if k == id_d: flag = True break if flag: result = v.cities return render_template("9-states.html", state="1", Query_name="State: {}".format(v.name), states=result) else: return render_template("9-states.html", state="", Query_name="Not found!", states=states)
def states_by_id(id=None): """Display HTML page""" states = storage.all("State") if id: id = "State." + id return render_template('9-states.html', states=states, id=id)
def get_amenities(): """Retrieves the list of all""" all_amenities = storage.all('Amenity').values() dict_amenities = [obj.to_dict() for obj in all_amenities] return jsonify(dict_amenities)
def states(state_id=None): """ddisplay states and cities in alpha""" states = storage.all("State") if state_id is not None: state_id = 'State.' + state_id return render_template('9-states.html', states=states, state_id=state_id)
#!/usr/bin/python3 """ handle all default RESTful API""" from models.city import City from os import getenv from flask import abort, jsonify, request from models import storage from api.v1.views import app_views objs = storage.all('City') @app_views.route('/states/<state_id>/cities', methods=['GET'], strict_slashes=False) def get_cities(state_id): """get all cities of a state """ new_list = [] for key, val in objs.items(): if val.state_id == state_id: new_list.append(val.to_dict()) return jsonify(new_list) @app_views.route('/cities/<city_id>', methods=['GET'], strict_slashes=False) def get_city(city_id): """get a city """ city_obj = storage.get('City', city_id) if city_obj is None: abort(404)
def get_all_users(): ''' Retrieves a list of all user objects in the DB ''' data = storage.all(User) new = [val.to_dict() for key, val in data.items()] return jsonify(new)
def all_users(): all_users_li = [] for value in storage.all(User).values(): all_users_li.append(value.to_dict()) return (jsonify(all_users_li))
def state_list(): """hello even or odd number""" states = storage.all("State") return render_template("7-states_list.html", states=states)
def state_and_state(): """ Display an html page with state and state.id """ states_all = storage.all("State") return render_template('9-states.html', states_all=states_all)
def state_list(): my_states = [] for key, value in storage.all(State).items(): my_states.append(value) return render_template('9-states.html', my_states=my_states)
def display_html(): """ Display states from storage """ states = storage.all("State") return render_template('7-states_list.html', states=states)
def cities_by_states(): """ Display an html page city by state """ states = storage.all("State") return render_template('8-cities_by_states.html', states=states)
def states_list(): all_states = storage.all('State') return render_template('8-cities_by_states.html', all_states=all_states)
def cities_page(): """ display a HTML page: lists cities by states""" states_lst = storage.all('State').values() return render_template('8-cities_by_states.html', states_lst)
def state_l(): states = storage.all("State").values() return render_template('7-states_list.html', states=states)
def view_states(): """returns list of states""" """ if no states, returns an empty list with status code 200""" state_list = [val.to_dict() for val in storage.all("State").values()] return jsonify(state_list)
def states(state_id=None): """display the states and cities listed in alphabetical order""" states = storage.all("State") if state_id is not None: state_id = 'State.' + state_id return render_template('9-states.html', states=states, state_id=state_id)
def tearDownModule(): ob = storage.all() ob.clear() storage.save() if os.path.isfile('file.json'): os.remove('file.json')
def list_states(): """list all states in a db""" states = storage.all("State").values() return render_template("7-states_list.html", Query_name="States", states=states)
def get_amenities(): """ Retrieves the list of all Amenity objects """ amenities = storage.all(Amenity) return jsonify([amenity.to_dict() for amenity in amenities.values()])
#!/usr/bin/python3 """ a script that starts a Flask web application """ from models import storage, State from flask import Flask, render_template app = Flask(__name__) app.url_map.strict_slashes = False a_dict = storage.all('State').values() @app.route('/') def hello_world(): return 'Hello HBNB!' @app.route('/hbnb') def hello(): return 'HBNB' @app.route('/c/<text>') def hello_more(text): a_string = 'C ' + text return a_string.replace('_', ' ') @app.route('/python/') def hello_python(): a_string = 'Python ' + 'is cool' return a_string.replace('_', ' ')
def list_all_states(): """ init all state """ state_list = storage.all('State') return render_template('7-states_list.html', state_list=state_list)
def do_update(self, args): """ Updates a certain object with new info """ c_name = c_id = att_name = att_val = kwargs = '' # isolate cls from id/args, ex: (<cls>, delim, <id/args>) args = args.partition(" ") if args[0]: c_name = args[0] else: # class name not present print("** class name missing **") return if c_name not in HBNBCommand.classes: # class name invalid print("** class doesn't exist **") return # isolate id from args args = args[2].partition(" ") if args[0]: c_id = args[0] else: # id not present print("** instance id missing **") return # generate key from class and id key = c_name + "." + c_id # determine if key is present if key not in storage.all(): print("** no instance found **") return # first determine if kwargs or args if '{' in args[2] and '}' in args[2] and type(eval(args[2])) is dict: kwargs = eval(args[2]) args = [] # reformat kwargs into list, ex: [<name>, <value>, ...] for k, v in kwargs.items(): args.append(k) args.append(v) else: # isolate args args = args[2] if args and args[0] is '\"': # check for quoted arg second_quote = args.find('\"', 1) att_name = args[1:second_quote] args = args[second_quote + 1:] args = args.partition(' ') # if att_name was not quoted arg if not att_name and args[0] is not ' ': att_name = args[0] # check for quoted val arg if args[2] and args[2][0] is '\"': att_val = args[2][1:args[2].find('\"', 1)] # if att_val was not quoted arg if not att_val and args[2]: att_val = args[2].partition(' ')[0] args = [att_name, att_val] # retrieve dictionary of current objects new_dict = storage.all()[key] # iterate through attr names and values for i, att_name in enumerate(args): # block only runs on even iterations if (i % 2 == 0): att_val = args[i + 1] # following item is value if not att_name: # check for att_name print("** attribute name missing **") return if not att_val: # check for att_value print("** value missing **") return # type cast as necessary if att_name in HBNBCommand.types: att_val = HBNBCommand.types[att_name](att_val) # update dictionary with name, value pair new_dict.__dict__.update({att_name: att_val}) new_dict.save() # save updates to file
def states_list(): states = storage.all(State).values() cities = storage.all(City).values() return render_template("8-cities_by_states.html", states=states, cities=cities)
def state_list(): """ route to display a HTML page """ states = storage.all(State).values() return render_template('8-cities_by_states.html', states=states)
def get_amenities(): """Retrieves the list of all Amenity objects""" amty_list = [] for amty in storage.all('Amenity').values(): amty_list.append(amty.to_dict()) return jsonify(amty_list)
def test_all_returns_dict(self): """Test that all returns the FileStorage.__objects attr""" storage = FileStorage() new_dict = storage.all() self.assertEqual(type(new_dict), dict) self.assertIs(new_dict, storage._FileStorage__objects)
def states_all(): """Display States""" states = storage.all(State) return render_template('9-states.html', state=states, mode="none")
def cities_by_states(): states = storage.all(State) return render_template('8-cities_by_states.html', states=states)
#!/usr/bin/python3 import sys import os sys.path.insert(1, os.path.join(os.path.split(__file__)[0], '../')) from models import storage from models.base_model import BaseModel all_objs = storage.all() print("-- Reloaded objects --") for obj_id in all_objs.keys(): obj = all_objs[obj_id] print(obj) print("-- Create a new object --") my_model = BaseModel() my_model.name = "Holberton" my_model.my_number = 89 my_model.save() print(my_model)
def display_states_list(): """disolay states""" return render_template('7-states_list.html', storage=storage.all('State'))
def get_users(): """ doc for get_users method """ users = storage.all(User) return jsonify([user.to_dict() for user in users.values()])
def list_states(): '''Retrieves a list of all State objects''' list_states = [obj.to_dict() for obj in storage.all("State").values()] return jsonify(list_states)