From 525933f63cb39896c3d5452235747cbca3bb2379 Mon Sep 17 00:00:00 2001 From: Adriana Gutierrez Date: Fri, 22 Apr 2022 13:53:42 -0400 Subject: [PATCH 01/19] defined Planet class and instantiated a list of the planets in our solar system --- app/routes.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..b30f8a2c4 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,21 @@ -from flask import Blueprint +from flask import Blueprint, jsonify + +class Planet: + def __init__(self, id, name, description, gravity): + self.id = id + self.name = name + self.description = description + self.gravity = gravity + +planets = [ + Planet(1, "Mercury", "Smallest and closest to sun", 3.7), + Planet(2, "Venus", "Brightest object in the Earth's night sky", 8.8), + Planet(3, "Earth", "Big blue ball, lots of water", 9.8), + Planet(4, "Mars", "Baren red rock", 3.7), + Planet(5, "Jupiter", "Enormous gas giant", 24.8), + Planet(6, "Saturn", "Pretty rings", 10.4), + Planet(7, "Uranus", "Unfortunately named", 8.9), + Planet(8, "Neptune", "Smallest gas giant", 11.2), + Planet(9, "Pluto", "Not really a planet", 0.6) +] From 4843797033abe4a43ed48a59b5beb16b3d4c029b Mon Sep 17 00:00:00 2001 From: Adriana Gutierrez Date: Fri, 22 Apr 2022 14:04:14 -0400 Subject: [PATCH 02/19] created /planets endpoing --- app/__init__.py | 3 +++ app/routes.py | 14 ++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..ab9eee40e 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -4,4 +4,7 @@ def create_app(test_config=None): app = Flask(__name__) + from .routes import planets_bp + app.register_blueprint(planets_bp) + return app diff --git a/app/routes.py b/app/routes.py index b30f8a2c4..501c7c093 100644 --- a/app/routes.py +++ b/app/routes.py @@ -19,3 +19,17 @@ def __init__(self, id, name, description, gravity): Planet(9, "Pluto", "Not really a planet", 0.6) ] +planets_bp = Blueprint("planets_bp", __name__, url_prefix="/planets") + +@planets_bp.route("", methods = ["GET"]) +def handle_planets(): + planets_response = [] + for planet in planets: + planets_response.append(dict( + id=planet.id, + name=planet.name, + description=planet.description, + gravity=planet.gravity + )) + + return jsonify(planets_response) \ No newline at end of file From 9dc023d582ca095144cca67f2a5632cedb213097 Mon Sep 17 00:00:00 2001 From: olive Date: Mon, 25 Apr 2022 13:51:53 -0500 Subject: [PATCH 03/19] wave 2 completed --- app/routes.py | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/app/routes.py b/app/routes.py index 501c7c093..ac9776b49 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,4 +1,4 @@ -from flask import Blueprint, jsonify +from flask import Blueprint, jsonify, abort, make_response class Planet: def __init__(self, id, name, description, gravity): @@ -6,6 +6,14 @@ def __init__(self, id, name, description, gravity): self.name = name self.description = description self.gravity = gravity + + def to_dict(self): + return dict( + id=self.id, + name=self.name, + description=self.description, + gravity=self.gravity, + ) planets = [ Planet(1, "Mercury", "Smallest and closest to sun", 3.7), @@ -32,4 +40,24 @@ def handle_planets(): gravity=planet.gravity )) - return jsonify(planets_response) \ No newline at end of file + return jsonify(planets_response) + +def validate_planet(id): + try: + id = int(id) + except ValueError: + abort(make_response(jsonify(dict(details=f"invalid id: {id}")), 400)) + + for planet in planets: + if planet.id == id: + # return the planet + return planet + + # no planet found + abort(make_response(jsonify(dict(details=f"planet id {id} not found")), 404)) + +# GET /planets/id +@planets_bp.route("/", methods=("GET",)) +def get_planet(id): + planet = validate_planet(id) + return jsonify(planet.to_dict()) From 91d2fffd1fba13c36bc5f8651b46ad1bbd7ac4a0 Mon Sep 17 00:00:00 2001 From: olive Date: Tue, 26 Apr 2022 16:13:22 -0500 Subject: [PATCH 04/19] refactored handle_planets to use to_dict --- app/routes.py | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/app/routes.py b/app/routes.py index ac9776b49..1aab98ad9 100644 --- a/app/routes.py +++ b/app/routes.py @@ -33,12 +33,7 @@ def to_dict(self): def handle_planets(): planets_response = [] for planet in planets: - planets_response.append(dict( - id=planet.id, - name=planet.name, - description=planet.description, - gravity=planet.gravity - )) + planets_response.append(planet.to_dict()) return jsonify(planets_response) From ca9dd4d377dfc30645f021cde0869ec59f646f34 Mon Sep 17 00:00:00 2001 From: olive Date: Tue, 26 Apr 2022 16:18:00 -0500 Subject: [PATCH 05/19] refactored handle_planets with list comprehension --- app/routes.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/app/routes.py b/app/routes.py index 1aab98ad9..863dcab89 100644 --- a/app/routes.py +++ b/app/routes.py @@ -31,9 +31,7 @@ def to_dict(self): @planets_bp.route("", methods = ["GET"]) def handle_planets(): - planets_response = [] - for planet in planets: - planets_response.append(planet.to_dict()) + planets_response = [planet.to_dict() for planet in planets] return jsonify(planets_response) @@ -45,7 +43,6 @@ def validate_planet(id): for planet in planets: if planet.id == id: - # return the planet return planet # no planet found From 11776263a201863dfcd956e3b825027b6acccb27 Mon Sep 17 00:00:00 2001 From: olive Date: Tue, 26 Apr 2022 16:19:28 -0500 Subject: [PATCH 06/19] added comment for consistency --- app/routes.py | 1 + 1 file changed, 1 insertion(+) diff --git a/app/routes.py b/app/routes.py index 863dcab89..69911b12a 100644 --- a/app/routes.py +++ b/app/routes.py @@ -29,6 +29,7 @@ def to_dict(self): planets_bp = Blueprint("planets_bp", __name__, url_prefix="/planets") +# GET /planets @planets_bp.route("", methods = ["GET"]) def handle_planets(): planets_response = [planet.to_dict() for planet in planets] From 12928663a4e28162c25e9d841a0b51534257afe1 Mon Sep 17 00:00:00 2001 From: Adriana Gutierrez Date: Tue, 3 May 2022 14:21:30 -0400 Subject: [PATCH 07/19] created database, linked Planet model, linked database --- app/__init__.py | 12 +++ app/models/__init__.py | 0 app/models/planet.py | 16 ++++ app/routes.py | 92 +++++++++++------- migrations/README | 1 + migrations/alembic.ini | 45 +++++++++ migrations/env.py | 96 +++++++++++++++++++ migrations/script.py.mako | 24 +++++ .../047ba3167dcc_adds_planet_model.py | 34 +++++++ 9 files changed, 284 insertions(+), 36 deletions(-) create mode 100644 app/models/__init__.py create mode 100644 app/models/planet.py create mode 100644 migrations/README create mode 100644 migrations/alembic.ini create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/047ba3167dcc_adds_planet_model.py diff --git a/app/__init__.py b/app/__init__.py index ab9eee40e..6a2469bb5 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,9 +1,21 @@ from flask import Flask +from flask_sqlalchemy import SQLAlchemy +from flask_migrate import Migrate +db = SQLAlchemy() +migrate = Migrate() def create_app(test_config=None): app = Flask(__name__) + app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False + app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system_development' + + from app.models.planet import Planet + + db.init_app(app) + migrate.init_app(app, db) + from .routes import planets_bp app.register_blueprint(planets_bp) diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/app/models/planet.py b/app/models/planet.py new file mode 100644 index 000000000..38c0c13be --- /dev/null +++ b/app/models/planet.py @@ -0,0 +1,16 @@ +from app import db + +class Planet(db.Model): + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + name = db.Column(db.String, nullable=False) + description = db.Column(db.String, nullable=False) + gravity = db.Column(db.Float, nullable=False) + + def to_dict(self): + planet_dict = dict( + id = self.id, + name = self.name, + description = self.description, + gravity = self.gravity + ) + return planet_dict \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 69911b12a..4dd87d588 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,53 +1,73 @@ -from flask import Blueprint, jsonify, abort, make_response - -class Planet: - def __init__(self, id, name, description, gravity): - self.id = id - self.name = name - self.description = description - self.gravity = gravity - - def to_dict(self): - return dict( - id=self.id, - name=self.name, - description=self.description, - gravity=self.gravity, - ) +from app import db +from app.models.planet import Planet +from flask import Blueprint, jsonify, abort, make_response, request + +# class Planet: +# def __init__(self, id, name, description, gravity): +# self.id = id +# self.name = name +# self.description = description +# self.gravity = gravity + +# def to_dict(self): +# return dict( +# id=self.id, +# name=self.name, +# description=self.description, +# gravity=self.gravity, +# ) -planets = [ - Planet(1, "Mercury", "Smallest and closest to sun", 3.7), - Planet(2, "Venus", "Brightest object in the Earth's night sky", 8.8), - Planet(3, "Earth", "Big blue ball, lots of water", 9.8), - Planet(4, "Mars", "Baren red rock", 3.7), - Planet(5, "Jupiter", "Enormous gas giant", 24.8), - Planet(6, "Saturn", "Pretty rings", 10.4), - Planet(7, "Uranus", "Unfortunately named", 8.9), - Planet(8, "Neptune", "Smallest gas giant", 11.2), - Planet(9, "Pluto", "Not really a planet", 0.6) -] +# planets = [ +# Planet(1, "Mercury", "Smallest and closest to sun", 3.7), +# Planet(2, "Venus", "Brightest object in the Earth's night sky", 8.8), +# Planet(3, "Earth", "Big blue ball, lots of water", 9.8), +# Planet(4, "Mars", "Baren red rock", 3.7), +# Planet(5, "Jupiter", "Enormous gas giant", 24.8), +# Planet(6, "Saturn", "Pretty rings", 10.4), +# Planet(7, "Uranus", "Unfortunately named", 8.9), +# Planet(8, "Neptune", "Smallest gas giant", 11.2), +# Planet(9, "Pluto", "Not really a planet", 0.6) +# ] planets_bp = Blueprint("planets_bp", __name__, url_prefix="/planets") # GET /planets @planets_bp.route("", methods = ["GET"]) -def handle_planets(): - planets_response = [planet.to_dict() for planet in planets] +def read_all_planets(): + all_planets = Planet.query.all() + result_list = [planet.to_dict() for planet in all_planets] - return jsonify(planets_response) + return make_response(jsonify(result_list), 200) -def validate_planet(id): +def get_valid_planet(id): try: id = int(id) except ValueError: abort(make_response(jsonify(dict(details=f"invalid id: {id}")), 400)) - for planet in planets: - if planet.id == id: - return planet + planet = Planet.query.get(id) + + if not planet: + abort(make_response(jsonify(dict(details=f"planet id {id} not found")), 404)) + + return planet + +@planets_bp.route("", methods=["POST"]) +def create_planet(): + request_body = request.get_json() + if "name" and "description" and "gravity" not in request_body: + return make_response(f"Invalid request", 400) + + new_planet = Planet(name=request_body["name"], + description=request_body["description"], + gravity=request_body["gravity"] + ) + + db.session.add(new_planet) + db.session.commit() + + return make_response(f"Planet {new_planet.name} successfully created", 201) - # no planet found - abort(make_response(jsonify(dict(details=f"planet id {id} not found")), 404)) # GET /planets/id @planets_bp.route("/", methods=("GET",)) diff --git a/migrations/README b/migrations/README new file mode 100644 index 000000000..98e4f9c44 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 000000000..f8ed4801f --- /dev/null +++ b/migrations/alembic.ini @@ -0,0 +1,45 @@ +# A generic, single database configuration. + +[alembic] +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 000000000..8b3fb3353 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,96 @@ +from __future__ import with_statement + +import logging +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool +from flask import current_app + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) +logger = logging.getLogger('alembic.env') + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +config.set_main_option( + 'sqlalchemy.url', + str(current_app.extensions['migrate'].db.engine.url).replace('%', '%%')) +target_metadata = current_app.extensions['migrate'].db.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, target_metadata=target_metadata, literal_binds=True + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + # this callback is used to prevent an auto-migration from being generated + # when there are no changes to the schema + # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html + def process_revision_directives(context, revision, directives): + if getattr(config.cmd_opts, 'autogenerate', False): + script = directives[0] + if script.upgrade_ops.is_empty(): + directives[:] = [] + logger.info('No changes in schema detected.') + + connectable = engine_from_config( + config.get_section(config.config_ini_section), + prefix='sqlalchemy.', + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=target_metadata, + process_revision_directives=process_revision_directives, + **current_app.extensions['migrate'].configure_args + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 000000000..2c0156303 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,24 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} diff --git a/migrations/versions/047ba3167dcc_adds_planet_model.py b/migrations/versions/047ba3167dcc_adds_planet_model.py new file mode 100644 index 000000000..20f778e72 --- /dev/null +++ b/migrations/versions/047ba3167dcc_adds_planet_model.py @@ -0,0 +1,34 @@ +"""adds Planet model + +Revision ID: 047ba3167dcc +Revises: +Create Date: 2022-05-03 13:52:22.875338 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '047ba3167dcc' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('planet', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('description', sa.String(), nullable=False), + sa.Column('gravity', sa.Float(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('planet') + # ### end Alembic commands ### From 05900c5e6e8e1fccbd5cca034a8bf0fa272b8adf Mon Sep 17 00:00:00 2001 From: Adriana Gutierrez Date: Tue, 3 May 2022 14:35:19 -0400 Subject: [PATCH 08/19] waves 3 and 4 completed --- app/routes.py | 52 ++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 41 insertions(+), 11 deletions(-) diff --git a/app/routes.py b/app/routes.py index 4dd87d588..3d17dcf7e 100644 --- a/app/routes.py +++ b/app/routes.py @@ -31,14 +31,6 @@ planets_bp = Blueprint("planets_bp", __name__, url_prefix="/planets") -# GET /planets -@planets_bp.route("", methods = ["GET"]) -def read_all_planets(): - all_planets = Planet.query.all() - result_list = [planet.to_dict() for planet in all_planets] - - return make_response(jsonify(result_list), 200) - def get_valid_planet(id): try: id = int(id) @@ -52,6 +44,17 @@ def get_valid_planet(id): return planet + +# GET /planets +@planets_bp.route("", methods = ["GET"]) +def read_all_planets(): + all_planets = Planet.query.all() + result_list = [planet.to_dict() for planet in all_planets] + + return make_response(jsonify(result_list), 200) + + +# CREATE /planets @planets_bp.route("", methods=["POST"]) def create_planet(): request_body = request.get_json() @@ -71,6 +74,33 @@ def create_planet(): # GET /planets/id @planets_bp.route("/", methods=("GET",)) -def get_planet(id): - planet = validate_planet(id) - return jsonify(planet.to_dict()) +def read_planet_by_id(id): + planet = get_valid_planet(id) + return make_response(jsonify(planet.to_dict()), 200) + +# UPDATE /planets/id +@planets_bp.route("/", methods=["PUT"]) +def update_planet_by_id(id): + planet = get_valid_planet(id) + request_body = request.get_json() + + if "name" and "description" and "gravity" not in request_body: + return make_response(f"Invalid request", 400) + + planet.name = request_body["name"] + planet.description = request_body["description"] + planet.gravity=request_body["gravity"] + + db.session.commit() + + return make_response(f"Planet #{planet.id} successfully updated. \ + Planet: {planet.to_dict()}", 200) + +@planets_bp.route("/", methods = ["DELETE"]) +def delete_planet_by_id(id): + planet = get_valid_planet(id) + + db.session.delete(planet) + db.session.commit() + + return make_response(f"Planet #{planet.id} successfully deleted.") \ No newline at end of file From 07019d184e8ce6e09a04ebaff7a4fff4a5eaca6b Mon Sep 17 00:00:00 2001 From: olive Date: Thu, 5 May 2022 11:29:23 -0500 Subject: [PATCH 09/19] jsonify all responses --- app/routes.py | 47 ++++++++++++++++------------------------------- 1 file changed, 16 insertions(+), 31 deletions(-) diff --git a/app/routes.py b/app/routes.py index 3d17dcf7e..271ca6a8d 100644 --- a/app/routes.py +++ b/app/routes.py @@ -2,33 +2,6 @@ from app.models.planet import Planet from flask import Blueprint, jsonify, abort, make_response, request -# class Planet: -# def __init__(self, id, name, description, gravity): -# self.id = id -# self.name = name -# self.description = description -# self.gravity = gravity - -# def to_dict(self): -# return dict( -# id=self.id, -# name=self.name, -# description=self.description, -# gravity=self.gravity, -# ) - -# planets = [ -# Planet(1, "Mercury", "Smallest and closest to sun", 3.7), -# Planet(2, "Venus", "Brightest object in the Earth's night sky", 8.8), -# Planet(3, "Earth", "Big blue ball, lots of water", 9.8), -# Planet(4, "Mars", "Baren red rock", 3.7), -# Planet(5, "Jupiter", "Enormous gas giant", 24.8), -# Planet(6, "Saturn", "Pretty rings", 10.4), -# Planet(7, "Uranus", "Unfortunately named", 8.9), -# Planet(8, "Neptune", "Smallest gas giant", 11.2), -# Planet(9, "Pluto", "Not really a planet", 0.6) -# ] - planets_bp = Blueprint("planets_bp", __name__, url_prefix="/planets") def get_valid_planet(id): @@ -69,7 +42,7 @@ def create_planet(): db.session.add(new_planet) db.session.commit() - return make_response(f"Planet {new_planet.name} successfully created", 201) + return make_response(jsonify(f"Planet {new_planet.name} successfully created", 201)) # GET /planets/id @@ -93,8 +66,8 @@ def update_planet_by_id(id): db.session.commit() - return make_response(f"Planet #{planet.id} successfully updated. \ - Planet: {planet.to_dict()}", 200) + return make_response(jsonify(f"Planet #{planet.id} successfully updated. \ + Planet: {planet.to_dict()}", 200)) @planets_bp.route("/", methods = ["DELETE"]) def delete_planet_by_id(id): @@ -103,4 +76,16 @@ def delete_planet_by_id(id): db.session.delete(planet) db.session.commit() - return make_response(f"Planet #{planet.id} successfully deleted.") \ No newline at end of file + return make_response(jsonify(f"Planet #{planet.id} successfully deleted.",200)) + +# planets = [ +# Planet(1, "Mercury", "Smallest and closest to sun", 3.7), +# Planet(2, "Venus", "Brightest object in the Earth's night sky", 8.8), +# Planet(3, "Earth", "Big blue ball, lots of water", 9.8), +# Planet(4, "Mars", "Baren red rock", 3.7), +# Planet(5, "Jupiter", "Enormous gas giant", 24.8), +# Planet(6, "Saturn", "Pretty rings", 10.4), +# Planet(7, "Uranus", "Unfortunately named", 8.9), +# Planet(8, "Neptune", "Smallest gas giant", 11.2), +# Planet(9, "Pluto", "Not really a planet", 0.6) +# ] From 6fac3a6667c5e912ac3253fa16b240baaf3436c5 Mon Sep 17 00:00:00 2001 From: olive Date: Thu, 5 May 2022 13:01:11 -0500 Subject: [PATCH 10/19] midway refactoring --- app/models/planet.py | 15 ++++++++++- app/routes.py | 60 ++++++++++++++++++++++++-------------------- 2 files changed, 47 insertions(+), 28 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index 38c0c13be..9076628c7 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -13,4 +13,17 @@ def to_dict(self): description = self.description, gravity = self.gravity ) - return planet_dict \ No newline at end of file + return planet_dict + + @classmethod + def from_dict(cls, data_dict): + return cls( + name = data_dict["name"], + description = data_dict["description"], + gravity = data_dict["gravity"] + ) + + def replace_details(self, data_dict): + self.name = data_dict["name"] + self.description = data_dict["description"] + self.gravity = data_dict["gravity"] \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 271ca6a8d..931981a35 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,68 +1,74 @@ from app import db from app.models.planet import Planet from flask import Blueprint, jsonify, abort, make_response, request +from .routes_helper import error_message planets_bp = Blueprint("planets_bp", __name__, url_prefix="/planets") -def get_valid_planet(id): +def make_planet_safely(data_dict): try: - id = int(id) - except ValueError: - abort(make_response(jsonify(dict(details=f"invalid id: {id}")), 400)) + return Planet.from_dict(data_dict) + except KeyError as err: + error_message(f"Missing key: {err}", 400) - planet = Planet.query.get(id) +def replace_planet_safely(planet, data_dict): + try: + planet.replace_details(data_dict) + except KeyError as err: + error_message(f"Missing key: {err}", 400) + + # planet = Planet.query.get(id) - if not planet: - abort(make_response(jsonify(dict(details=f"planet id {id} not found")), 404)) + # if not planet: + # abort(make_response(jsonify(dict(details=f"planet id {id} not found")), 404)) - return planet + # return planet # GET /planets @planets_bp.route("", methods = ["GET"]) def read_all_planets(): - all_planets = Planet.query.all() - result_list = [planet.to_dict() for planet in all_planets] + name_param = request.args.get("name") + + if name_param: + planets = Planet.query.filter_by(name=name_param) + else: + planets = Planet.query.all() - return make_response(jsonify(result_list), 200) + result_list = [planet.to_dict() for planet in planets] + + return jsonify(result_list) # CREATE /planets @planets_bp.route("", methods=["POST"]) def create_planet(): request_body = request.get_json() - if "name" and "description" and "gravity" not in request_body: - return make_response(f"Invalid request", 400) + # if "name" and "description" and "gravity" not in request_body: + # return make_response(f"Invalid request", 400) + planet = make_planet_safely(request_body) - new_planet = Planet(name=request_body["name"], - description=request_body["description"], - gravity=request_body["gravity"] - ) - db.session.add(new_planet) + db.session.add(planet) db.session.commit() - return make_response(jsonify(f"Planet {new_planet.name} successfully created", 201)) + return jsonify(f"Planet {planet.name} successfully created"), 201 # GET /planets/id @planets_bp.route("/", methods=("GET",)) def read_planet_by_id(id): - planet = get_valid_planet(id) - return make_response(jsonify(planet.to_dict()), 200) + planet = get_planet_record_by_id(id) + return jsonify(planet.to_dict()) # UPDATE /planets/id @planets_bp.route("/", methods=["PUT"]) def update_planet_by_id(id): - planet = get_valid_planet(id) + planet = get_planet_record_by_id(id) request_body = request.get_json() - if "name" and "description" and "gravity" not in request_body: - return make_response(f"Invalid request", 400) + replace_planet_safely(planet, request_body) - planet.name = request_body["name"] - planet.description = request_body["description"] - planet.gravity=request_body["gravity"] db.session.commit() From d9e2eb6f80b0d8a0ddef3b2b73f8fddbe546ac15 Mon Sep 17 00:00:00 2001 From: Adriana Gutierrez Date: Thu, 5 May 2022 16:06:15 -0400 Subject: [PATCH 11/19] completed refactoring and routes --- app/__init__.py | 2 +- app/{ => routes}/routes.py | 54 +++++++++++++++++++++++++------------ app/routes/routes_helper.py | 4 +++ 3 files changed, 42 insertions(+), 18 deletions(-) rename app/{ => routes}/routes.py (64%) create mode 100644 app/routes/routes_helper.py diff --git a/app/__init__.py b/app/__init__.py index 6a2469bb5..669de5c49 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -16,7 +16,7 @@ def create_app(test_config=None): db.init_app(app) migrate.init_app(app, db) - from .routes import planets_bp + from .routes.routes import planets_bp app.register_blueprint(planets_bp) return app diff --git a/app/routes.py b/app/routes/routes.py similarity index 64% rename from app/routes.py rename to app/routes/routes.py index 931981a35..b380216fa 100644 --- a/app/routes.py +++ b/app/routes/routes.py @@ -17,26 +17,33 @@ def replace_planet_safely(planet, data_dict): except KeyError as err: error_message(f"Missing key: {err}", 400) - # planet = Planet.query.get(id) - - # if not planet: - # abort(make_response(jsonify(dict(details=f"planet id {id} not found")), 404)) +def get_planet_record_by_id(id): + try: + id = int(id) + except ValueError: + error_message(f"Invalid id {id}", 400) - # return planet + planet = Planet.query.get(id) + if planet: + return planet + + error_message(f"No planet with id {id} found", 404) # GET /planets @planets_bp.route("", methods = ["GET"]) def read_all_planets(): - name_param = request.args.get("name") + name_param = request.args.get("name").capitalize() if name_param: planets = Planet.query.filter_by(name=name_param) + else: planets = Planet.query.all() result_list = [planet.to_dict() for planet in planets] - + if not result_list: + return jsonify(f"No planet found with name {name_param}"), 404 return jsonify(result_list) @@ -44,11 +51,9 @@ def read_all_planets(): @planets_bp.route("", methods=["POST"]) def create_planet(): request_body = request.get_json() - # if "name" and "description" and "gravity" not in request_body: - # return make_response(f"Invalid request", 400) + planet = make_planet_safely(request_body) - db.session.add(planet) db.session.commit() @@ -63,26 +68,41 @@ def read_planet_by_id(id): # UPDATE /planets/id @planets_bp.route("/", methods=["PUT"]) -def update_planet_by_id(id): +def replace_planet_by_id(id): planet = get_planet_record_by_id(id) request_body = request.get_json() - replace_planet_safely(planet, request_body) + replace_planet_safely(planet, request_body) - db.session.commit() - return make_response(jsonify(f"Planet #{planet.id} successfully updated. \ - Planet: {planet.to_dict()}", 200)) + return jsonify(f"Planet #{planet.id} successfully updated. \ + Planet: {planet.to_dict()}") @planets_bp.route("/", methods = ["DELETE"]) def delete_planet_by_id(id): - planet = get_valid_planet(id) + planet = get_planet_record_by_id(id) db.session.delete(planet) db.session.commit() - return make_response(jsonify(f"Planet #{planet.id} successfully deleted.",200)) + return jsonify(f"Planet #{planet.id} successfully deleted.") + +@planets_bp.route("/", methods = ["PATCH"]) +def update_planet_with_id(id): + planet = get_planet_record_by_id(id) + request_body = request.get_json() + planet_keys = request_body.keys() + + if "name" in planet_keys: + planet.name = request_body["name"] + if "description" in planet_keys: + planet.description = request_body["description"] + if "gravity" in planet_keys: + planet.gravity = request_body["gravity"] + + db.session.commit() + return jsonify(planet.to_dict()) # planets = [ # Planet(1, "Mercury", "Smallest and closest to sun", 3.7), diff --git a/app/routes/routes_helper.py b/app/routes/routes_helper.py new file mode 100644 index 000000000..4482f0442 --- /dev/null +++ b/app/routes/routes_helper.py @@ -0,0 +1,4 @@ +from flask import jsonify, abort, make_response + +def error_message(message, status_code): + abort(make_response(jsonify(dict(details=message)), status_code)) \ No newline at end of file From 1b45591ba6d2443059e23621a3a71db42de19c24 Mon Sep 17 00:00:00 2001 From: olive Date: Thu, 5 May 2022 15:36:54 -0500 Subject: [PATCH 12/19] moved capitalize() in read_all_planets function to avoid Nonetype Error --- app/routes/routes.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/app/routes/routes.py b/app/routes/routes.py index b380216fa..a4293f19b 100644 --- a/app/routes/routes.py +++ b/app/routes/routes.py @@ -33,15 +33,16 @@ def get_planet_record_by_id(id): # GET /planets @planets_bp.route("", methods = ["GET"]) def read_all_planets(): - name_param = request.args.get("name").capitalize() + name_param = request.args.get("name") if name_param: - planets = Planet.query.filter_by(name=name_param) + planets = Planet.query.filter_by(name=name_param.capitalize()) else: planets = Planet.query.all() result_list = [planet.to_dict() for planet in planets] + if not result_list: return jsonify(f"No planet found with name {name_param}"), 404 return jsonify(result_list) From 21836267c41f38712fdb8ba77f1f485cfe09b83c Mon Sep 17 00:00:00 2001 From: Adriana Gutierrez Date: Thu, 5 May 2022 17:13:24 -0400 Subject: [PATCH 13/19] set up test environment --- app/__init__.py | 43 ++++++++++++++++++++++++++++++++++++++----- 1 file changed, 38 insertions(+), 5 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 669de5c49..7d181d893 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,22 +1,55 @@ +# from flask import Flask +# from flask_sqlalchemy import SQLAlchemy +# from flask_migrate import Migrate + +# db = SQLAlchemy() +# migrate = Migrate() + +# def create_app(test_config=None): +# app = Flask(__name__) + +# app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False +# app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system_development' + +# from app.models.planet import Planet + +# db.init_app(app) +# migrate.init_app(app, db) + +# from .routes.routes import planets_bp +# app.register_blueprint(planets_bp) + +# return app + from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate +from dotenv import load_dotenv +import os db = SQLAlchemy() migrate = Migrate() +load_dotenv() def create_app(test_config=None): app = Flask(__name__) - app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False - app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system_development' - - from app.models.planet import Planet + if not test_config: + app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get( + "SQLALCHEMY_DATABASE_URI") + else: + app.config["TESTING"] = True + app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False + app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( + "SQLALCHEMY_TEST_DATABASE_URI") db.init_app(app) migrate.init_app(app, db) + from app.models.planet import Planet + from .routes.routes import planets_bp app.register_blueprint(planets_bp) - return app + return app \ No newline at end of file From bdfdcd7def13a6fe6bc32fe1658dec3a4b05b69b Mon Sep 17 00:00:00 2001 From: olive Date: Thu, 5 May 2022 16:41:02 -0500 Subject: [PATCH 14/19] added test folder --- tests/__init__.py | 0 tests/conftest.py | 0 tests/test_routes.py | 0 3 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 tests/__init__.py create mode 100644 tests/conftest.py create mode 100644 tests/test_routes.py diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/test_routes.py b/tests/test_routes.py new file mode 100644 index 000000000..e69de29bb From 69e40892467827dab3dae88fa7e5f6ee5d244c4b Mon Sep 17 00:00:00 2001 From: Adriana Gutierrez Date: Thu, 5 May 2022 17:44:13 -0400 Subject: [PATCH 15/19] set up tests --- tests/conftest.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/tests/conftest.py b/tests/conftest.py index e69de29bb..96d35f4c1 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -0,0 +1,25 @@ +import pytest +from app import create_app +from app import db +from flask.signals import request_finished + + +@pytest.fixture +def app(): + app = create_app({"TESTING": True}) + + @request_finished.connect_via(app) + def expire_session(sender, response, **extra): + db.session.remove() + + with app.app_context(): + db.create_all() + yield app + + with app.app_context(): + db.drop_all() + + +@pytest.fixture +def client(app): + return app.test_client() From 988bd6ed13e881a9ea73cac92d8777219e49c3a2 Mon Sep 17 00:00:00 2001 From: Adriana Gutierrez Date: Thu, 5 May 2022 18:15:53 -0400 Subject: [PATCH 16/19] wave06 complete --- app/routes/routes.py | 2 +- tests/conftest.py | 14 +++++++++ tests/test_routes.py | 68 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 83 insertions(+), 1 deletion(-) diff --git a/app/routes/routes.py b/app/routes/routes.py index a4293f19b..bf186e782 100644 --- a/app/routes/routes.py +++ b/app/routes/routes.py @@ -44,7 +44,7 @@ def read_all_planets(): result_list = [planet.to_dict() for planet in planets] if not result_list: - return jsonify(f"No planet found with name {name_param}"), 404 + return jsonify("No planets found with that name."), 200 return jsonify(result_list) diff --git a/tests/conftest.py b/tests/conftest.py index 96d35f4c1..fdff7dc9f 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -2,6 +2,7 @@ from app import create_app from app import db from flask.signals import request_finished +from app.models.planet import Planet @pytest.fixture @@ -23,3 +24,16 @@ def expire_session(sender, response, **extra): @pytest.fixture def client(app): return app.test_client() + +@pytest.fixture +def two_saved_planets(app): + # Arrange + mercury = Planet(name="Mercury", + description="Mercury's description", + gravity=2) + venus = Planet(name="Venus", + description="A riveting description of Venus.", + gravity=3.1) + + db.session.add_all([mercury, venus]) + db.session.commit() \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py index e69de29bb..f369abe8f 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -0,0 +1,68 @@ +def test_get_all_planets_with_no_records(client): + # Act + response = client.get("/planets") + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert response_body == "No planets found with that name." + +def test_get_one_planet(client, two_saved_planets): + # Act + response = client.get("/planets/1") + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert response_body == { + "id":1, + "name":"Mercury", + "description":"Mercury's description", + "gravity":2 + } + +def test_get_one_planet_no_data(client): + # Act + response = client.get("/planets/1") + response_body = response.get_json() + + # Assert + assert response.status_code == 404 + assert response_body["details"] == "No planet with id 1 found" + +def test_get_all_planets_with_valid_records(client, two_saved_planets): + # Act + response = client.get("/planets") + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert response_body == [ + { + "description": "Mercury's description", + "gravity": 2, + "id": 1, + "name": "Mercury" + }, + { + "description": "A riveting description of Venus.", + "gravity": 3.1, + "id": 2, + "name": "Venus" + } + ] + +def test_create_one_planet(client): + # Act + response = client.post("/planets", json={ + "description": "Mercury's description", + "gravity": 2, + "id": 1, + "name": "Mercury" + }) + response_body = response.get_json() + + # Assert + assert response.status_code == 201 + assert response_body == "Planet Mercury successfully created" + \ No newline at end of file From 7d8ea775214d935e84bd59a095c8b5af28bf682a Mon Sep 17 00:00:00 2001 From: olive Date: Fri, 6 May 2022 10:32:10 -0500 Subject: [PATCH 17/19] removed commented out code --- app/__init__.py | 23 ----------------------- app/routes/routes.py | 11 ----------- 2 files changed, 34 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 7d181d893..7e167094f 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,26 +1,3 @@ -# from flask import Flask -# from flask_sqlalchemy import SQLAlchemy -# from flask_migrate import Migrate - -# db = SQLAlchemy() -# migrate = Migrate() - -# def create_app(test_config=None): -# app = Flask(__name__) - -# app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False -# app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system_development' - -# from app.models.planet import Planet - -# db.init_app(app) -# migrate.init_app(app, db) - -# from .routes.routes import planets_bp -# app.register_blueprint(planets_bp) - -# return app - from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate diff --git a/app/routes/routes.py b/app/routes/routes.py index bf186e782..6f478deac 100644 --- a/app/routes/routes.py +++ b/app/routes/routes.py @@ -105,14 +105,3 @@ def update_planet_with_id(id): db.session.commit() return jsonify(planet.to_dict()) -# planets = [ -# Planet(1, "Mercury", "Smallest and closest to sun", 3.7), -# Planet(2, "Venus", "Brightest object in the Earth's night sky", 8.8), -# Planet(3, "Earth", "Big blue ball, lots of water", 9.8), -# Planet(4, "Mars", "Baren red rock", 3.7), -# Planet(5, "Jupiter", "Enormous gas giant", 24.8), -# Planet(6, "Saturn", "Pretty rings", 10.4), -# Planet(7, "Uranus", "Unfortunately named", 8.9), -# Planet(8, "Neptune", "Smallest gas giant", 11.2), -# Planet(9, "Pluto", "Not really a planet", 0.6) -# ] From 82598201464ba659f83e2fc3cdcc21642216d68f Mon Sep 17 00:00:00 2001 From: olive Date: Fri, 6 May 2022 10:39:33 -0500 Subject: [PATCH 18/19] final --- app/routes/routes.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/routes/routes.py b/app/routes/routes.py index 6f478deac..e62137baa 100644 --- a/app/routes/routes.py +++ b/app/routes/routes.py @@ -44,7 +44,7 @@ def read_all_planets(): result_list = [planet.to_dict() for planet in planets] if not result_list: - return jsonify("No planets found with that name."), 200 + return jsonify("No planets found with that name.") return jsonify(result_list) From 5c9b9e8d2b419958854e17116ce383106658faff Mon Sep 17 00:00:00 2001 From: olive Date: Wed, 11 May 2022 12:40:40 -0500 Subject: [PATCH 19/19] added Procfile --- Procfile | 1 + requirements.txt | 8 ++++++++ 2 files changed, 9 insertions(+) create mode 100644 Procfile diff --git a/Procfile b/Procfile new file mode 100644 index 000000000..62e430aca --- /dev/null +++ b/Procfile @@ -0,0 +1 @@ +web: gunicorn 'app:create_app()' \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index a506b4d12..db5708086 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,19 +1,27 @@ alembic==1.5.4 +attrs==21.4.0 autopep8==1.5.5 blinker==1.4 certifi==2020.12.5 chardet==4.0.0 click==7.1.2 +coverage==6.3.2 Flask==1.1.2 Flask-Migrate==2.6.0 Flask-SQLAlchemy==2.4.4 +gunicorn==20.1.0 idna==2.10 +iniconfig==1.1.1 itsdangerous==1.1.0 Jinja2==2.11.3 Mako==1.1.4 MarkupSafe==1.1.1 +packaging==21.3 +pluggy==0.13.1 psycopg2-binary==2.8.6 +py==1.11.0 pycodestyle==2.6.0 +pyparsing==3.0.9 pytest==6.2.3 pytest-cov==2.12.1 python-dateutil==2.8.1