From 306bf24b3e4c90cac6691f437861419ec5257226 Mon Sep 17 00:00:00 2001 From: Lauren Kleinert Date: Fri, 22 Apr 2022 11:00:36 -0700 Subject: [PATCH 01/12] Created Planet Class --- app/routes.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..75441b49d 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,19 @@ from flask import Blueprint +class Planet: + def __init__(self, id, name, description, order_in_solar_system): + self.id = id + self.name = name + self.description = description + self.order_in_solar_system = order_in_solar_system + +planets = [ + Planet(1, "Mercury", "smallest", "first"), + Planet(2, "Venus", "red, hot", "second"), + Planet(3, "Earth", "our home", "third"), + Planet(4, "Mars", "desert-like", "fourth"), + Planet(5, "Jupiter", "largest", "fifth"), + Planet(6, "Saturn", "lots o' rings", "sixth"), + Planet(7, "Uranus", "smelly", "seventh"), + Planet(8, "Neptune", "blue", "eigth") +] From dd64aee1b38d00a62961a6a9d21c1d951e024630 Mon Sep 17 00:00:00 2001 From: Lauren Kleinert Date: Fri, 22 Apr 2022 11:10:06 -0700 Subject: [PATCH 02/12] Created Planets blueprint, registered blueprint with app object, and created blueprint endpoint get_planets --- app/__init__.py | 2 ++ app/routes.py | 15 ++++++++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..3675c9309 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -4,4 +4,6 @@ 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 75441b49d..6a172bf74 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,4 +1,4 @@ -from flask import Blueprint +from flask import Blueprint, jsonify class Planet: def __init__(self, id, name, description, order_in_solar_system): @@ -17,3 +17,16 @@ def __init__(self, id, name, description, order_in_solar_system): Planet(7, "Uranus", "smelly", "seventh"), Planet(8, "Neptune", "blue", "eigth") ] +planets_bp = Blueprint("planets", __name__, url_prefix = "/planets") + +@planets_bp.route("", methods=["GET"]) +def get_planets(): + planet_response = [] + for planet in planets: + planet_response.append({ + "id": planet.id, + "name": planet.name, + "description": planet.description, + "order in solar system": planet.order_in_solar_system + }) + return jsonify(planet_response) From 7c8273b9151966eacddca5210565367ca878911e Mon Sep 17 00:00:00 2001 From: Ivana Maldonado Date: Mon, 25 Apr 2022 14:55:12 -0400 Subject: [PATCH 03/12] Created a route for one planet, created validate_planet function, added class instance method to_json --- app/__init__.py | 2 +- app/routes.py | 42 ++++++++++++++++++++++++++++++++++-------- 2 files changed, 35 insertions(+), 9 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 3675c9309..3e25d996d 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,9 +1,9 @@ from flask import Flask - 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 6a172bf74..c4dc79125 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,4 +1,4 @@ -from flask import Blueprint, jsonify +from flask import Blueprint, jsonify, make_response, abort class Planet: def __init__(self, id, name, description, order_in_solar_system): @@ -7,6 +7,14 @@ def __init__(self, id, name, description, order_in_solar_system): self.description = description self.order_in_solar_system = order_in_solar_system + def to_json(self): + return { + "id": self.id, + "name": self.name, + "description": self.description, + "order in solar system": self.order_in_solar_system + } + planets = [ Planet(1, "Mercury", "smallest", "first"), Planet(2, "Venus", "red, hot", "second"), @@ -15,18 +23,36 @@ def __init__(self, id, name, description, order_in_solar_system): Planet(5, "Jupiter", "largest", "fifth"), Planet(6, "Saturn", "lots o' rings", "sixth"), Planet(7, "Uranus", "smelly", "seventh"), - Planet(8, "Neptune", "blue", "eigth") + Planet(8, "Neptune", "blue", "eigth") ] + planets_bp = Blueprint("planets", __name__, url_prefix = "/planets") @planets_bp.route("", methods=["GET"]) def get_planets(): planet_response = [] for planet in planets: - planet_response.append({ - "id": planet.id, - "name": planet.name, - "description": planet.description, - "order in solar system": planet.order_in_solar_system - }) + planet_response.append(planet.to_json()) return jsonify(planet_response) + + +def validate_planet(planet_id): + try: + planet_id = int(planet_id) + except: + abort(make_response({"message":f"planet {planet_id} invalid"}, 400)) + + for planet in planets: + if planet.id == planet_id: + return planet + return abort(make_response({"message":f"planet {planet_id} not found"}, 404)) + + +@planets_bp.route("/", methods = ["GET"]) +def get_one_planet(planet_id): + planet_id = validate_planet(planet_id) + + return jsonify(planet_id.to_json()) + + + From 697070ecf298f5138252d6c6c5a30a7292cd3b98 Mon Sep 17 00:00:00 2001 From: Lauren Kleinert Date: Mon, 25 Apr 2022 12:23:16 -0700 Subject: [PATCH 04/12] Added status code to return of get_planets() --- app/routes.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index c4dc79125..39ffed307 100644 --- a/app/routes.py +++ b/app/routes.py @@ -33,7 +33,7 @@ def get_planets(): planet_response = [] for planet in planets: planet_response.append(planet.to_json()) - return jsonify(planet_response) + return jsonify(planet_response), 200 def validate_planet(planet_id): From e7d20d490e9bb44ee71655505660adafef8da85c Mon Sep 17 00:00:00 2001 From: Lauren Kleinert Date: Tue, 26 Apr 2022 13:15:27 -0700 Subject: [PATCH 05/12] Added status code to function get_one_planet(planet_id) --- app/routes.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index 39ffed307..c52a1e8ed 100644 --- a/app/routes.py +++ b/app/routes.py @@ -52,7 +52,7 @@ def validate_planet(planet_id): def get_one_planet(planet_id): planet_id = validate_planet(planet_id) - return jsonify(planet_id.to_json()) + return jsonify(planet_id.to_json()), 200 From 005bfddf3ee921357ba2f4da0dc7b56062ec2f87 Mon Sep 17 00:00:00 2001 From: Lauren Kleinert Date: Fri, 29 Apr 2022 14:41:59 -0400 Subject: [PATCH 06/12] Connected db to app, created model Class Planets, created endpoints POST /planets, GET /planets --- app/__init__.py | 17 +++- app/models/__init__.py | 0 app/models/planet.py | 17 ++++ app/routes.py | 82 ++++++++-------- migrations/README | 1 + migrations/alembic.ini | 45 +++++++++ migrations/env.py | 96 +++++++++++++++++++ migrations/script.py.mako | 24 +++++ .../37a70224f42b_adds_planet_model.py | 34 +++++++ 9 files changed, 271 insertions(+), 45 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/37a70224f42b_adds_planet_model.py diff --git a/app/__init__.py b/app/__init__.py index 3e25d996d..05869d25e 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,9 +1,24 @@ 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 planets_bp app.register_blueprint(planets_bp) - + return app + 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..40fe672a7 --- /dev/null +++ b/app/models/planet.py @@ -0,0 +1,17 @@ +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) + order_in_ss = db.Column(db.String) + + def to_json(self): + return { + "id": self.id, + "name": self.name, + "description": self.description, + "order in solar system": self.order_in_ss + } + + \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index c52a1e8ed..00c99d5d9 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,58 +1,52 @@ -from flask import Blueprint, jsonify, make_response, abort - -class Planet: - def __init__(self, id, name, description, order_in_solar_system): - self.id = id - self.name = name - self.description = description - self.order_in_solar_system = order_in_solar_system - - def to_json(self): - return { - "id": self.id, - "name": self.name, - "description": self.description, - "order in solar system": self.order_in_solar_system - } - -planets = [ - Planet(1, "Mercury", "smallest", "first"), - Planet(2, "Venus", "red, hot", "second"), - Planet(3, "Earth", "our home", "third"), - Planet(4, "Mars", "desert-like", "fourth"), - Planet(5, "Jupiter", "largest", "fifth"), - Planet(6, "Saturn", "lots o' rings", "sixth"), - Planet(7, "Uranus", "smelly", "seventh"), - Planet(8, "Neptune", "blue", "eigth") -] +from app import db +from app.models.planet import Planet +from flask import Blueprint, jsonify, make_response, request + +planets_bp = Blueprint("planets", __name__, url_prefix="/planets") + +@planets_bp.route("", methods=["POST"]) +def post_new_planet(): + request_body = request.get_json() + new_planet = Planet(name=request_body["name"], + description=request_body["description"], + order_in_ss = request_body["order in solar system"] ) + + db.session.add(new_planet) + db.session.commit() + + return make_response(f"Planet {new_planet.name} successfully created", 201) + + planets_bp = Blueprint("planets", __name__, url_prefix = "/planets") @planets_bp.route("", methods=["GET"]) -def get_planets(): - planet_response = [] +def read_all_planets(): + planets_response = [] + planets = Planet.query.all() for planet in planets: - planet_response.append(planet.to_json()) - return jsonify(planet_response), 200 + planets_response.append(planet.to_json()) + + return jsonify(planets_response) -def validate_planet(planet_id): - try: - planet_id = int(planet_id) - except: - abort(make_response({"message":f"planet {planet_id} invalid"}, 400)) +# def validate_planet(planet_id): +# try: +# planet_id = int(planet_id) +# except: +# abort(make_response({"message":f"planet {planet_id} invalid"}, 400)) - for planet in planets: - if planet.id == planet_id: - return planet - return abort(make_response({"message":f"planet {planet_id} not found"}, 404)) +# for planet in planets: +# if planet.id == planet_id: +# return planet +# return abort(make_response({"message":f"planet {planet_id} not found"}, 404)) -@planets_bp.route("/", methods = ["GET"]) -def get_one_planet(planet_id): - planet_id = validate_planet(planet_id) +# @planets_bp.route("/", methods = ["GET"]) +# def get_one_planet(planet_id): +# planet_id = validate_planet(planet_id) - return jsonify(planet_id.to_json()), 200 +# return jsonify(planet_id.to_json()), 200 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/37a70224f42b_adds_planet_model.py b/migrations/versions/37a70224f42b_adds_planet_model.py new file mode 100644 index 000000000..954c9c0d5 --- /dev/null +++ b/migrations/versions/37a70224f42b_adds_planet_model.py @@ -0,0 +1,34 @@ +"""adds Planet model + +Revision ID: 37a70224f42b +Revises: +Create Date: 2022-04-29 14:09:36.875694 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '37a70224f42b' +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('order_in_ss', 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 501f764f025412fed64c48cac9d09dab8a2e3224 Mon Sep 17 00:00:00 2001 From: Lauren Kleinert Date: Tue, 3 May 2022 10:43:54 -0700 Subject: [PATCH 07/12] Included changes made to syntax per instructor feedback, previous commit empty --- app/routes.py | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/app/routes.py b/app/routes.py index 00c99d5d9..61d7ffc83 100644 --- a/app/routes.py +++ b/app/routes.py @@ -16,18 +16,13 @@ def post_new_planet(): return make_response(f"Planet {new_planet.name} successfully created", 201) - - -planets_bp = Blueprint("planets", __name__, url_prefix = "/planets") - @planets_bp.route("", methods=["GET"]) def read_all_planets(): planets_response = [] planets = Planet.query.all() - for planet in planets: - planets_response.append(planet.to_json()) + planets_response = [planet.to_json() for planet in planets] - return jsonify(planets_response) + return jsonify(planets_response), 200 # def validate_planet(planet_id): From cff8319030a655473231ce359e8c2aa21bec01ae Mon Sep 17 00:00:00 2001 From: Lauren Kleinert Date: Tue, 3 May 2022 11:17:13 -0700 Subject: [PATCH 08/12] Add endpoint functions for get one planet, update, and delete --- app/routes.py | 51 ++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 40 insertions(+), 11 deletions(-) diff --git a/app/routes.py b/app/routes.py index 61d7ffc83..516275bc3 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,9 +1,22 @@ from app import db from app.models.planet import Planet -from flask import Blueprint, jsonify, make_response, request +from flask import Blueprint, jsonify, make_response, request, abort planets_bp = Blueprint("planets", __name__, url_prefix="/planets") +def validate_planet(planet_id): + try: + planet_id = int(planet_id) + except: + abort(make_response({"message":f"planet {planet_id} invalid"}, 400)) + + planet = Planet.query.get(planet_id) + if not planet: + return abort(make_response({"message":f"planet {planet_id} not found"}, 404)) + + return planet + + @planets_bp.route("", methods=["POST"]) def post_new_planet(): request_body = request.get_json() @@ -16,25 +29,41 @@ def post_new_planet(): return make_response(f"Planet {new_planet.name} successfully created", 201) + @planets_bp.route("", methods=["GET"]) def read_all_planets(): - planets_response = [] planets = Planet.query.all() planets_response = [planet.to_json() for planet in planets] return jsonify(planets_response), 200 -# def validate_planet(planet_id): -# try: -# planet_id = int(planet_id) -# except: -# abort(make_response({"message":f"planet {planet_id} invalid"}, 400)) +@planets_bp.route("/", methods=["GET"]) +def read_one_planet(planet_id): + planet = validate_planet(planet_id) + return jsonify(planet.to_json()), 200 + + +@planets_bp.route("/", methods=["PUT"]) +def update_planet(planet_id): + update_body = request.get_json() + planet = validate_planet(planet_id) + + planet.name = update_body["name"] + planet.description = update_body["description"] + planet.order_in_ss = update_body["order in solar system"] + + db.session.commit() + + return make_response(f"Planet {planet.id} successfully updated", 200) + +@planets_bp.route("/", methods=["DELETE"]) +def delete_planet(planet_id): + planet = validate_planet(planet_id) + db.session.delete(planet) + db.session.commit() -# for planet in planets: -# if planet.id == planet_id: -# return planet -# return abort(make_response({"message":f"planet {planet_id} not found"}, 404)) + return make_response(f"Planet {planet.id} successfully deleted", 200) # @planets_bp.route("/", methods = ["GET"]) From 4e228b40fba8757643c8e647e7570169907b18b3 Mon Sep 17 00:00:00 2001 From: Ivana Maldonado Date: Wed, 4 May 2022 14:51:41 -0400 Subject: [PATCH 09/12] Refactored - created routes folder and helpers.py file, created instance method update and class method create. --- app/__init__.py | 2 +- app/models/planet.py | 14 +++++++++++++- app/routes/__init__.py | 0 app/routes/helpers.py | 14 ++++++++++++++ app/{ => routes}/routes.py | 35 ++++------------------------------- 5 files changed, 32 insertions(+), 33 deletions(-) create mode 100644 app/routes/__init__.py create mode 100644 app/routes/helpers.py rename app/{ => routes}/routes.py (60%) diff --git a/app/__init__.py b/app/__init__.py index 05869d25e..986b72804 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -17,7 +17,7 @@ def create_app(test_config=None): from app.models.planet import Planet - from .routes import planets_bp + from app.routes.routes import planets_bp app.register_blueprint(planets_bp) return app diff --git a/app/models/planet.py b/app/models/planet.py index 40fe672a7..098cfe25c 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -14,4 +14,16 @@ def to_json(self): "order in solar system": self.order_in_ss } - \ No newline at end of file + def update(self, update_body): + self.name = update_body["name"] + self.description = update_body["description"] + self.order_in_ss = update_body["order in solar system"] + + @classmethod + def create_planet(cls, request_body): + new_planet = cls( + name=request_body['name'], + description=request_body['description'], + order_in_ss=request_body['order in solar system'], + ) + return new_planet \ No newline at end of file diff --git a/app/routes/__init__.py b/app/routes/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/app/routes/helpers.py b/app/routes/helpers.py new file mode 100644 index 000000000..b7c77e8c7 --- /dev/null +++ b/app/routes/helpers.py @@ -0,0 +1,14 @@ +from flask import abort, make_response +from app.models.planet import Planet + +def validate_planet(planet_id): + try: + planet_id = int(planet_id) + except: + abort(make_response({"message":f"planet {planet_id} invalid"}, 400)) + + planet = Planet.query.get(planet_id) + if not planet: + return abort(make_response({"message":f"planet {planet_id} not found"}, 404)) + + return planet \ No newline at end of file diff --git a/app/routes.py b/app/routes/routes.py similarity index 60% rename from app/routes.py rename to app/routes/routes.py index 516275bc3..7caf17ccb 100644 --- a/app/routes.py +++ b/app/routes/routes.py @@ -1,28 +1,15 @@ from app import db from app.models.planet import Planet -from flask import Blueprint, jsonify, make_response, request, abort +from flask import Blueprint, jsonify, make_response, request, abort +from .helpers import validate_planet planets_bp = Blueprint("planets", __name__, url_prefix="/planets") -def validate_planet(planet_id): - try: - planet_id = int(planet_id) - except: - abort(make_response({"message":f"planet {planet_id} invalid"}, 400)) - - planet = Planet.query.get(planet_id) - if not planet: - return abort(make_response({"message":f"planet {planet_id} not found"}, 404)) - - return planet - - @planets_bp.route("", methods=["POST"]) def post_new_planet(): request_body = request.get_json() - new_planet = Planet(name=request_body["name"], - description=request_body["description"], - order_in_ss = request_body["order in solar system"] ) + + new_planet = Planet.create_planet(request_body) db.session.add(new_planet) db.session.commit() @@ -49,10 +36,6 @@ def update_planet(planet_id): update_body = request.get_json() planet = validate_planet(planet_id) - planet.name = update_body["name"] - planet.description = update_body["description"] - planet.order_in_ss = update_body["order in solar system"] - db.session.commit() return make_response(f"Planet {planet.id} successfully updated", 200) @@ -64,13 +47,3 @@ def delete_planet(planet_id): db.session.commit() return make_response(f"Planet {planet.id} successfully deleted", 200) - - -# @planets_bp.route("/", methods = ["GET"]) -# def get_one_planet(planet_id): -# planet_id = validate_planet(planet_id) - -# return jsonify(planet_id.to_json()), 200 - - - From 420a77f18294f5b66821fd3ef63286ff049840c1 Mon Sep 17 00:00:00 2001 From: Lauren Kleinert Date: Wed, 4 May 2022 12:17:08 -0700 Subject: [PATCH 10/12] Updated name of update_planet instance method, corrected syntax in PUT endpoint method --- app/models/planet.py | 2 +- app/routes/routes.py | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index 098cfe25c..5a608d270 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -14,7 +14,7 @@ def to_json(self): "order in solar system": self.order_in_ss } - def update(self, update_body): + def update_planet(self, update_body): self.name = update_body["name"] self.description = update_body["description"] self.order_in_ss = update_body["order in solar system"] diff --git a/app/routes/routes.py b/app/routes/routes.py index 7caf17ccb..765fb24ae 100644 --- a/app/routes/routes.py +++ b/app/routes/routes.py @@ -33,8 +33,10 @@ def read_one_planet(planet_id): @planets_bp.route("/", methods=["PUT"]) def update_planet(planet_id): - update_body = request.get_json() planet = validate_planet(planet_id) + request_body = request.get_json() + + planet.update_planet(request_body) db.session.commit() From 06bf6aab14742ecedfb974c9636448ae7dd55df1 Mon Sep 17 00:00:00 2001 From: Lauren Kleinert Date: Thu, 5 May 2022 11:12:09 -0700 Subject: [PATCH 11/12] Created .env file, refactored create_app(), created test folder and files, populated testconfit, created fixtures, create test get_planet for empty db --- app/__init__.py | 14 +++++++++++++- app/routes/routes.py | 12 ++++++++---- app/tests/__init__.py | 0 app/tests/conftest.py | 25 +++++++++++++++++++++++++ app/tests/test_routes.py | 8 ++++++++ 5 files changed, 54 insertions(+), 5 deletions(-) create mode 100644 app/tests/__init__.py create mode 100644 app/tests/conftest.py create mode 100644 app/tests/test_routes.py diff --git a/app/__init__.py b/app/__init__.py index 986b72804..050a36489 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,16 +1,28 @@ 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) diff --git a/app/routes/routes.py b/app/routes/routes.py index 765fb24ae..9e3878746 100644 --- a/app/routes/routes.py +++ b/app/routes/routes.py @@ -14,12 +14,16 @@ def post_new_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) @planets_bp.route("", methods=["GET"]) def read_all_planets(): - planets = Planet.query.all() + name_query = request.args.get("name") + if name_query: + planets = Planet.query.filter_by(name=name_query) + else: + planets = Planet.query.all() planets_response = [planet.to_json() for planet in planets] return jsonify(planets_response), 200 @@ -40,7 +44,7 @@ def update_planet(planet_id): db.session.commit() - return make_response(f"Planet {planet.id} successfully updated", 200) + return make_response(jsonify(f"Planet {planet.id} successfully updated"), 200) @planets_bp.route("/", methods=["DELETE"]) def delete_planet(planet_id): @@ -48,4 +52,4 @@ def delete_planet(planet_id): db.session.delete(planet) db.session.commit() - return make_response(f"Planet {planet.id} successfully deleted", 200) + return make_response(jsonify(f"Planet {planet.id} successfully deleted"), 200) diff --git a/app/tests/__init__.py b/app/tests/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/app/tests/conftest.py b/app/tests/conftest.py new file mode 100644 index 000000000..96d35f4c1 --- /dev/null +++ b/app/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() diff --git a/app/tests/test_routes.py b/app/tests/test_routes.py new file mode 100644 index 000000000..e1fa0a3b8 --- /dev/null +++ b/app/tests/test_routes.py @@ -0,0 +1,8 @@ +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 == [] From 91a9cc3ee8eabd07430bf11007a2d92bd1aa4692 Mon Sep 17 00:00:00 2001 From: Ivana Maldonado Date: Thu, 5 May 2022 15:01:42 -0400 Subject: [PATCH 12/12] created tests for one planet with and without data, all planets with data, and create one planet --- app/tests/conftest.py | 16 ++++++++++++ app/tests/test_routes.py | 56 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) diff --git a/app/tests/conftest.py b/app/tests/conftest.py index 96d35f4c1..573b90cd8 100644 --- a/app/tests/conftest.py +++ b/app/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,18 @@ def expire_session(sender, response, **extra): @pytest.fixture def client(app): return app.test_client() + +@pytest.fixture +def two_saved_planet(app): + saturn = Planet(name= "Saturn", + description="lots of rings", + order_in_ss="sixth" + ) + + earth = Planet(name= "Earth", + description="our planet", + order_in_ss="third" + ) + + db.session.add_all([saturn, earth]) + db.session.commit() diff --git a/app/tests/test_routes.py b/app/tests/test_routes.py index e1fa0a3b8..6e71bdebe 100644 --- a/app/tests/test_routes.py +++ b/app/tests/test_routes.py @@ -6,3 +6,59 @@ def test_get_all_planets_with_no_records(client): # Assert assert response.status_code == 200 assert response_body == [] + +def test_get_one_planet(client, two_saved_planet): + # Act + response = client.get("/planets/1") + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert response_body == { + "id": 1, + "name": "Saturn", + "description": "lots of rings", + "order in solar system": "sixth" + } + +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 == {"message": "planet 1 not found"} + +def test_get_all_planets_with_data(client, two_saved_planet): + # Act + response = client.get("/planets") + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert response_body == [{ + "id": 1, + "name": "Saturn", + "description": "lots of rings", + "order in solar system": "sixth" + }, + { + "id": 2, + "name": "Earth", + "description": "our planet", + "order in solar system": "third" + }] + +def test_create_one_planet(client): + # Act + response = client.post("/planets", json={ + "name": "Saturn", + "description": "lots of rings", + "order in solar system": "sixth" + }) + response_body = response.get_json() + + # Assert + assert response.status_code == 201 + assert response_body == "Planet Saturn successfully created" \ No newline at end of file