Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

working hard #3746

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added api/__init__.py
Empty file.
Binary file added api/__pycache__/__init__.cpython-38.pyc
Binary file not shown.
Empty file added api/v1/__init__.py
Empty file.
Binary file added api/v1/__pycache__/__init__.cpython-38.pyc
Binary file not shown.
Binary file added api/v1/__pycache__/app.cpython-38.pyc
Binary file not shown.
50 changes: 50 additions & 0 deletions api/v1/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
#!/usr/bin/python3
'''Contains a Flask web application API.
'''
import os
from flask import Flask, jsonify
from flask_cors import CORS

from models import storage
from api.v1.views import app_views


app = Flask(__name__)
'''The Flask web application instance.'''
app_host = os.getenv('HBNB_API_HOST', '0.0.0.0')
app_port = int(os.getenv('HBNB_API_PORT', '5000'))
app.url_map.strict_slashes = False
app.register_blueprint(app_views)
CORS(app, resources={'/*': {'origins': app_host}})


@app.teardown_appcontext
def teardown_flask(exception):
'''The Flask app/request context end event listener.'''
# print(exception)
storage.close()


@app.errorhandler(404)
def error_404(error):
'''Handles the 404 HTTP error code.'''
return jsonify(error='Not found'), 404


@app.errorhandler(400)
def error_400(error):
'''Handles the 400 HTTP error code.'''
msg = 'Bad request'
if isinstance(error, Exception) and hasattr(error, 'description'):
msg = error.description
return jsonify(error=msg), 400


if __name__ == '__main__':
app_host = os.getenv('HBNB_API_HOST', '0.0.0.0')
app_port = int(os.getenv('HBNB_API_PORT', '5000'))
app.run(
host=app_host,
port=app_port,
threaded=True
)
17 changes: 17 additions & 0 deletions api/v1/views/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#!/usr/bin/python3
'''Contains the blueprint for the API.'''
from flask import Blueprint


app_views = Blueprint('app_views', __name__, url_prefix='/api/v1')
'''The blueprint for the AirBnB clone API.'''


from api.v1.views.amenities import *
from api.v1.views.cities import *
from api.v1.views.index import *
from api.v1.views.places_amenities import *
from api.v1.views.places import *
from api.v1.views.places_reviews import *
from api.v1.views.states import *
from api.v1.views.users import *
Binary file added api/v1/views/__pycache__/__init__.cpython-38.pyc
Binary file not shown.
Binary file added api/v1/views/__pycache__/index.cpython-38.pyc
Binary file not shown.
86 changes: 86 additions & 0 deletions api/v1/views/amenities.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
#!/usr/bin/python3
'''Contains the amenities view for the API.'''
from flask import jsonify, request
from werkzeug.exceptions import NotFound, MethodNotAllowed, BadRequest

from api.v1.views import app_views
from models import storage
from models.amenity import Amenity


ALLOWED_METHODS = ['GET', 'DELETE', 'POST', 'PUT']
'''Methods allowed for the amenities endpoint.'''


@app_views.route('/amenities', methods=ALLOWED_METHODS)
@app_views.route('/amenities/<amenity_id>', methods=ALLOWED_METHODS)
def handle_amenities(amenity_id=None):
'''The method handler for the amenities endpoint.
'''
handlers = {
'GET': get_amenities,
'DELETE': remove_amenity,
'POST': add_amenity,
'PUT': update_amenity,
}
if request.method in handlers:
return handlers[request.method](amenity_id)
else:
raise MethodNotAllowed(list(handlers.keys()))


def get_amenities(amenity_id=None):
'''Gets the amenity with the given id or all amenities.
'''
all_amenities = storage.all(Amenity).values()
if amenity_id:
res = list(filter(lambda x: x.id == amenity_id, all_amenities))
if res:
return jsonify(res[0].to_dict())
raise NotFound()
all_amenities = list(map(lambda x: x.to_dict(), all_amenities))
return jsonify(all_amenities)


def remove_amenity(amenity_id=None):
'''Removes a amenity with the given id.
'''
all_amenities = storage.all(Amenity).values()
res = list(filter(lambda x: x.id == amenity_id, all_amenities))
if res:
storage.delete(res[0])
storage.save()
return jsonify({}), 200
raise NotFound()


def add_amenity(amenity_id=None):
'''Adds a new amenity.
'''
data = request.get_json()
if type(data) is not dict:
raise BadRequest(description='Not a JSON')
if 'name' not in data:
raise BadRequest(description='Missing name')
new_amenity = Amenity(**data)
new_amenity.save()
return jsonify(new_amenity.to_dict()), 201


def update_amenity(amenity_id=None):
'''Updates the amenity with the given id.
'''
xkeys = ('id', 'created_at', 'updated_at')
all_amenities = storage.all(Amenity).values()
res = list(filter(lambda x: x.id == amenity_id, all_amenities))
if res:
data = request.get_json()
if type(data) is not dict:
raise BadRequest(description='Not a JSON')
old_amenity = res[0]
for key, value in data.items():
if key not in xkeys:
setattr(old_amenity, key, value)
old_amenity.save()
return jsonify(old_amenity.to_dict()), 200
raise NotFound()
98 changes: 98 additions & 0 deletions api/v1/views/cities.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
#!/usr/bin/python3
'''Contains the cities view for the API.'''
from flask import jsonify, request
from werkzeug.exceptions import NotFound, MethodNotAllowed, BadRequest

from api.v1.views import app_views
from models import storage, storage_t
from models.city import City
from models.place import Place
from models.review import Review
from models.state import State


@app_views.route('/states/<state_id>/cities', methods=['GET', 'POST'])
@app_views.route('/cities/<city_id>', methods=['GET', 'DELETE', 'PUT'])
def handle_cities(state_id=None, city_id=None):
'''The method handler for the cities endpoint.
'''
handlers = {
'GET': get_cities,
'DELETE': remove_city,
'POST': add_city,
'PUT': update_city,
}
if request.method in handlers:
return handlers[request.method](state_id, city_id)
else:
raise MethodNotAllowed(list(handlers.keys()))


def get_cities(state_id=None, city_id=None):
'''Gets the city with the given id or all cities in
the state with the given id.
'''
if state_id:
state = storage.get(State, state_id)
if state:
cities = list(map(lambda x: x.to_dict(), state.cities))
return jsonify(cities)
elif city_id:
city = storage.get(City, city_id)
if city:
return jsonify(city.to_dict())
raise NotFound()


def remove_city(state_id=None, city_id=None):
'''Removes a city with the given id.
'''
if city_id:
city = storage.get(City, city_id)
if city:
storage.delete(city)
if storage_t != "db":
for place in storage.all(Place).values():
if place.city_id == city_id:
for review in storage.all(Review).values():
if review.place_id == place.id:
storage.delete(review)
storage.delete(place)
storage.save()
return jsonify({}), 200
raise NotFound()


def add_city(state_id=None, city_id=None):
'''Adds a new city.
'''
state = storage.get(State, state_id)
if not state:
raise NotFound()
data = request.get_json()
if type(data) is not dict:
raise BadRequest(description='Not a JSON')
if 'name' not in data:
raise BadRequest(description='Missing name')
data['state_id'] = state_id
city = City(**data)
city.save()
return jsonify(city.to_dict()), 201


def update_city(state_id=None, city_id=None):
'''Updates the city with the given id.
'''
xkeys = ('id', 'state_id', 'created_at', 'updated_at')
if city_id:
city = storage.get(City, city_id)
if city:
data = request.get_json()
if type(data) is not dict:
raise BadRequest(description='Not a JSON')
for key, value in data.items():
if key not in xkeys:
setattr(city, key, value)
city.save()
return jsonify(city.to_dict()), 200
raise NotFound()
36 changes: 36 additions & 0 deletions api/v1/views/index.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#!/usr/bin/python3
'''Contains the index view for the API.'''
from flask import jsonify

from api.v1.views import app_views
from models import storage
from models.amenity import Amenity
from models.city import City
from models.place import Place
from models.review import Review
from models.state import State
from models.user import User


@app_views.route('/status')
def get_status():
'''Gets the status of the API.
'''
return jsonify(status='OK')


@app_views.route('/stats')
def get_stats():
'''Gets the number of objects for each type.
'''
objects = {
'amenities': Amenity,
'cities': City,
'places': Place,
'reviews': Review,
'states': State,
'users': User
}
for key, value in objects.items():
objects[key] = storage.count(value)
return jsonify(objects)
Loading