From 823ef3c0c288845cf92ebac95cdd69e3c0f94be8 Mon Sep 17 00:00:00 2001 From: Myranae Date: Fri, 22 Apr 2022 14:02:31 -0400 Subject: [PATCH 01/20] passes wave 1 part 1 requirements --- app/__init__.py | 3 +++ app/routes.py | 37 ++++++++++++++++++++++++++++++++++++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..1123a559e 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 bp + app.register_blueprint(bp) + return app diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..96e6390fd 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,37 @@ -from flask import Blueprint +from flask import Blueprint, jsonify + +class Planet: + def __init__(self, id, name, description, color): + self.id = id + self.name = name + self.description = description + self.color = color + +planets = [ + Planet(1, "Mercury", "Super small, comparatively", "slate gray"), + Planet(2, "Venus", "It's sooo hot!", "yellow-white"), + Planet(3, "Earth", "Home to humans", "blue-green"), + Planet(4, "Mars", "The red one", "red"), + Planet(5, "Jupiter", "The biggest of them all", "orange-yellow"), + Planet(6, "Saturn", "What beautiful rings it has!", "hazy yellow-brown"), + Planet(7, "Uranus", "Tilted sideways", "blue-green"), + Planet(8, "Neptune", "Giant, stormy, blue", "blue"), + Planet(9, "Maybe Pluto", "Is it really a planet??", "reddish-brown") + ] + +bp = Blueprint("planets", __name__, url_prefix="/planets") + +@bp.route("", methods=["GET"]) +def get_planets(): + results_list = [] + for planet in planets: + results_list.append( + { + "id": planet.id, + "name": planet.name, + "description": planet.description, + "color": planet.color, + } + ) + return jsonify(results_list) From f40beb4340e767da08dfaef4a6e3cf4da5594df5 Mon Sep 17 00:00:00 2001 From: Myranae Date: Mon, 25 Apr 2022 14:52:35 -0400 Subject: [PATCH 02/20] partial progress on wave 2 --- app/routes.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/app/routes.py b/app/routes.py index 96e6390fd..4640443b8 100644 --- a/app/routes.py +++ b/app/routes.py @@ -8,6 +8,14 @@ def __init__(self, id, name, description, color): self.description = description self.color = color + def to_dict(self): + return { + self.id, + self.name, + self.description, + self.color, + } + planets = [ Planet(1, "Mercury", "Super small, comparatively", "slate gray"), Planet(2, "Venus", "It's sooo hot!", "yellow-white"), @@ -22,6 +30,14 @@ def __init__(self, id, name, description, color): bp = Blueprint("planets", __name__, url_prefix="/planets") +def validate_planet(id): + try: + id = int(id) + except ValueError: + abort(make_response({"message": "invalid id: {id}"}), 400) + + for planet in planets: + @bp.route("", methods=["GET"]) def get_planets(): results_list = [] @@ -35,3 +51,8 @@ def get_planets(): } ) return jsonify(results_list) + +@bp.route("/", methods=["GET"]) +def get_planet(id): + planet = validate_planet() + return planet.to_dict(), 200 From 510d039d38b90e28075d89421bdb452fa276c15e Mon Sep 17 00:00:00 2001 From: Shayla Logan Date: Mon, 25 Apr 2022 12:13:46 -0700 Subject: [PATCH 03/20] Added functionality to read one planet and provide custom error messages --- app/routes.py | 31 ++++++++++++++----------------- 1 file changed, 14 insertions(+), 17 deletions(-) diff --git a/app/routes.py b/app/routes.py index 4640443b8..01f4f569d 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: @@ -9,12 +9,12 @@ def __init__(self, id, name, description, color): self.color = color def to_dict(self): - return { - self.id, - self.name, - self.description, - self.color, - } + return dict( + id=self.id, + name=self.name, + description=self.description, + color=self.color, + ) planets = [ Planet(1, "Mercury", "Super small, comparatively", "slate gray"), @@ -34,25 +34,22 @@ def validate_planet(id): try: id = int(id) except ValueError: - abort(make_response({"message": "invalid id: {id}"}), 400) + abort(make_response({"message":f"invalid id: {id}"}, 400)) for planet in planets: + if planet.id == id: + return planet + + abort(make_response({"Message":f"Planet ID {id} not found"}, 404)) @bp.route("", methods=["GET"]) def get_planets(): results_list = [] for planet in planets: - results_list.append( - { - "id": planet.id, - "name": planet.name, - "description": planet.description, - "color": planet.color, - } - ) + results_list.append(planet.to_dict()) return jsonify(results_list) @bp.route("/", methods=["GET"]) def get_planet(id): - planet = validate_planet() + planet = validate_planet(id) return planet.to_dict(), 200 From d5b47efdfb98d5d5d7d1465c4206884452f9f872 Mon Sep 17 00:00:00 2001 From: Myranae Date: Fri, 29 Apr 2022 14:02:54 -0400 Subject: [PATCH 04/20] sets up database, table, and planet model --- app/__init__.py | 12 +++ app/models/planet.py | 9 ++ app/routes.py | 52 +++++----- migrations/README | 1 + migrations/alembic.ini | 45 +++++++++ migrations/env.py | 96 +++++++++++++++++++ migrations/script.py.mako | 24 +++++ .../fdb0b190d588_adds_planet_model.py | 34 +++++++ 8 files changed, 247 insertions(+), 26 deletions(-) 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/fdb0b190d588_adds_planet_model.py diff --git a/app/__init__.py b/app/__init__.py index 1123a559e..457a8e08e 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' + + db.init_app(app) + migrate.init_app(app, db) + + from app.models.planet import Planet + from .routes import bp app.register_blueprint(bp) diff --git a/app/models/planet.py b/app/models/planet.py new file mode 100644 index 000000000..ce26db701 --- /dev/null +++ b/app/models/planet.py @@ -0,0 +1,9 @@ +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) + color = db.Column(db.String) + + diff --git a/app/routes.py b/app/routes.py index 01f4f569d..bb855593b 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,32 +1,32 @@ from flask import Blueprint, jsonify, abort, make_response -class Planet: - def __init__(self, id, name, description, color): - self.id = id - self.name = name - self.description = description - self.color = color - - def to_dict(self): - return dict( - id=self.id, - name=self.name, - description=self.description, - color=self.color, - ) - -planets = [ - Planet(1, "Mercury", "Super small, comparatively", "slate gray"), - Planet(2, "Venus", "It's sooo hot!", "yellow-white"), - Planet(3, "Earth", "Home to humans", "blue-green"), - Planet(4, "Mars", "The red one", "red"), - Planet(5, "Jupiter", "The biggest of them all", "orange-yellow"), - Planet(6, "Saturn", "What beautiful rings it has!", "hazy yellow-brown"), - Planet(7, "Uranus", "Tilted sideways", "blue-green"), - Planet(8, "Neptune", "Giant, stormy, blue", "blue"), - Planet(9, "Maybe Pluto", "Is it really a planet??", "reddish-brown") - ] +# class Planet: +# def __init__(self, id, name, description, color): +# self.id = id +# self.name = name +# self.description = description +# self.color = color + +# def to_dict(self): +# return dict( +# id=self.id, +# name=self.name, +# description=self.description, +# color=self.color, +# ) + +# planets = [ +# Planet(1, "Mercury", "Super small, comparatively", "slate gray"), +# Planet(2, "Venus", "It's sooo hot!", "yellow-white"), +# Planet(3, "Earth", "Home to humans", "blue-green"), +# Planet(4, "Mars", "The red one", "red"), +# Planet(5, "Jupiter", "The biggest of them all", "orange-yellow"), +# Planet(6, "Saturn", "What beautiful rings it has!", "hazy yellow-brown"), +# Planet(7, "Uranus", "Tilted sideways", "blue-green"), +# Planet(8, "Neptune", "Giant, stormy, blue", "blue"), +# Planet(9, "Maybe Pluto", "Is it really a planet??", "reddish-brown") +# ] bp = Blueprint("planets", __name__, url_prefix="/planets") 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/fdb0b190d588_adds_planet_model.py b/migrations/versions/fdb0b190d588_adds_planet_model.py new file mode 100644 index 000000000..a115b87a0 --- /dev/null +++ b/migrations/versions/fdb0b190d588_adds_planet_model.py @@ -0,0 +1,34 @@ +"""Adds planet model + +Revision ID: fdb0b190d588 +Revises: +Create Date: 2022-04-29 14:01:13.547601 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'fdb0b190d588' +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('color', sa.String(), 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 560597a5d1b28a03ec3dc0e1d475a8907fbc5eae Mon Sep 17 00:00:00 2001 From: Shayla Logan Date: Fri, 29 Apr 2022 11:33:26 -0700 Subject: [PATCH 05/20] added POST route --- app/routes.py | 64 ++++++++++++++++++++++++++++++++------------------- 1 file changed, 40 insertions(+), 24 deletions(-) diff --git a/app/routes.py b/app/routes.py index bb855593b..1abe06463 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,4 +1,6 @@ -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: @@ -30,26 +32,40 @@ bp = Blueprint("planets", __name__, url_prefix="/planets") -def validate_planet(id): - try: - id = int(id) - except ValueError: - abort(make_response({"message":f"invalid id: {id}"}, 400)) - - for planet in planets: - if planet.id == id: - return planet - - abort(make_response({"Message":f"Planet ID {id} not found"}, 404)) - -@bp.route("", methods=["GET"]) -def get_planets(): - results_list = [] - for planet in planets: - results_list.append(planet.to_dict()) - return jsonify(results_list) - -@bp.route("/", methods=["GET"]) -def get_planet(id): - planet = validate_planet(id) - return planet.to_dict(), 200 +@bp.route("", methods=["POST"]) +def create_planet(): + request_body = request.get_json() + new_planet = Planet( + name = request_body["name"], + description = request_body["description"], + color = request_body["color"] + ) + + db.session.add(new_planet) + db.session.commit() + + return f"Planet {new_planet.name} successfully created", 201 + +# def validate_planet(id): +# try: +# id = int(id) +# except ValueError: +# abort(make_response({"message":f"invalid id: {id}"}, 400)) + +# for planet in planets: +# if planet.id == id: +# return planet + +# abort(make_response({"Message":f"Planet ID {id} not found"}, 404)) + +# @bp.route("", methods=["GET"]) +# def get_planets(): +# results_list = [] +# for planet in planets: +# results_list.append(planet.to_dict()) +# return jsonify(results_list) + +# @bp.route("/", methods=["GET"]) +# def get_planet(id): +# planet = validate_planet(id) +# return planet.to_dict(), 200 From 5e3f63ceff86984ee59270d508d1c958fef7934c Mon Sep 17 00:00:00 2001 From: Myranae Date: Fri, 29 Apr 2022 14:43:59 -0400 Subject: [PATCH 06/20] sets up the read all planets route --- app/routes.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/app/routes.py b/app/routes.py index 1abe06463..4ce061442 100644 --- a/app/routes.py +++ b/app/routes.py @@ -46,6 +46,20 @@ def create_planet(): return f"Planet {new_planet.name} successfully created", 201 +@bp.route("", methods=["GET"]) +def read_all_planets(): + planets = Planet.query.all() + planets_response = [] + for planet in planets: + planets_response.append( + { + "name": planet.name, + "description": planet.description, + "color": planet.color + } + ) + return jsonify(planets_response) + # def validate_planet(id): # try: # id = int(id) From 496c2d46b307dd136db578d047649db68cfebebe Mon Sep 17 00:00:00 2001 From: Myranae Date: Tue, 3 May 2022 13:48:51 -0400 Subject: [PATCH 07/20] adds read_one_planet route and to_dict method --- app/models/planet.py | 7 ++++++ app/routes.py | 55 ++++---------------------------------------- 2 files changed, 11 insertions(+), 51 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index ce26db701..4060b42b1 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -6,4 +6,11 @@ class Planet(db.Model): description = db.Column(db.String) color = db.Column(db.String) + def to_dict(self): + return { + "id": self.id, + "name": self.name, + "description": self.description, + "color": self.color + } diff --git a/app/routes.py b/app/routes.py index 4ce061442..1427d82bb 100644 --- a/app/routes.py +++ b/app/routes.py @@ -2,34 +2,6 @@ from app import db from app.models.planet import Planet - -# class Planet: -# def __init__(self, id, name, description, color): -# self.id = id -# self.name = name -# self.description = description -# self.color = color - -# def to_dict(self): -# return dict( -# id=self.id, -# name=self.name, -# description=self.description, -# color=self.color, -# ) - -# planets = [ -# Planet(1, "Mercury", "Super small, comparatively", "slate gray"), -# Planet(2, "Venus", "It's sooo hot!", "yellow-white"), -# Planet(3, "Earth", "Home to humans", "blue-green"), -# Planet(4, "Mars", "The red one", "red"), -# Planet(5, "Jupiter", "The biggest of them all", "orange-yellow"), -# Planet(6, "Saturn", "What beautiful rings it has!", "hazy yellow-brown"), -# Planet(7, "Uranus", "Tilted sideways", "blue-green"), -# Planet(8, "Neptune", "Giant, stormy, blue", "blue"), -# Planet(9, "Maybe Pluto", "Is it really a planet??", "reddish-brown") -# ] - bp = Blueprint("planets", __name__, url_prefix="/planets") @bp.route("", methods=["POST"]) @@ -60,26 +32,7 @@ def read_all_planets(): ) return jsonify(planets_response) -# def validate_planet(id): -# try: -# id = int(id) -# except ValueError: -# abort(make_response({"message":f"invalid id: {id}"}, 400)) - -# for planet in planets: -# if planet.id == id: -# return planet - -# abort(make_response({"Message":f"Planet ID {id} not found"}, 404)) - -# @bp.route("", methods=["GET"]) -# def get_planets(): -# results_list = [] -# for planet in planets: -# results_list.append(planet.to_dict()) -# return jsonify(results_list) - -# @bp.route("/", methods=["GET"]) -# def get_planet(id): -# planet = validate_planet(id) -# return planet.to_dict(), 200 +@bp.route("/", methods=["GET"]) +def read_one_planet(planet_id): + planet = Planet.query.get(planet_id) + return planet.to_dict() \ No newline at end of file From 9aedb80d2f40ae4b44543bbd217442784a187b1a Mon Sep 17 00:00:00 2001 From: Shayla Logan Date: Tue, 3 May 2022 11:06:29 -0700 Subject: [PATCH 08/20] added validate_planet and delete planet --- app/routes.py | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/app/routes.py b/app/routes.py index 1427d82bb..dc7130b81 100644 --- a/app/routes.py +++ b/app/routes.py @@ -4,6 +4,19 @@ bp = Blueprint("planets", __name__, url_prefix="/planets") +def validate_planet(planet_id): + try: + planet_id = int(planet_id) + except ValueError: + abort(make_response(f"Planet {planet_id} is invalid", 400)) + + planet = Planet.query.get(planet_id) + + if not planet: + abort(make_response(f"Planet {planet_id} not found", 404)) + + return planet + @bp.route("", methods=["POST"]) def create_planet(): request_body = request.get_json() @@ -34,5 +47,15 @@ def read_all_planets(): @bp.route("/", methods=["GET"]) def read_one_planet(planet_id): - planet = Planet.query.get(planet_id) - return planet.to_dict() \ No newline at end of file + planet = validate_planet(planet_id) + + return planet.to_dict() + +@bp.route("/", methods=["DELETE"]) +def delete_planet(planet_id): + planet = validate_planet(planet_id) + + db.session.delete(planet) + db.session.commit() + + return jsonify(f'Planet {planet_id} successfully deleted') \ No newline at end of file From 83373830968869f8d88271e3795b5dddc9c33a43 Mon Sep 17 00:00:00 2001 From: Myranae Date: Tue, 3 May 2022 14:20:16 -0400 Subject: [PATCH 09/20] adds update route --- app/routes.py | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index dc7130b81..6556f9ebc 100644 --- a/app/routes.py +++ b/app/routes.py @@ -38,6 +38,7 @@ def read_all_planets(): for planet in planets: planets_response.append( { + "id": planet.id, "name": planet.name, "description": planet.description, "color": planet.color @@ -58,4 +59,18 @@ def delete_planet(planet_id): db.session.delete(planet) db.session.commit() - return jsonify(f'Planet {planet_id} successfully deleted') \ No newline at end of file + return jsonify(f'Planet {planet_id} successfully deleted') + +@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.color = request_body["color"] + + db.session.commit() + + return make_response(f"Planet {planet_id} was successfully updated.") From 875547dd0314b6bf9c48f46716993eda4b9a23b1 Mon Sep 17 00:00:00 2001 From: Myranae Date: Wed, 4 May 2022 13:52:27 -0400 Subject: [PATCH 10/20] refactors route file to new folder --- app/__init__.py | 2 +- app/{routes.py => routes/planet_routes.py} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename app/{routes.py => routes/planet_routes.py} (100%) diff --git a/app/__init__.py b/app/__init__.py index 457a8e08e..228d5f4f2 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -16,7 +16,7 @@ def create_app(test_config=None): from app.models.planet import Planet - from .routes import bp + from .routes.planet_routes import bp app.register_blueprint(bp) return app diff --git a/app/routes.py b/app/routes/planet_routes.py similarity index 100% rename from app/routes.py rename to app/routes/planet_routes.py From 4b8a05da0da96abcc4b1aa18dd590ffe31a7c9cd Mon Sep 17 00:00:00 2001 From: Myranae Date: Wed, 4 May 2022 14:30:50 -0400 Subject: [PATCH 11/20] adds in filtering all planets by query params --- app/routes/planet_routes.py | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/app/routes/planet_routes.py b/app/routes/planet_routes.py index 6556f9ebc..dfe8ccba8 100644 --- a/app/routes/planet_routes.py +++ b/app/routes/planet_routes.py @@ -17,6 +17,7 @@ def validate_planet(planet_id): return planet + @bp.route("", methods=["POST"]) def create_planet(): request_body = request.get_json() @@ -33,7 +34,23 @@ def create_planet(): @bp.route("", methods=["GET"]) def read_all_planets(): - planets = Planet.query.all() + name_param = request.args.get("name") + description_param = request.args.get("description") + color_param = request.args.get("color") + + planets = Planet.query + + if name_param: + planets = planets.filter_by(name=name_param) + if description_param: + planets = planets.filter_by(description=description_param) + if color_param: + planets = planets.filter_by(color=color_param) + + planets = planets.all() + + #.query provides an in progress query + planets_response = [] for planet in planets: planets_response.append( From 9c6eb19b8a38566153011c105fa3ce6184e810d9 Mon Sep 17 00:00:00 2001 From: Shayla Logan Date: Thu, 5 May 2022 11:02:05 -0700 Subject: [PATCH 12/20] Added automated test setup --- app/__init__.py | 8 +++++++- tests/__init__.py | 0 tests/conftest.py | 0 tests/test_routes.py | 25 +++++++++++++++++++++++++ 4 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 tests/__init__.py create mode 100644 tests/conftest.py create mode 100644 tests/test_routes.py diff --git a/app/__init__.py b/app/__init__.py index 228d5f4f2..4ef7dc10b 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,6 +1,7 @@ from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate +import os db = SQLAlchemy() migrate = Migrate() @@ -9,7 +10,12 @@ 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 test_config == None: + 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) 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..ac8a4193b --- /dev/null +++ b/tests/test_routes.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 From b47b247ee6a26375bdb4ad0782baf71ca0afbaca Mon Sep 17 00:00:00 2001 From: Shayla Logan Date: Thu, 5 May 2022 11:05:06 -0700 Subject: [PATCH 13/20] added conftest --- tests/conftest.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/tests/conftest.py b/tests/conftest.py index e69de29bb..ac8a4193b 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() \ No newline at end of file From 130ae260800c582175b434fd2787ccf347c81f48 Mon Sep 17 00:00:00 2001 From: Myranae Date: Thu, 5 May 2022 14:32:11 -0400 Subject: [PATCH 14/20] creates dummy test data and three tests --- app/__init__.py | 4 +++- tests/conftest.py | 18 +++++++++++++++- tests/test_routes.py | 49 ++++++++++++++++++++++++++++---------------- 3 files changed, 51 insertions(+), 20 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 4ef7dc10b..d38f42e7b 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,17 +1,19 @@ 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 - if test_config == None: + if not test_config: app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI') else: app.config['TESTING'] = True diff --git a/tests/conftest.py b/tests/conftest.py index ac8a4193b..b515b790b 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 @@ -22,4 +23,19 @@ 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 create_two_planets(app): + planet_one = Planet( + name="Mercury", + description="smallest planet", + color="magenta" + ) + planet_two = Planet( + name="Mars", + description="maybe we will live here?", + color="reddish brown" + ) + db.session.add_all([planet_one, planet_two]) + db.session.commit() \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py index ac8a4193b..8ff0dc91f 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -1,25 +1,38 @@ -import pytest -from app import create_app -from app import db -from flask.signals import request_finished +# import pytest +# Create a test to check `GET` `/planets` returns `200` and an empty array. +def test_get_all_planets_with_no_records(client): + # Act + response = client.get('/planets') + response_body = response.get_json() -@pytest.fixture -def app(): - app = create_app({"TESTING": True}) + #assert + assert response.status_code == 200 + assert response_body == [] - @request_finished.connect_via(app) - def expire_session(sender, response, **extra): - db.session.remove() +def test_get_one_planet_with_dummy_records(client, create_two_planets): + # Act + response = client.get('/planets/1') + response_body = response.get_json() - with app.app_context(): - db.create_all() - yield app + #assert + assert response.status_code == 200 + assert response_body == { + "id": 1, + "name": "Mercury", + "description": "smallest planet", + "color": "magenta" + } - with app.app_context(): - db.drop_all() +def test_get_one_planet_with_no_records(client): + # Act + response = client.get('/planets/1') + response_body = response.get_json() + #assert + assert response.status_code == 404 + assert response_body == None -@pytest.fixture -def client(app): - return app.test_client() \ No newline at end of file + # { + # "message": "Planet 1 not found" + # } \ No newline at end of file From ebb7fa1f2d6f340e620ea69264475d390b1dd085 Mon Sep 17 00:00:00 2001 From: Shayla Logan Date: Thu, 5 May 2022 11:45:14 -0700 Subject: [PATCH 15/20] added test for post --- tests/test_routes.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/tests/test_routes.py b/tests/test_routes.py index 8ff0dc91f..8c091b834 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -33,6 +33,15 @@ def test_get_one_planet_with_no_records(client): assert response.status_code == 404 assert response_body == None - # { - # "message": "Planet 1 not found" - # } \ No newline at end of file +# def test_create_one_planet(client): +# # Act +# response = client.post('/planets', json={ +# "name": "Venus", +# "description": "Planet of love", +# "color": "hot pink" +# }) +# response_body = response.get_json() + +# #assert +# assert response.status_code == 201 +# assert response_body == "Planet Venus successfully created" \ No newline at end of file From a7fc7254f5aa0533aac7c7ca7b3593543a3d9115 Mon Sep 17 00:00:00 2001 From: Shayla Logan Date: Thu, 5 May 2022 11:47:28 -0700 Subject: [PATCH 16/20] added jsonify to response --- app/routes/planet_routes.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/routes/planet_routes.py b/app/routes/planet_routes.py index dfe8ccba8..f5e4709c1 100644 --- a/app/routes/planet_routes.py +++ b/app/routes/planet_routes.py @@ -30,7 +30,7 @@ def create_planet(): db.session.add(new_planet) db.session.commit() - return f"Planet {new_planet.name} successfully created", 201 + return make_response(jsonify(f"Planet {new_planet.name} successfully created"), 201) @bp.route("", methods=["GET"]) def read_all_planets(): From dcd538680014b85cff16a5b4950f859630aaeb79 Mon Sep 17 00:00:00 2001 From: Myranae Date: Thu, 5 May 2022 14:53:00 -0400 Subject: [PATCH 17/20] uncomments a test --- tests/test_routes.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/tests/test_routes.py b/tests/test_routes.py index 8c091b834..4e4c2fe58 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -33,15 +33,15 @@ def test_get_one_planet_with_no_records(client): assert response.status_code == 404 assert response_body == None -# def test_create_one_planet(client): -# # Act -# response = client.post('/planets', json={ -# "name": "Venus", -# "description": "Planet of love", -# "color": "hot pink" -# }) -# response_body = response.get_json() - -# #assert -# assert response.status_code == 201 -# assert response_body == "Planet Venus successfully created" \ No newline at end of file +def test_create_one_planet(client): + # Act + response = client.post('/planets', json={ + "name": "Venus", + "description": "Planet of love", + "color": "hot pink" + }) + response_body = response.get_json() + + #assert + assert response.status_code == 201 + assert response_body == "Planet Venus successfully created" \ No newline at end of file From ec693fc09dbd532ad6af6601198822835e81bce8 Mon Sep 17 00:00:00 2001 From: Shayla Logan Date: Thu, 5 May 2022 11:55:34 -0700 Subject: [PATCH 18/20] added test for posts --- tests/test_routes.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/tests/test_routes.py b/tests/test_routes.py index 8c091b834..4e4c2fe58 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -33,15 +33,15 @@ def test_get_one_planet_with_no_records(client): assert response.status_code == 404 assert response_body == None -# def test_create_one_planet(client): -# # Act -# response = client.post('/planets', json={ -# "name": "Venus", -# "description": "Planet of love", -# "color": "hot pink" -# }) -# response_body = response.get_json() - -# #assert -# assert response.status_code == 201 -# assert response_body == "Planet Venus successfully created" \ No newline at end of file +def test_create_one_planet(client): + # Act + response = client.post('/planets', json={ + "name": "Venus", + "description": "Planet of love", + "color": "hot pink" + }) + response_body = response.get_json() + + #assert + assert response.status_code == 201 + assert response_body == "Planet Venus successfully created" \ No newline at end of file From 47a746d8df5ea06b5b6dfdda0e74cbf20723a79e Mon Sep 17 00:00:00 2001 From: Shayla Logan Date: Thu, 5 May 2022 13:48:25 -0700 Subject: [PATCH 19/20] added tests for put and delete --- app/routes/planet_routes.py | 2 +- tests/test_routes.py | 24 +++++++++++++++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/app/routes/planet_routes.py b/app/routes/planet_routes.py index f5e4709c1..11a3ac516 100644 --- a/app/routes/planet_routes.py +++ b/app/routes/planet_routes.py @@ -90,4 +90,4 @@ def update_planet(planet_id): db.session.commit() - return make_response(f"Planet {planet_id} was successfully updated.") + return make_response(jsonify(f"Planet {planet_id} was successfully replaced.")) diff --git a/tests/test_routes.py b/tests/test_routes.py index 4e4c2fe58..15959b28b 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -44,4 +44,26 @@ def test_create_one_planet(client): #assert assert response.status_code == 201 - assert response_body == "Planet Venus successfully created" \ No newline at end of file + assert response_body == "Planet Venus successfully created" + +def test_replace_one_planet(client, create_two_planets): + # Act + response = client.put('/planets/1', json={ + "name": "Earth", + "description": "Home for humans", + "color": "blueish green" + }) + response_body = response.get_json() + + #assert + assert response.status_code == 200 + assert response_body == "Planet 1 was successfully replaced." + +def test_delete_one_planet(client, create_two_planets): + # Act + response = client.delete('/planets/1') + response_body = response.get_json() + + #assert + assert response.status_code == 200 + assert response_body == 'Planet 1 successfully deleted' \ No newline at end of file From 47a731111813d97fdb6dcd81a340cdf46d02b569 Mon Sep 17 00:00:00 2001 From: Shayla Logan Date: Wed, 11 May 2022 10:09:07 -0700 Subject: [PATCH 20/20] 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..37b7c1d29 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.8 pytest==6.2.3 pytest-cov==2.12.1 python-dateutil==2.8.1