From 79db9c62349034e1263d814654f17d07547ab158 Mon Sep 17 00:00:00 2001 From: Reyna Diaz Date: Mon, 24 Oct 2022 14:47:30 -0400 Subject: [PATCH 01/23] "adds wave 01 class + list" --- app/routes.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..0e8b108fc 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,15 @@ from flask import Blueprint +class Planet: + + def __init__(self, id, name, description, moons): + self.id = id + self.name = name + self.description = description + self.moons = moons + +planets = [ + Planet(1, "Earth", "our home", 1), + Planet(2, "Mars", "red planet", 2), + Planet(3, "Pluto", "is a planet", 5) +] From 51d85d03f7f9411a0b8b75f3e017967490acbe06 Mon Sep 17 00:00:00 2001 From: Reyna Diaz Date: Mon, 24 Oct 2022 15:00:22 -0400 Subject: [PATCH 02/23] "wave 01 created RESTful endpoint, registered bp" --- app/__init__.py | 3 +++ app/routes.py | 2 ++ 2 files changed, 5 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 0e8b108fc..89195e208 100644 --- a/app/routes.py +++ b/app/routes.py @@ -13,3 +13,5 @@ def __init__(self, id, name, description, moons): Planet(2, "Mars", "red planet", 2), Planet(3, "Pluto", "is a planet", 5) ] + +planets_bp = Blueprint("planets", __name__, url_prefix="/planets") \ No newline at end of file From 8c7d6b250aa754b29b72bfc512f4518e17686bc8 Mon Sep 17 00:00:00 2001 From: Reyna Diaz Date: Mon, 24 Oct 2022 15:07:58 -0400 Subject: [PATCH 03/23] "wave 01 added handle_planets() funct" --- app/routes.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/app/routes.py b/app/routes.py index 89195e208..b8e62756a 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,4 +1,5 @@ -from flask import Blueprint +from unicodedata import name +from flask import Blueprint, jsonify class Planet: @@ -14,4 +15,16 @@ def __init__(self, id, name, description, moons): Planet(3, "Pluto", "is a planet", 5) ] -planets_bp = Blueprint("planets", __name__, url_prefix="/planets") \ No newline at end of file +planets_bp = Blueprint("planets", __name__, url_prefix="/planets") + +@planets_bp.route("", methods=["GET"]) +def handle_planets(): + planets_response = [] + for planet in planets: + planets_response.append({ + "id": planet.id, + "name": planet.name, + "description": planet.description, + "moons": planet.moons + }) + return jsonify(planets_response) \ No newline at end of file From c20d81bfd05b7ed483d583abf23dd69f14abae46 Mon Sep 17 00:00:00 2001 From: mc-dev99 Date: Tue, 25 Oct 2022 16:44:28 -0400 Subject: [PATCH 04/23] Wave 02 added validate_planet and endpoint for returning single planet --- app/routes.py | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/app/routes.py b/app/routes.py index b8e62756a..55ba7923a 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,5 +1,5 @@ from unicodedata import name -from flask import Blueprint, jsonify +from flask import Blueprint, jsonify, abort, make_response class Planet: @@ -27,4 +27,27 @@ def handle_planets(): "description": planet.description, "moons": planet.moons }) - return jsonify(planets_response) \ No newline at end of file + return jsonify(planets_response) + +def validate_planet(planet_id): + try: + planet_id = int(planet_id) + except: + abort(make_response({"message": f"planet {planet_id} is invalid"}, 400)) + + for planet in planets: + if planet.id == int(planet_id): + return planet + + abort(make_response({"message": f"planet {planet_id} not found"}, 404)) + +@planets_bp.route("/", methods=["GET"]) +def handle_planet(planet_id): + planet = validate_planet(planet_id) + + return { + "id": planet.id, + "name": planet.name, + "description": planet.description, + "moons": planet.moons, + } \ No newline at end of file From f05cdb2d24193cfbb1f96223a7277cf477d81fb6 Mon Sep 17 00:00:00 2001 From: mhc Date: Tue, 1 Nov 2022 13:44:10 -0400 Subject: [PATCH 05/23] created planet.py & __init__.py SQLAlchemy setup --- app/__init__.py | 11 +++++++++++ app/models/__init__.py | 0 app/models/planet.py | 0 3 files changed, 11 insertions(+) create mode 100644 app/models/__init__.py create mode 100644 app/models/planet.py diff --git a/app/__init__.py b/app/__init__.py index ab9eee40e..ce1480222 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,9 +1,20 @@ 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' + + 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..e69de29bb From 06a9613d6bfc234dd3558359cc997f281f9c8e2f Mon Sep 17 00:00:00 2001 From: mhc Date: Tue, 1 Nov 2022 13:46:57 -0400 Subject: [PATCH 06/23] created Planet model --- app/models/planet.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/app/models/planet.py b/app/models/planet.py index e69de29bb..4b822cd0d 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -0,0 +1,7 @@ +from app import db + +class Planet(db.Model): + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + name = db.Column(db.String) + description = db.Column(db.String) + moons = db.Column(db.Integer) \ No newline at end of file From 4bdb3e5fb78308c3487453b4b1b5e19614c2ccc6 Mon Sep 17 00:00:00 2001 From: mhc Date: Tue, 1 Nov 2022 15:38:07 -0400 Subject: [PATCH 07/23] flask db init & initial migration --- migrations/README | 1 + migrations/alembic.ini | 45 ++++++++++++++++++ migrations/env.py | 96 +++++++++++++++++++++++++++++++++++++++ migrations/script.py.mako | 24 ++++++++++ 4 files changed, 166 insertions(+) create mode 100644 migrations/README create mode 100644 migrations/alembic.ini create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako 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"} From a4d794d5cbc1760226ba9b65a1cf30cd7510f628 Mon Sep 17 00:00:00 2001 From: mhc Date: Tue, 1 Nov 2022 15:41:58 -0400 Subject: [PATCH 08/23] correctly imported app.models.planet Planet --- app/__init__.py | 2 ++ .../861a80c043e6_adds_planet_model.py | 34 +++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 migrations/versions/861a80c043e6_adds_planet_model.py diff --git a/app/__init__.py b/app/__init__.py index ce1480222..6322cf4ef 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -15,6 +15,8 @@ def create_app(test_config=None): db.init_app(app) migrate.init_app(app, db) + from app.models.planet import Planet + from .routes import planets_bp app.register_blueprint(planets_bp) diff --git a/migrations/versions/861a80c043e6_adds_planet_model.py b/migrations/versions/861a80c043e6_adds_planet_model.py new file mode 100644 index 000000000..2b29505e9 --- /dev/null +++ b/migrations/versions/861a80c043e6_adds_planet_model.py @@ -0,0 +1,34 @@ +"""adds Planet model + +Revision ID: 861a80c043e6 +Revises: +Create Date: 2022-11-01 15:41:37.575877 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '861a80c043e6' +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=True), + sa.Column('description', sa.String(), nullable=True), + sa.Column('moons', sa.Integer(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('planet') + # ### end Alembic commands ### From f6b32034141149d193332dd371be24ac8be57a09 Mon Sep 17 00:00:00 2001 From: Reyna Diaz Date: Tue, 1 Nov 2022 16:03:03 -0400 Subject: [PATCH 09/23] "added create_planet and read_all_planet routes" --- app/routes.py | 52 +++++++++++++++++++++++++++++++++++------------- solar-system-api | 1 + 2 files changed, 39 insertions(+), 14 deletions(-) create mode 160000 solar-system-api diff --git a/app/routes.py b/app/routes.py index 55ba7923a..224fb8a03 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,25 +1,49 @@ from unicodedata import name -from flask import Blueprint, jsonify, abort, make_response +from flask import Blueprint, jsonify, abort, make_response, request +from app import db +from app.models.planet import Planet -class Planet: +# class Planet: - def __init__(self, id, name, description, moons): - self.id = id - self.name = name - self.description = description - self.moons = moons +# def __init__(self, id, name, description, moons): +# self.id = id +# self.name = name +# self.description = description +# self.moons = moons -planets = [ - Planet(1, "Earth", "our home", 1), - Planet(2, "Mars", "red planet", 2), - Planet(3, "Pluto", "is a planet", 5) -] +# planets = [ +# Planet(1, "Earth", "our home", 1), +# Planet(2, "Mars", "red planet", 2), +# Planet(3, "Pluto", "is a planet", 5) +# ] planets_bp = Blueprint("planets", __name__, url_prefix="/planets") +@planets_bp.route("", methods=["POST"]) +def create_planet(): + if request.method == "POST": + request_body = request.get_json() + if ("name" not in request_body or "description" not in request_body + or "moons" not in request_body): + return make_response(f"Invalid Request", 400) + + new_planet = Planet( + name=request_body["name"], + description=request_body["description"], + moons=request_body["moons"], + ) + + db.session.add(new_planet) + db.session.commit() + + return make_response( + f"Planet {new_planet.name} successfully created", 201 + ) + @planets_bp.route("", methods=["GET"]) -def handle_planets(): +def read_all_planets(): planets_response = [] + planets = Planet.query.all() for planet in planets: planets_response.append({ "id": planet.id, @@ -34,7 +58,7 @@ def validate_planet(planet_id): planet_id = int(planet_id) except: abort(make_response({"message": f"planet {planet_id} is invalid"}, 400)) - + planets = Planet.query.all() for planet in planets: if planet.id == int(planet_id): return planet diff --git a/solar-system-api b/solar-system-api new file mode 160000 index 000000000..c20d81bfd --- /dev/null +++ b/solar-system-api @@ -0,0 +1 @@ +Subproject commit c20d81bfd05b7ed483d583abf23dd69f14abae46 From e9f1eb89537ec6d4d1f9def28def9d90a9b953f1 Mon Sep 17 00:00:00 2001 From: mhc Date: Tue, 1 Nov 2022 16:15:44 -0400 Subject: [PATCH 10/23] refactored validate_planet + added read_one_planet --- app/routes.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/app/routes.py b/app/routes.py index 224fb8a03..8d819a992 100644 --- a/app/routes.py +++ b/app/routes.py @@ -58,15 +58,16 @@ def validate_planet(planet_id): planet_id = int(planet_id) except: abort(make_response({"message": f"planet {planet_id} is invalid"}, 400)) - planets = Planet.query.all() - for planet in planets: - if planet.id == int(planet_id): - return planet - abort(make_response({"message": f"planet {planet_id} not found"}, 404)) + planet = Planet.query.get(planet_id) + + if not planet: + abort(make_response({"message": f"planet {planet_id} not found"}, 404)) + + return planet @planets_bp.route("/", methods=["GET"]) -def handle_planet(planet_id): +def read_one_planet(planet_id): planet = validate_planet(planet_id) return { From 2abef4f116f99817aad9255040858643ed4d8e53 Mon Sep 17 00:00:00 2001 From: mhc Date: Tue, 1 Nov 2022 16:22:49 -0400 Subject: [PATCH 11/23] added update_planet route --- app/routes.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index 8d819a992..871df20f4 100644 --- a/app/routes.py +++ b/app/routes.py @@ -75,4 +75,18 @@ def read_one_planet(planet_id): "name": planet.name, "description": planet.description, "moons": planet.moons, - } \ No newline at end of file + } + +@planets_bp.route("/", methods=["PUT"]) +def update_planet(planet_id): + planet = validate_planet(planet_id) + + request_body = request.get_json() + + planet.name = request_body["name"] + planet.description = request_body["description"] + planet.moons = request_body["moons"] + + db.session.commit() + + return make_response(f"Planet #{planet.id} successfully updated") \ No newline at end of file From 3f3472dcf612fcb8e7d041b3aefca87825596f36 Mon Sep 17 00:00:00 2001 From: Reyna Diaz Date: Tue, 1 Nov 2022 16:28:02 -0400 Subject: [PATCH 12/23] "added delete_planet route" --- app/routes.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index 871df20f4..2a0daa4f9 100644 --- a/app/routes.py +++ b/app/routes.py @@ -89,4 +89,13 @@ def update_planet(planet_id): db.session.commit() - return make_response(f"Planet #{planet.id} successfully updated") \ No newline at end of file + return make_response(f"Planet #{planet.id} successfully updated") + +@planets_bp.route("/", methods=["DELETE"]) +def delete_planet(planet_id): + planet = validate_planet(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 c0c2645cc479012fc5ddf3186188cff2821e1a02 Mon Sep 17 00:00:00 2001 From: Reyna Diaz Date: Wed, 2 Nov 2022 17:25:48 -0400 Subject: [PATCH 13/23] "read_one+read_all funct refactor, adds to_dict()" --- app/models/planet.py | 11 ++++++++++- app/routes.py | 27 ++++++++++++++------------- 2 files changed, 24 insertions(+), 14 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index 4b822cd0d..6ee680dfa 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -4,4 +4,13 @@ class Planet(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String) description = db.Column(db.String) - moons = db.Column(db.Integer) \ No newline at end of file + moons = db.Column(db.Integer) + + + def to_dict(self): + return { + "id": self.id, + "name": self.name, + "description": self.description, + "moons": self.moons + } \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 2a0daa4f9..246ff8f0b 100644 --- a/app/routes.py +++ b/app/routes.py @@ -45,12 +45,13 @@ def read_all_planets(): planets_response = [] planets = Planet.query.all() for planet in planets: - planets_response.append({ - "id": planet.id, - "name": planet.name, - "description": planet.description, - "moons": planet.moons - }) + # planets_response.append({ + # "id": planet.id, + # "name": planet.name, + # "description": planet.description, + # "moons": planet.moons + # }) + planets_response.append(planet.to_dict()) return jsonify(planets_response) def validate_planet(planet_id): @@ -69,13 +70,13 @@ def validate_planet(planet_id): @planets_bp.route("/", methods=["GET"]) def read_one_planet(planet_id): planet = validate_planet(planet_id) - - return { - "id": planet.id, - "name": planet.name, - "description": planet.description, - "moons": planet.moons, - } + return planet.to_dict() + # return { + # "id": planet.id, + # "name": planet.name, + # "description": planet.description, + # "moons": planet.moons, + # } @planets_bp.route("/", methods=["PUT"]) def update_planet(planet_id): From 6abc230d780c6d68accf9724c5856f0d2e2a44b0 Mon Sep 17 00:00:00 2001 From: mhc Date: Wed, 2 Nov 2022 17:37:47 -0400 Subject: [PATCH 14/23] refactored routes, made helper funcs --- app/models/planet.py | 7 +++++++ app/routes.py | 6 +----- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index 6ee680dfa..5e797828f 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -7,6 +7,13 @@ class Planet(db.Model): moons = db.Column(db.Integer) + @classmethod + def from_dict(cls, planet_data): + new_planet = Planet(name=planet_data["name"], + description=planet_data["description"], + moons=planet_data["moons"]) + return new_planet + def to_dict(self): return { "id": self.id, diff --git a/app/routes.py b/app/routes.py index 246ff8f0b..d3e4d5c74 100644 --- a/app/routes.py +++ b/app/routes.py @@ -27,11 +27,7 @@ def create_planet(): or "moons" not in request_body): return make_response(f"Invalid Request", 400) - new_planet = Planet( - name=request_body["name"], - description=request_body["description"], - moons=request_body["moons"], - ) + new_planet = Planet.from_dict(request_body) db.session.add(new_planet) db.session.commit() From 17711c7afc8c73c92aa3c3a32c6b55fcd198f7c4 Mon Sep 17 00:00:00 2001 From: mhc Date: Thu, 3 Nov 2022 13:56:41 -0400 Subject: [PATCH 15/23] refactored validate_planet to validate_model --- app/routes.py | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/app/routes.py b/app/routes.py index d3e4d5c74..b393b52b1 100644 --- a/app/routes.py +++ b/app/routes.py @@ -50,22 +50,22 @@ def read_all_planets(): planets_response.append(planet.to_dict()) return jsonify(planets_response) -def validate_planet(planet_id): +def validate_model(cls, model_id): try: - planet_id = int(planet_id) + model_id = int(model_id) except: - abort(make_response({"message": f"planet {planet_id} is invalid"}, 400)) - - planet = Planet.query.get(planet_id) - - if not planet: - abort(make_response({"message": f"planet {planet_id} not found"}, 404)) - - return planet + abort(make_response({"message":f"{cls.__name__} {model_id} invalid"}, 400)) + + model = cls.query.get(model_id) + + if not model: + abort(make_response({"message":f"{cls.__name__} {model_id} not found"}, 404)) + + return model @planets_bp.route("/", methods=["GET"]) def read_one_planet(planet_id): - planet = validate_planet(planet_id) + planet = validate_model(Planet, planet_id) return planet.to_dict() # return { # "id": planet.id, @@ -76,7 +76,7 @@ def read_one_planet(planet_id): @planets_bp.route("/", methods=["PUT"]) def update_planet(planet_id): - planet = validate_planet(planet_id) + planet = validate_model(Planet, planet_id) request_body = request.get_json() @@ -90,7 +90,7 @@ def update_planet(planet_id): @planets_bp.route("/", methods=["DELETE"]) def delete_planet(planet_id): - planet = validate_planet(planet_id) + planet = validate_model(Planet, planet_id) db.session.delete(planet) db.session.commit() From 72203290dacccfb3ce1501692645443c837a99f5 Mon Sep 17 00:00:00 2001 From: mhc Date: Thu, 3 Nov 2022 14:02:18 -0400 Subject: [PATCH 16/23] modified create_app to handle test mode --- app/__init__.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index 6322cf4ef..4fe5183cc 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,16 +1,24 @@ 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' + + if not test_config: + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("SQLALCHEMY_DATABASE_URI") + else: + app.config["TESTING"] = True + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("SQLALCHEMY_TEST_DATABASE_URI") db.init_app(app) migrate.init_app(app, db) From 09bd95726c03bd742b8a172c2da6220731af2197 Mon Sep 17 00:00:00 2001 From: mhc Date: Thu, 3 Nov 2022 14:07:19 -0400 Subject: [PATCH 17/23] created tests folder, set up conftest.py --- tests/__init__.py | 0 tests/conftest.py | 25 +++++++++++++++++++++++++ tests/test_routes.py | 0 3 files changed, 25 insertions(+) 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..ac8a4193b --- /dev/null +++ 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() \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py new file mode 100644 index 000000000..e69de29bb From 79eed88804e28647ff862e57bd00437c9b25c1f2 Mon Sep 17 00:00:00 2001 From: Reyna Diaz Date: Thu, 3 Nov 2022 14:11:46 -0400 Subject: [PATCH 18/23] "adds test get_all_planets" --- tests/test_routes.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/test_routes.py b/tests/test_routes.py index e69de29bb..ce2210060 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -0,0 +1,6 @@ +def test_get_all_planets_with_no_records(client): + response = client.get("/planets") + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == [] \ No newline at end of file From c56d26f0bc36b176aec4bf7f5c3d200b9cc5adc9 Mon Sep 17 00:00:00 2001 From: Reyna Diaz Date: Thu, 3 Nov 2022 14:27:16 -0400 Subject: [PATCH 19/23] "fixture two_planets + test_by_id + id_not_found" --- tests/conftest.py | 13 ++++++++++++- tests/test_routes.py | 21 ++++++++++++++++++++- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index ac8a4193b..3b5ee1349 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,6 +1,7 @@ import pytest from app import create_app from app import db +from app.models.planet import Planet from flask.signals import request_finished @@ -22,4 +23,14 @@ def expire_session(sender, response, **extra): @pytest.fixture def client(app): - return app.test_client() \ No newline at end of file + return app.test_client() + +@pytest.fixture +def two_saved_planets(app): + big_planet = Planet(name="Jupiter", + description="big planet", moons = 80) + small_planet = Planet(name="Mercury", + description="small planet", moons=0) + + db.session.add_all([big_planet, small_planet]) + db.session.commit() \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py index ce2210060..170dc2c81 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -3,4 +3,23 @@ def test_get_all_planets_with_no_records(client): response_body = response.get_json() assert response.status_code == 200 - assert response_body == [] \ No newline at end of file + assert response_body == [] + +def test_get_planet_by_id(client, two_saved_planets): + response = client.get("planets/1") + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == { + "id":1, + "name": "Jupiter", + "description": "big planet", + "moons": 80 + } + +def test_get_planet_by_id_not_found(client, two_saved_planets): + response = client.get("planets/6") + response_body = response.get_json() + + assert response.status_code == 404 + assert response_body == {"message":f"Planet 6 not found"} \ No newline at end of file From e72a913e1a6087409d0d3d3ed77b478b7cddbabf Mon Sep 17 00:00:00 2001 From: mhc Date: Thu, 3 Nov 2022 14:37:09 -0400 Subject: [PATCH 20/23] added test for get all planets with records & create a planet --- tests/test_routes.py | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/tests/test_routes.py b/tests/test_routes.py index 170dc2c81..4531f70c7 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -5,6 +5,24 @@ def test_get_all_planets_with_no_records(client): assert response.status_code == 200 assert response_body == [] +def test_get_all_planets_with_records(client, two_saved_planets): + response = client.get("/planets") + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == [{ + "id":1, + "name": "Jupiter", + "description": "big planet", + "moons": 80 + }, + { + "id":2, + "name": "Mercury", + "description": "small planet", + "moons": 0 + }] + def test_get_planet_by_id(client, two_saved_planets): response = client.get("planets/1") response_body = response.get_json() @@ -22,4 +40,17 @@ def test_get_planet_by_id_not_found(client, two_saved_planets): response_body = response.get_json() assert response.status_code == 404 - assert response_body == {"message":f"Planet 6 not found"} \ No newline at end of file + assert response_body == {"message": "Planet 6 not found"} + +def test_create_one_planet(client): + # Act + response = client.post("/planets", json={ + "name": "Neptune", + "description": "named after the Roman god of the sea", + "moons": 14 + }) + response_body = response.get_data(as_text=True) + + # Assert + assert response.status_code == 201 + assert response_body == "Planet Neptune successfully created" From af6508d04a62166ac55c3d20095f7375d74aeb60 Mon Sep 17 00:00:00 2001 From: mhc Date: Mon, 7 Nov 2022 13:26:37 -0500 Subject: [PATCH 21/23] removed redundant if from create_planet route --- app/routes.py | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/app/routes.py b/app/routes.py index b393b52b1..af8382593 100644 --- a/app/routes.py +++ b/app/routes.py @@ -21,20 +21,19 @@ @planets_bp.route("", methods=["POST"]) def create_planet(): - if request.method == "POST": - request_body = request.get_json() - if ("name" not in request_body or "description" not in request_body - or "moons" not in request_body): - return make_response(f"Invalid Request", 400) - - new_planet = Planet.from_dict(request_body) - - db.session.add(new_planet) - db.session.commit() - - return make_response( - f"Planet {new_planet.name} successfully created", 201 - ) + request_body = request.get_json() + if ("name" not in request_body or "description" not in request_body + or "moons" not in request_body): + return make_response(f"Invalid Request", 400) + + new_planet = Planet.from_dict(request_body) + + db.session.add(new_planet) + db.session.commit() + + return make_response( + f"Planet {new_planet.name} successfully created", 201 + ) @planets_bp.route("", methods=["GET"]) def read_all_planets(): From a31c19487559cd0d1c6ed657263fa88cf655128c Mon Sep 17 00:00:00 2001 From: mhc Date: Mon, 7 Nov 2022 14:29:53 -0500 Subject: [PATCH 22/23] pip installed gunicorn --- requirements.txt | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/requirements.txt b/requirements.txt index fba2b3e38..517b98b2d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,19 +1,27 @@ alembic==1.5.4 +attrs==22.1.0 autopep8==1.5.5 blinker==1.4 certifi==2020.12.5 chardet==4.0.0 click==7.1.2 +coverage==6.5.0 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==1.0.0 psycopg2-binary==2.9.4 +py==1.11.0 pycodestyle==2.6.0 +pyparsing==3.0.9 pytest==7.1.1 pytest-cov==2.12.1 python-dateutil==2.8.1 @@ -23,5 +31,6 @@ requests==2.25.1 six==1.15.0 SQLAlchemy==1.3.23 toml==0.10.2 +tomli==2.0.1 urllib3==1.26.4 Werkzeug==1.0.1 From da2cb7f9054efb7ece231858de06a4ba7c316191 Mon Sep 17 00:00:00 2001 From: mhc Date: Mon, 7 Nov 2022 14:30:26 -0500 Subject: [PATCH 23/23] touched Procfile and configured it --- Procfile | 1 + 1 file changed, 1 insertion(+) 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