From 7e37962bd5e9f597be28c05ba27c3918462f1001 Mon Sep 17 00:00:00 2001 From: Katherine Guarnizo Date: Mon, 24 Apr 2023 18:05:58 -0400 Subject: [PATCH 01/26] Complete wave 1 --- app/__init__.py | 3 +++ app/routes.py | 28 +++++++++++++++++++++++++++- 2 files changed, 30 insertions(+), 1 deletion(-) 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 8e9dfe684..4488b964e 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,28 @@ -from flask import Blueprint +from flask import Blueprint, jsonify +planets_bp = Blueprint("planets", __name__, url_prefix="/planets") + +class Planet: + def __init__(self, id, name, description, num_moons): + self.id = id, + self.name = name, + self.description = description, + self.num_moons = num_moons + +planets = [ + Planet(1, "Mercury", "It's the first planet in our solar system", 0), + Planet(2, "Venus", "It's the second planet in our solar system", 0), + Planet(3, "Earth", "It's the third planet in our solar system", 1) +] + +@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, + "num_moons": planet.num_moons + }) + return jsonify(planets_response) \ No newline at end of file From 008e5638804bd50e30d5e2788c623afadea074c6 Mon Sep 17 00:00:00 2001 From: Madison Jackson Date: Mon, 24 Apr 2023 15:59:45 -0700 Subject: [PATCH 02/26] configuring wave 2 code --- app/routes.py | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index 4488b964e..e04134177 100644 --- a/app/routes.py +++ b/app/routes.py @@ -25,4 +25,21 @@ def handle_planets(): "description": planet.description, "num_moons": planet.num_moons }) - return jsonify(planets_response) \ No newline at end of file + return jsonify(planets_response) + +@planets_bp.route("/", methods=["GET"]) +def handle_planet(id): + # try: + id = int(id) + # except: + # return {"error message": f"planet {id} is invalid"}, 400 + + for planet in planets: + if planet.id == id: + return { + "id": planet.id, + "name": planet.name, + "description": planet.description, + "num_moons": planet.num_moons + } + # return {"error message": f"planet {id} not found"}, 404 \ No newline at end of file From fb0b10ced2912cb1f003e7e06cfe228565e3fb5c Mon Sep 17 00:00:00 2001 From: Katherine Guarnizo Date: Tue, 25 Apr 2023 15:30:01 -0400 Subject: [PATCH 03/26] fix TypeError from wave 2 --- app/routes.py | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/app/routes.py b/app/routes.py index e04134177..534d0ef1a 100644 --- a/app/routes.py +++ b/app/routes.py @@ -4,9 +4,9 @@ class Planet: def __init__(self, id, name, description, num_moons): - self.id = id, - self.name = name, - self.description = description, + self.id = id + self.name = name + self.description = description self.num_moons = num_moons planets = [ @@ -27,19 +27,20 @@ def handle_planets(): }) return jsonify(planets_response) -@planets_bp.route("/", methods=["GET"]) -def handle_planet(id): - # try: - id = int(id) - # except: - # return {"error message": f"planet {id} is invalid"}, 400 +@planets_bp.route("/", methods=["GET"]) +def handle_planet(planet_id): + try: + planet_id = int(planet_id) + except: + return {"error message": f"planet {planet_id} is invalid"}, 400 for planet in planets: - if planet.id == id: + if planet.id == planet_id: return { "id": planet.id, "name": planet.name, "description": planet.description, "num_moons": planet.num_moons } - # return {"error message": f"planet {id} not found"}, 404 \ No newline at end of file + return {"error message": f"planet {planet_id} not found"}, 404 + From 405a3fc96f4e5ade4cc1fbd9d45c0ab90435dd47 Mon Sep 17 00:00:00 2001 From: Katherine Guarnizo Date: Tue, 25 Apr 2023 16:05:35 -0400 Subject: [PATCH 04/26] Refactor wave 2 --- app/routes.py | 42 ++++++++++++++++++++++++++---------------- 1 file changed, 26 insertions(+), 16 deletions(-) diff --git a/app/routes.py b/app/routes.py index 534d0ef1a..be2dcb196 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 planets_bp = Blueprint("planets", __name__, url_prefix="/planets") @@ -9,6 +9,20 @@ def __init__(self, id, name, description, num_moons): self.description = description self.num_moons = num_moons + def to_dict(self): + return dict( + id=self.id, + name=self.name, + description=self.description, + num_moons=self.num_moons + ) + # return { + # "id": self.id, + # "name": self.name, + # "description": self.description, + # "num_moons": self.num_moons + # } + planets = [ Planet(1, "Mercury", "It's the first planet in our solar system", 0), Planet(2, "Venus", "It's the second planet in our solar system", 0), @@ -19,28 +33,24 @@ def __init__(self, id, name, description, num_moons): def handle_planets(): planets_response = [] for planet in planets: - planets_response.append({ - "id": planet.id, - "name": planet.name, - "description": planet.description, - "num_moons": planet.num_moons - }) + planets_response.append(planet.to_dict()) + return jsonify(planets_response) @planets_bp.route("/", methods=["GET"]) def handle_planet(planet_id): + planet = validate_planet(planet_id) + + return planet.to_dict() + + +def validate_planet(planet_id): try: planet_id = int(planet_id) except: - return {"error message": f"planet {planet_id} is invalid"}, 400 + abort(make_response({"error message": f"planet {planet_id} is invalid"}, 400)) for planet in planets: if planet.id == planet_id: - return { - "id": planet.id, - "name": planet.name, - "description": planet.description, - "num_moons": planet.num_moons - } - return {"error message": f"planet {planet_id} not found"}, 404 - + return planet + abort(make_response({"error message": f"planet {planet_id} not found"}, 404)) \ No newline at end of file From 5eca8d1691e7634bf5e109d5408bceadf271c07e Mon Sep 17 00:00:00 2001 From: Katherine Guarnizo Date: Tue, 25 Apr 2023 16:08:20 -0400 Subject: [PATCH 05/26] Refactor wave 1 --- app/routes.py | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/app/routes.py b/app/routes.py index be2dcb196..a98ce0e96 100644 --- a/app/routes.py +++ b/app/routes.py @@ -10,18 +10,12 @@ def __init__(self, id, name, description, num_moons): self.num_moons = num_moons def to_dict(self): - return dict( - id=self.id, - name=self.name, - description=self.description, - num_moons=self.num_moons - ) - # return { - # "id": self.id, - # "name": self.name, - # "description": self.description, - # "num_moons": self.num_moons - # } + return { + "id": self.id, + "name": self.name, + "description": self.description, + "num_moons": self.num_moons + } planets = [ Planet(1, "Mercury", "It's the first planet in our solar system", 0), From 1e43869b1299d506b78d83a7fbe45b5eddb50d99 Mon Sep 17 00:00:00 2001 From: Madison Jackson Date: Fri, 28 Apr 2023 11:51:30 -0700 Subject: [PATCH 06/26] fixing import error --- app/__init__.py | 13 ++++++++ app/routes.py | 86 ++++++++++++++++++++++++------------------------- 2 files changed, 56 insertions(+), 43 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index ab9eee40e..9ece5b765 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,9 +1,22 @@ 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/hello_books_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) diff --git a/app/routes.py b/app/routes.py index a98ce0e96..839dcf492 100644 --- a/app/routes.py +++ b/app/routes.py @@ -2,49 +2,49 @@ planets_bp = Blueprint("planets", __name__, url_prefix="/planets") -class Planet: - def __init__(self, id, name, description, num_moons): - self.id = id - self.name = name - self.description = description - self.num_moons = num_moons - - def to_dict(self): - return { - "id": self.id, - "name": self.name, - "description": self.description, - "num_moons": self.num_moons - } - -planets = [ - Planet(1, "Mercury", "It's the first planet in our solar system", 0), - Planet(2, "Venus", "It's the second planet in our solar system", 0), - Planet(3, "Earth", "It's the third planet in our solar system", 1) -] - -@planets_bp.route("", methods=["GET"]) -def handle_planets(): - planets_response = [] - for planet in planets: - planets_response.append(planet.to_dict()) - - return jsonify(planets_response) - -@planets_bp.route("/", methods=["GET"]) -def handle_planet(planet_id): - planet = validate_planet(planet_id) - - return planet.to_dict() +# class Planet: +# def __init__(self, id, name, description, num_moons): +# self.id = id +# self.name = name +# self.description = description +# self.num_moons = num_moons + +# def to_dict(self): +# return { +# "id": self.id, +# "name": self.name, +# "description": self.description, +# "num_moons": self.num_moons +# } + +# planets = [ +# Planet(1, "Mercury", "It's the first planet in our solar system", 0), +# Planet(2, "Venus", "It's the second planet in our solar system", 0), +# Planet(3, "Earth", "It's the third planet in our solar system", 1) +# ] + +# @planets_bp.route("", methods=["GET"]) +# def handle_planets(): +# planets_response = [] +# for planet in planets: +# planets_response.append(planet.to_dict()) + +# return jsonify(planets_response) + +# @planets_bp.route("/", methods=["GET"]) +# def handle_planet(planet_id): +# planet = validate_planet(planet_id) + +# return planet.to_dict() -def validate_planet(planet_id): - try: - planet_id = int(planet_id) - except: - abort(make_response({"error message": f"planet {planet_id} is invalid"}, 400)) +# def validate_planet(planet_id): + # try: + # planet_id = int(planet_id) + # except: + # abort(make_response({"error message": f"planet {planet_id} is invalid"}, 400)) - for planet in planets: - if planet.id == planet_id: - return planet - abort(make_response({"error message": f"planet {planet_id} not found"}, 404)) \ No newline at end of file + # for planet in planets: + # if planet.id == planet_id: + # return planet + # abort(make_response({"error message": f"planet {planet_id} not found"}, 404)) \ No newline at end of file From cea2ec6b6b78b18e7712fbc67fd753214e9c2857 Mon Sep 17 00:00:00 2001 From: Madison Jackson Date: Fri, 28 Apr 2023 11:58:22 -0700 Subject: [PATCH 07/26] adding migrations --- app/models/__init__.py | 0 app/models/planet.py | 7 +++ migrations/README | 1 + migrations/alembic.ini | 45 ++++++++++++++++++ migrations/env.py | 96 +++++++++++++++++++++++++++++++++++++++ migrations/script.py.mako | 24 ++++++++++ 6 files changed, 173 insertions(+) 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 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..1b9c0501a --- /dev/null +++ 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) + num_moons = db.Column(db.Integer) \ No newline at end of file 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 ab5a2ad132d0c5fda4d8543bd0113cdee99e298f Mon Sep 17 00:00:00 2001 From: Madison Jackson Date: Fri, 28 Apr 2023 12:11:17 -0700 Subject: [PATCH 08/26] update config str --- app/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 9ece5b765..1873b6ff1 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -10,13 +10,13 @@ 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/hello_books_development' + 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) From 2f7d6ec122dd3efe55d66e8f16f8e69a1577b4b0 Mon Sep 17 00:00:00 2001 From: Madison Jackson Date: Sun, 30 Apr 2023 17:12:41 -0700 Subject: [PATCH 09/26] resolved version issue on migration --- .../c2db3d6bd34d_adds_planet_model.py | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 migrations/versions/c2db3d6bd34d_adds_planet_model.py diff --git a/migrations/versions/c2db3d6bd34d_adds_planet_model.py b/migrations/versions/c2db3d6bd34d_adds_planet_model.py new file mode 100644 index 000000000..2ea345111 --- /dev/null +++ b/migrations/versions/c2db3d6bd34d_adds_planet_model.py @@ -0,0 +1,34 @@ +"""adds Planet model + +Revision ID: c2db3d6bd34d +Revises: +Create Date: 2023-04-30 17:09:28.989027 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'c2db3d6bd34d' +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('num_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 252bc3dfa309525cb49adbb4bcfca9e0480def50 Mon Sep 17 00:00:00 2001 From: Katherine Guarnizo Date: Sun, 30 Apr 2023 20:14:14 -0400 Subject: [PATCH 10/26] uninstall requirements and reinstall --- app/__init__.py | 2 +- .../6f10d35aed47_adds_planet_model.py | 34 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 migrations/versions/6f10d35aed47_adds_planet_model.py diff --git a/app/__init__.py b/app/__init__.py index 9ece5b765..63e466d16 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -10,7 +10,7 @@ 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/hello_books_development' + app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system_development' db.init_app(app) migrate.init_app(app, db) diff --git a/migrations/versions/6f10d35aed47_adds_planet_model.py b/migrations/versions/6f10d35aed47_adds_planet_model.py new file mode 100644 index 000000000..cdd58db95 --- /dev/null +++ b/migrations/versions/6f10d35aed47_adds_planet_model.py @@ -0,0 +1,34 @@ +"""adds Planet model + +Revision ID: 6f10d35aed47 +Revises: +Create Date: 2023-04-28 19:09:55.071118 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '6f10d35aed47' +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('num_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 d0a3c2faa8030cb390f0b3820365541e366d34a5 Mon Sep 17 00:00:00 2001 From: Katherine Guarnizo Date: Sun, 30 Apr 2023 20:55:30 -0400 Subject: [PATCH 11/26] Create post method --- app/routes.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index 839dcf492..03082e360 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,7 +1,23 @@ -from flask import Blueprint, jsonify, abort, make_response +from app import db +from app.models.planet import Planet +from flask import Blueprint, jsonify, abort, make_response, request planets_bp = Blueprint("planets", __name__, url_prefix="/planets") +@planets_bp.route("", methods=["POST"]) +def create_planets(): + request_body = request.get_json() + new_planet = Planet(name = request_body["name"], + description = request_body["description"], + num_moons = request_body["num_moons"]) + + db.session.add(new_planet) + db.session.commit() + + return make_response(f"Planet {new_planet.name} successfully created, 201") + + + # class Planet: # def __init__(self, id, name, description, num_moons): # self.id = id From 7959c97ebc5a3358be4b147f6f8922af5a837c5e Mon Sep 17 00:00:00 2001 From: Madison Jackson Date: Sun, 30 Apr 2023 18:26:45 -0700 Subject: [PATCH 12/26] finished wave 3; setting up for wave 4 --- app/models/planet.py | 6 +++--- app/routes.py | 22 ++++++++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index 1b9c0501a..de8b3dc04 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -2,6 +2,6 @@ class Planet(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) - name = db.Column(db.String) - description = db.Column(db.String) - num_moons = db.Column(db.Integer) \ No newline at end of file + name = db.Column(db.String, nullable=False) + description = db.Column(db.String, nullable=False) + num_moons = db.Column(db.Integer, nullable=False) \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 03082e360..f27add889 100644 --- a/app/routes.py +++ b/app/routes.py @@ -16,6 +16,28 @@ def create_planets(): 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() + for planet in planets: + planets_response.append( + { + "id": planet.id, + "name": planet.name, + "description": planet.description, + "num_moons": planet.num_moons + } + ) + return jsonify(planets_response) + +@planets_bp.route("", methods=["PATCH"]) +def update_planet(): + request_update = request.get_json() + update_planet = Planet() #SQLALCHEMY + +@planets_bp.route("", methods=["DELETE"]) + # class Planet: From c82da1b0c74c54bca042e02c407eaeb8f1eb99e4 Mon Sep 17 00:00:00 2001 From: Katherine Guarnizo Date: Tue, 2 May 2023 14:11:34 -0400 Subject: [PATCH 13/26] Complete wave 4 --- app/routes.py | 80 ++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 57 insertions(+), 23 deletions(-) diff --git a/app/routes.py b/app/routes.py index f27add889..ab1636f84 100644 --- a/app/routes.py +++ b/app/routes.py @@ -31,12 +31,64 @@ def read_all_planets(): ) return jsonify(planets_response) -@planets_bp.route("", methods=["PATCH"]) -def update_planet(): - request_update = request.get_json() - update_planet = Planet() #SQLALCHEMY -@planets_bp.route("", methods=["DELETE"]) +@planets_bp.route("/", methods=["GET"]) +def read_one_planet(planet_id): + planet = validate_planet(planet_id) + + return jsonify({ + "id": planet.id, + "name": planet.name, + "description": planet.description, + "num_moons": planet.num_moons + }) + + +@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.num_moons = request_body["num_moons"] + + db.session.commit() + + 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") + + +def validate_planet(planet_id): + try: + planet_id = int(planet_id) + except: + abort(make_response({"error message": f"planet {planet_id} is invalid"}, 400)) + + planet = Planet.query.get(planet_id) + + + if not planet: + abort(make_response({"error message": f"planet {planet_id} not found"}, 404)) + + return planet + + + +# @planets_bp.route("", methods=["PATCH"]) +# def update_planet(): +# request_update = request.get_json() +# update_planet = Planet() #SQLALCHEMY + +# @planets_bp.route("", methods=["DELETE"]) @@ -68,21 +120,3 @@ def update_planet(): # planets_response.append(planet.to_dict()) # return jsonify(planets_response) - -# @planets_bp.route("/", methods=["GET"]) -# def handle_planet(planet_id): -# planet = validate_planet(planet_id) - -# return planet.to_dict() - - -# def validate_planet(planet_id): - # try: - # planet_id = int(planet_id) - # except: - # abort(make_response({"error message": f"planet {planet_id} is invalid"}, 400)) - - # for planet in planets: - # if planet.id == planet_id: - # return planet - # abort(make_response({"error message": f"planet {planet_id} not found"}, 404)) \ No newline at end of file From 8760fd5af17c9ac2218bdfab6f9158885109b879 Mon Sep 17 00:00:00 2001 From: Madison Jackson Date: Tue, 2 May 2023 11:12:20 -0700 Subject: [PATCH 14/26] will fix merge --- app/routes.py | 65 +++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 50 insertions(+), 15 deletions(-) diff --git a/app/routes.py b/app/routes.py index f27add889..913c06b03 100644 --- a/app/routes.py +++ b/app/routes.py @@ -4,6 +4,21 @@ planets_bp = Blueprint("planets", __name__, url_prefix="/planets") +#verify if a planet exists +def validate_planet(planet_id): + try: + planet_id = int(planet_id) + except: + abort(make_response({"error message": f"planet {planet_id} is invalid"}, 400)) + + planet = Planet.query.get(planet_id) + + if not planet: + abort(make_response({"error message": f"planet {planet_id} not found"}, 404)) + + return planet + +#creating new planets to add to the table @planets_bp.route("", methods=["POST"]) def create_planets(): request_body = request.get_json() @@ -16,6 +31,7 @@ def create_planets(): return make_response(f"Planet {new_planet.name} successfully created, 201") +#receiving all planets info @planets_bp.route("", methods=["GET"]) def read_all_planets(): planets_response = [] @@ -31,13 +47,42 @@ def read_all_planets(): ) return jsonify(planets_response) -@planets_bp.route("", methods=["PATCH"]) -def update_planet(): - request_update = request.get_json() - update_planet = Planet() #SQLALCHEMY +#receiving a specific planet's info +@planets_bp.route("/", methods = ["GET"]) +def read_one_planet(planet_id): + planet = validate_planet(planet_id) + return jsonify( + { + "id": planet.id, + "name": planet.name, + "description": planet.description, + "num_moons": planet.num_moons + } + ) + +#update planet info +@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.num_moons = request_body["num_moons"] -@planets_bp.route("", methods=["DELETE"]) + db.session.commit() + + return make_response(f"Planet #{planet_id} successfully updated.") + +#delete planet +@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.") # class Planet: @@ -76,13 +121,3 @@ def update_planet(): # return planet.to_dict() -# def validate_planet(planet_id): - # try: - # planet_id = int(planet_id) - # except: - # abort(make_response({"error message": f"planet {planet_id} is invalid"}, 400)) - - # for planet in planets: - # if planet.id == planet_id: - # return planet - # abort(make_response({"error message": f"planet {planet_id} not found"}, 404)) \ No newline at end of file From 57894cdae870c3a15db9d2df40c9c0367496b98a Mon Sep 17 00:00:00 2001 From: Madison Jackson Date: Tue, 2 May 2023 11:18:26 -0700 Subject: [PATCH 15/26] fixing merge conflict x2 --- app/routes.py | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/app/routes.py b/app/routes.py index 299c37dd8..4c69fb77e 100644 --- a/app/routes.py +++ b/app/routes.py @@ -4,21 +4,6 @@ planets_bp = Blueprint("planets", __name__, url_prefix="/planets") -#verify if a planet exists -def validate_planet(planet_id): - try: - planet_id = int(planet_id) - except: - abort(make_response({"error message": f"planet {planet_id} is invalid"}, 400)) - - planet = Planet.query.get(planet_id) - - if not planet: - abort(make_response({"error message": f"planet {planet_id} not found"}, 404)) - - return planet - -#creating new planets to add to the table @planets_bp.route("", methods=["POST"]) def create_planets(): request_body = request.get_json() @@ -31,7 +16,6 @@ def create_planets(): return make_response(f"Planet {new_planet.name} successfully created, 201") -#receiving all planets info @planets_bp.route("", methods=["GET"]) def read_all_planets(): planets_response = [] @@ -91,7 +75,6 @@ def validate_planet(planet_id): planet = Planet.query.get(planet_id) - if not planet: abort(make_response({"error message": f"planet {planet_id} not found"}, 404)) From b46750aa233d63f4b3babe09c34c7bb41f66fdac Mon Sep 17 00:00:00 2001 From: Madison Jackson Date: Wed, 3 May 2023 11:35:40 -0700 Subject: [PATCH 16/26] started wave 6: setup --- app/__init__.py | 15 +++++++++++++-- tests/__init__.py | 0 tests/conftest.py | 25 +++++++++++++++++++++++++ tests/test_routes.py | 8 ++++++++ 4 files changed, 46 insertions(+), 2 deletions(-) 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 1873b6ff1..b4756447d 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,16 +1,27 @@ 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_TRACK_MODIFICATIONS'] = False + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get( + "SQLALCHEMY_DATABASE_URI") + + else: + app.config["TESTING"] = True + app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get( + "SQLALCHEMY_TEST_DATABASE_URI") db.init_app(app) migrate.init_app(app, db) 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..12c88681b --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,25 @@ +import pytest +from app import create_app, db +from flask.signals import request_finished +from app.models.planet import Planet + + +@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..1124a9765 --- /dev/null +++ b/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 == [] \ No newline at end of file From 3507377f3f5418c8484cefc2499ececb89e4d164 Mon Sep 17 00:00:00 2001 From: Katherine Guarnizo Date: Wed, 3 May 2023 18:48:51 -0400 Subject: [PATCH 17/26] create tests for get/post one planet --- app/routes.py | 2 +- tests/conftest.py | 14 +++++++++++++- tests/test_routes.py | 33 ++++++++++++++++++++++++++++++++- 3 files changed, 46 insertions(+), 3 deletions(-) diff --git a/app/routes.py b/app/routes.py index 4c69fb77e..c9dddd28e 100644 --- a/app/routes.py +++ b/app/routes.py @@ -14,7 +14,7 @@ def create_planets(): 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(): diff --git a/tests/conftest.py b/tests/conftest.py index 12c88681b..2195498cd 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -22,4 +22,16 @@ 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 one_planet(app): + planet = Planet( + name = "Mercury", + description = "It's the first planet in our solar system", + num_moons = 0 + ) + db.session.add(planet) + db.session.commit() + return planet + diff --git a/tests/test_routes.py b/tests/test_routes.py index 1124a9765..3a8104f7c 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -1,3 +1,5 @@ +from app.models.planet import Planet + def test_get_all_planets_with_no_records(client): # Act response = client.get("/planets") @@ -5,4 +7,33 @@ def test_get_all_planets_with_no_records(client): # Assert assert response.status_code == 200 - assert response_body == [] \ No newline at end of file + assert response_body == [] + +def test_get_one_planet_returns_seeded_planet(client, one_planet): + response = client.get(f"/planets/{one_planet.id}") + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body["id"] == one_planet.id + assert response_body["name"] == one_planet.name + assert response_body["description"] == one_planet.description + assert response_body["num_moons"] == one_planet.num_moons + + +def test_create_planet_happy_path(client): + # arrange + EXPECTED_PLANET = { + "name": "Mercury", + "description": "It's the first planet in our solar system", + "num_moons": 0 + } + + response = client.post("/planets", json=EXPECTED_PLANET) + response_body = response.get_json() + + actual_planet = Planet.query.get(1) + assert response.status_code == 201 + assert response_body == f"Planet {EXPECTED_PLANET['name']} successfully created" + assert actual_planet.name == EXPECTED_PLANET["name"] + assert actual_planet.description == EXPECTED_PLANET["description"] + assert actual_planet.num_moons == EXPECTED_PLANET["num_moons"] \ No newline at end of file From 89226e26a5202a4138eec75fc9faf51e7faec4eb Mon Sep 17 00:00:00 2001 From: Katherine Guarnizo Date: Wed, 3 May 2023 19:47:50 -0400 Subject: [PATCH 18/26] Complete wave 6 and create tests for 404 error/array of planets --- tests/conftest.py | 17 +++++++++++++++++ tests/test_routes.py | 33 +++++++++++++++++++++++++++++++-- 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index 2195498cd..565ae00f8 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -35,3 +35,20 @@ def one_planet(app): db.session.commit() return planet + +@pytest.fixture +def saved_planets(app, one_planet): + # Arrange + # planet_one = Planet(name = "Mercury", + # description = "It's the first planet in our solar system", + # num_moons = 0) + planet_two = Planet(name = "Venus", + description = "It's the second planet in our solar system", + num_moons = 0) + planet_three = Planet(name = "Earth", + description = "It's the third planet in our solar system", + num_moons = 1) + + db.session.add_all([one_planet, planet_two, planet_three]) + db.session.commit() + diff --git a/tests/test_routes.py b/tests/test_routes.py index 3a8104f7c..9810e5a4e 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -27,7 +27,7 @@ def test_create_planet_happy_path(client): "description": "It's the first planet in our solar system", "num_moons": 0 } - + response = client.post("/planets", json=EXPECTED_PLANET) response_body = response.get_json() @@ -36,4 +36,33 @@ def test_create_planet_happy_path(client): assert response_body == f"Planet {EXPECTED_PLANET['name']} successfully created" assert actual_planet.name == EXPECTED_PLANET["name"] assert actual_planet.description == EXPECTED_PLANET["description"] - assert actual_planet.num_moons == EXPECTED_PLANET["num_moons"] \ No newline at end of file + assert actual_planet.num_moons == EXPECTED_PLANET["num_moons"] + + +def test_get_one_planet_id_not_found(client, one_planet): + # Act + response = client.get("/planets/4") + response_body = response.get_json() + + # Assert + assert response.status_code == 404 + assert response_body == {"error message":"planet 4 not found"} + + +def test_get_all_planets_with_saved_records(client, saved_planets): + #Assert + EXPECTED_PLANET_ONE_NAME= {"name": "Mercury"} + EXPECTED_PLANET_TWO_DESCRIPTION= {"description": "It's the second planet in our solar system"} + EXPECTED_PLANET_THREE_NUM_MOONS= {"num_moons": 1} + + response = client.get("/planets", json=EXPECTED_PLANET_ONE_NAME) + response_saved_body = response.get_json() + + planet_one = Planet.query.get(1) + planet_two = Planet.query.get(2) + planet_three = Planet.query.get(3) + assert response.status_code == 200 + assert len(response_saved_body) == 3 + assert planet_one.name == EXPECTED_PLANET_ONE_NAME["name"] + assert planet_two.description == EXPECTED_PLANET_TWO_DESCRIPTION["description"] + assert planet_three.num_moons == EXPECTED_PLANET_THREE_NUM_MOONS["num_moons"] From 026110ab74d14c98c847d377ebbb475a90572ff8 Mon Sep 17 00:00:00 2001 From: Madison Jackson Date: Thu, 4 May 2023 11:35:51 -0700 Subject: [PATCH 19/26] refactoring; update model with classmethod --- app/models/planet.py | 18 +++++++++++++++++- app/routes.py | 22 +++------------------- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index de8b3dc04..59cde40ce 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -4,4 +4,20 @@ class Planet(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String, nullable=False) description = db.Column(db.String, nullable=False) - num_moons = db.Column(db.Integer, nullable=False) \ No newline at end of file + num_moons = db.Column(db.Integer, nullable=False) + + def to_dict(self): + return { + "id": self.id, + "name": self.name, + "description": self.description, + "num_moons": self.num_moons + } + + @classmethod + def from_dict(cls, data_dict): + return cls( + name = data_dict["name"], + description = data_dict["description"], + num_moons = data_dict["num_moons"] + ) \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index c9dddd28e..b413b566f 100644 --- a/app/routes.py +++ b/app/routes.py @@ -7,9 +7,7 @@ @planets_bp.route("", methods=["POST"]) def create_planets(): request_body = request.get_json() - new_planet = Planet(name = request_body["name"], - description = request_body["description"], - num_moons = request_body["num_moons"]) + new_planet = Planet.from_dict(request_body) db.session.add(new_planet) db.session.commit() @@ -18,17 +16,8 @@ def create_planets(): @planets_bp.route("", methods=["GET"]) 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, - "num_moons": planet.num_moons - } - ) + planets_response = [planet.to_dict() for planet in planets] return jsonify(planets_response) @@ -36,12 +25,7 @@ def read_all_planets(): def read_one_planet(planet_id): planet = validate_planet(planet_id) - return jsonify({ - "id": planet.id, - "name": planet.name, - "description": planet.description, - "num_moons": planet.num_moons - }) + return jsonify(planet.to_dict()) @planets_bp.route("/", methods=["PUT"]) From d04893663a14abcd5ea54efb0ad4b91987f368ec Mon Sep 17 00:00:00 2001 From: Madison Jackson Date: Thu, 4 May 2023 12:00:49 -0700 Subject: [PATCH 20/26] updated model; started new test for null error --- app/routes.py | 13 ++++++++----- tests/conftest.py | 10 ++++++++++ tests/test_routes.py | 4 ++++ 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/app/routes.py b/app/routes.py index b413b566f..2c3ea02f9 100644 --- a/app/routes.py +++ b/app/routes.py @@ -7,12 +7,15 @@ @planets_bp.route("", methods=["POST"]) def create_planets(): request_body = request.get_json() - new_planet = Planet.from_dict(request_body) - - db.session.add(new_planet) - db.session.commit() + try: + new_planet = Planet.from_dict(request_body) + db.session.add(new_planet) + db.session.commit() - return make_response(jsonify(f"Planet {new_planet.name} successfully created"), 201) + return make_response(jsonify(f"Planet {new_planet.name} successfully created"), 201) + + except KeyError as error: + abort(make_response({"error message": f"missing required value: {error}"}, 400)) @planets_bp.route("", methods=["GET"]) def read_all_planets(): diff --git a/tests/conftest.py b/tests/conftest.py index 565ae00f8..3b0de85a6 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -52,3 +52,13 @@ def saved_planets(app, one_planet): db.session.add_all([one_planet, planet_two, planet_three]) db.session.commit() +# @pytest.fixture +# def error_planet(app): +# planet = Planet( +# name = "Pluto", +# description = "It's the first planet in our solar system", +# num_moons = +# ) +# db.session.add(planet) +# db.session.commit() +# return planet \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py index 9810e5a4e..a75d5a5c2 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -66,3 +66,7 @@ def test_get_all_planets_with_saved_records(client, saved_planets): assert planet_one.name == EXPECTED_PLANET_ONE_NAME["name"] assert planet_two.description == EXPECTED_PLANET_TWO_DESCRIPTION["description"] assert planet_three.num_moons == EXPECTED_PLANET_THREE_NUM_MOONS["num_moons"] + + +def test_create_planet_raises_key_error_with_missing_atr(client, error_planet): + From 0a5bac27eb49e2f8e38106954fbfc0807d3c7dad Mon Sep 17 00:00:00 2001 From: Madison Jackson Date: Thu, 4 May 2023 17:49:48 -0700 Subject: [PATCH 21/26] finished 400 error test --- tests/conftest.py | 5 ++--- tests/test_routes.py | 14 ++++++++++++-- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index 3b0de85a6..d7d5185e3 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -54,10 +54,9 @@ def saved_planets(app, one_planet): # @pytest.fixture # def error_planet(app): -# planet = Planet( +# planet = Planet( # name = "Pluto", -# description = "It's the first planet in our solar system", -# num_moons = +# description = "It's the first planet in our solar system" # ) # db.session.add(planet) # db.session.commit() diff --git a/tests/test_routes.py b/tests/test_routes.py index a75d5a5c2..3a38bf275 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -68,5 +68,15 @@ def test_get_all_planets_with_saved_records(client, saved_planets): assert planet_three.num_moons == EXPECTED_PLANET_THREE_NUM_MOONS["num_moons"] -def test_create_planet_raises_key_error_with_missing_atr(client, error_planet): - +def test_create_planet_raises_key_error_with_missing_atr(client): + error_planet = { + "name": "Pluto", + "description": "It's the first planet in our solar system" + } + + response = client.post("/planets", json=error_planet) + response_body = response.get_json() + + assert response.status_code == 400 + assert response_body == {"error message": f"missing required value: 'num_moons'"}, 400 + From 7e5c9dcea44c1643736adcaaaf2f63c2e554d01f Mon Sep 17 00:00:00 2001 From: Katherine Guarnizo Date: Thu, 4 May 2023 20:52:21 -0400 Subject: [PATCH 22/26] commit to pull latest changes --- tests/test_routes.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_routes.py b/tests/test_routes.py index 9810e5a4e..28d964d03 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -55,7 +55,7 @@ def test_get_all_planets_with_saved_records(client, saved_planets): EXPECTED_PLANET_TWO_DESCRIPTION= {"description": "It's the second planet in our solar system"} EXPECTED_PLANET_THREE_NUM_MOONS= {"num_moons": 1} - response = client.get("/planets", json=EXPECTED_PLANET_ONE_NAME) + response = client.get("/planets") response_saved_body = response.get_json() planet_one = Planet.query.get(1) From cb2c0596378b7da44310d75b538928106c29d3f5 Mon Sep 17 00:00:00 2001 From: Katherine Guarnizo Date: Thu, 4 May 2023 21:55:26 -0400 Subject: [PATCH 23/26] Complete wave 4 --- app/helper.py | 16 +++++++++++ app/routes.py | 68 +++++++++++--------------------------------- tests/conftest.py | 14 --------- tests/test_routes.py | 2 +- 4 files changed, 34 insertions(+), 66 deletions(-) create mode 100644 app/helper.py diff --git a/app/helper.py b/app/helper.py new file mode 100644 index 000000000..525c33cd5 --- /dev/null +++ b/app/helper.py @@ -0,0 +1,16 @@ +from app import db +from app.models.planet import Planet +from flask import Blueprint, jsonify, abort, make_response, request + +def validate_model(cls,model_id): + try: + model_id = int(model_id) + except: + abort(make_response({"error message": f"{cls.__name__} {model_id} is invalid"}, 400)) + + model = Planet.query.get(model_id) + + if not model: + abort(make_response({"error message": f"{cls.__name__} {model_id} not found"}, 404)) + + return model \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 2c3ea02f9..9b9f361e1 100644 --- a/app/routes.py +++ b/app/routes.py @@ -2,6 +2,7 @@ from app.models.planet import Planet from flask import Blueprint, jsonify, abort, make_response, request + planets_bp = Blueprint("planets", __name__, url_prefix="/planets") @planets_bp.route("", methods=["POST"]) @@ -19,21 +20,26 @@ def create_planets(): @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_dict() for planet in planets] return jsonify(planets_response) @planets_bp.route("/", methods=["GET"]) def read_one_planet(planet_id): - planet = validate_planet(planet_id) + planet = validate_model(Planet,planet_id) return jsonify(planet.to_dict()) @planets_bp.route("/", methods=["PUT"]) def update_planet(planet_id): - planet = validate_planet(planet_id) + planet = validate_model(planet_id) request_body = request.get_json() planet.name = request_body["name"] @@ -46,7 +52,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_id) db.session.delete(planet) db.session.commit() @@ -54,55 +60,15 @@ def delete_planet(planet_id): return make_response(f"Planet {planet.id} successfully deleted") -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({"error message": f"planet {planet_id} is invalid"}, 400)) + abort(make_response({"error message": f"{cls.__name__} {model_id} is invalid"}, 400)) - planet = Planet.query.get(planet_id) + model = Planet.query.get(model_id) - if not planet: - abort(make_response({"error message": f"planet {planet_id} not found"}, 404)) + if not model: + abort(make_response({"error message": f"{cls.__name__} {model_id} not found"}, 404)) - return planet - - - -# @planets_bp.route("", methods=["PATCH"]) -# def update_planet(): -# request_update = request.get_json() -# update_planet = Planet() #SQLALCHEMY - -# @planets_bp.route("", methods=["DELETE"]) - - - -# class Planet: -# def __init__(self, id, name, description, num_moons): -# self.id = id -# self.name = name -# self.description = description -# self.num_moons = num_moons - -# def to_dict(self): -# return { -# "id": self.id, -# "name": self.name, -# "description": self.description, -# "num_moons": self.num_moons -# } - -# planets = [ -# Planet(1, "Mercury", "It's the first planet in our solar system", 0), -# Planet(2, "Venus", "It's the second planet in our solar system", 0), -# Planet(3, "Earth", "It's the third planet in our solar system", 1) -# ] - -# @planets_bp.route("", methods=["GET"]) -# def handle_planets(): -# planets_response = [] -# for planet in planets: -# planets_response.append(planet.to_dict()) - -# return jsonify(planets_response) + return model diff --git a/tests/conftest.py b/tests/conftest.py index d7d5185e3..8112a1b95 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -38,10 +38,6 @@ def one_planet(app): @pytest.fixture def saved_planets(app, one_planet): - # Arrange - # planet_one = Planet(name = "Mercury", - # description = "It's the first planet in our solar system", - # num_moons = 0) planet_two = Planet(name = "Venus", description = "It's the second planet in our solar system", num_moons = 0) @@ -51,13 +47,3 @@ def saved_planets(app, one_planet): db.session.add_all([one_planet, planet_two, planet_three]) db.session.commit() - -# @pytest.fixture -# def error_planet(app): -# planet = Planet( -# name = "Pluto", -# description = "It's the first planet in our solar system" -# ) -# db.session.add(planet) -# db.session.commit() -# return planet \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py index 5b43a8922..83d9fb08b 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -46,7 +46,7 @@ def test_get_one_planet_id_not_found(client, one_planet): # Assert assert response.status_code == 404 - assert response_body == {"error message":"planet 4 not found"} + assert response_body == {"error message":"Planet 4 not found"} def test_get_all_planets_with_saved_records(client, saved_planets): From 10b697163440c8c91a86721a20fb020b1fefa145 Mon Sep 17 00:00:00 2001 From: Madison Jackson Date: Fri, 5 May 2023 09:32:19 -0700 Subject: [PATCH 24/26] completed solar system --- app/helper.py | 2 +- app/routes.py | 23 ++++++++--------------- tests/test_routes.py | 3 +++ 3 files changed, 12 insertions(+), 16 deletions(-) diff --git a/app/helper.py b/app/helper.py index 525c33cd5..7d44a01f5 100644 --- a/app/helper.py +++ b/app/helper.py @@ -8,7 +8,7 @@ def validate_model(cls,model_id): except: abort(make_response({"error message": f"{cls.__name__} {model_id} is invalid"}, 400)) - model = Planet.query.get(model_id) + model = cls.query.get(model_id) if not model: abort(make_response({"error message": f"{cls.__name__} {model_id} not found"}, 404)) diff --git a/app/routes.py b/app/routes.py index 9b9f361e1..0cba42f57 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,5 +1,6 @@ from app import db from app.models.planet import Planet +from app.helper import validate_model from flask import Blueprint, jsonify, abort, make_response, request @@ -21,8 +22,14 @@ def create_planets(): @planets_bp.route("", methods=["GET"]) def read_all_planets(): name_query = request.args.get("name") + description_query = request.args.get("description") + num_moons_query = request.args.get("num_moons") if name_query: planets = Planet.query.filter_by(name = name_query) + + if num_moons_query: + planets = Planet.query.filter_by(num_moons = num_moons_query) + else: planets = Planet.query.all() @@ -57,18 +64,4 @@ def delete_planet(planet_id): db.session.delete(planet) db.session.commit() - return make_response(f"Planet {planet.id} successfully deleted") - - -def validate_model(cls,model_id): - try: - model_id = int(model_id) - except: - abort(make_response({"error message": f"{cls.__name__} {model_id} is invalid"}, 400)) - - model = Planet.query.get(model_id) - - if not model: - abort(make_response({"error message": f"{cls.__name__} {model_id} not found"}, 404)) - - return model + return make_response(f"Planet {planet.id} successfully deleted") \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py index 83d9fb08b..ef96eb293 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -80,3 +80,6 @@ def test_create_planet_raises_key_error_with_missing_atr(client): assert response.status_code == 400 assert response_body == {"error message": f"missing required value: 'num_moons'"}, 400 + + + From 5f823b48b086e17aab3ada70919c073444928b64 Mon Sep 17 00:00:00 2001 From: Katherine Guarnizo Date: Mon, 8 May 2023 17:28:24 -0400 Subject: [PATCH 25/26] Create star class and register blueprint --- app/__init__.py | 8 +++++++- app/models/star.py | 17 +++++++++++++++++ app/{routes.py => planet_routes.py} | 0 app/star_routes.py | 4 ++++ 4 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 app/models/star.py rename app/{routes.py => planet_routes.py} (100%) create mode 100644 app/star_routes.py diff --git a/app/__init__.py b/app/__init__.py index b4756447d..8a7d9b01b 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -28,7 +28,13 @@ def create_app(test_config=None): from app.models.planet import Planet - from .routes import planets_bp + from .planet_routes import planets_bp app.register_blueprint(planets_bp) + from app.models.star import Star + + from .star_routes import star_bp + app.register_blueprint(star_bp) + + return app diff --git a/app/models/star.py b/app/models/star.py new file mode 100644 index 000000000..8ca040667 --- /dev/null +++ b/app/models/star.py @@ -0,0 +1,17 @@ +from app import db + +class Star(db.Model): + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + name = db.Column(db.String, nullable=False) + + def to_dict(self): + return { + "id": self.id, + "name": self.name + } + + @classmethod + def from_dict(cls, data_dict): + return cls( + name = data_dict["name"] + ) \ No newline at end of file diff --git a/app/routes.py b/app/planet_routes.py similarity index 100% rename from app/routes.py rename to app/planet_routes.py diff --git a/app/star_routes.py b/app/star_routes.py new file mode 100644 index 000000000..31f0aaca7 --- /dev/null +++ b/app/star_routes.py @@ -0,0 +1,4 @@ +from flask import Blueprint, jsonify, abort, make_response, request +from app import db + +star_bp = Blueprint("stars", __name__, url_prefix="/stars") \ No newline at end of file From 8b951a526e42d4837a48df6473f24ca641192a7c Mon Sep 17 00:00:00 2001 From: Madison Jackson Date: Mon, 8 May 2023 15:39:18 -0700 Subject: [PATCH 26/26] fixed changes from star practice --- app/__init__.py | 4 ---- app/models/star.py | 17 ----------------- app/star_routes.py | 4 ---- 3 files changed, 25 deletions(-) delete mode 100644 app/models/star.py delete mode 100644 app/star_routes.py diff --git a/app/__init__.py b/app/__init__.py index 8a7d9b01b..9e4e3fbf1 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -31,10 +31,6 @@ def create_app(test_config=None): from .planet_routes import planets_bp app.register_blueprint(planets_bp) - from app.models.star import Star - - from .star_routes import star_bp - app.register_blueprint(star_bp) return app diff --git a/app/models/star.py b/app/models/star.py deleted file mode 100644 index 8ca040667..000000000 --- a/app/models/star.py +++ /dev/null @@ -1,17 +0,0 @@ -from app import db - -class Star(db.Model): - id = db.Column(db.Integer, primary_key=True, autoincrement=True) - name = db.Column(db.String, nullable=False) - - def to_dict(self): - return { - "id": self.id, - "name": self.name - } - - @classmethod - def from_dict(cls, data_dict): - return cls( - name = data_dict["name"] - ) \ No newline at end of file diff --git a/app/star_routes.py b/app/star_routes.py deleted file mode 100644 index 31f0aaca7..000000000 --- a/app/star_routes.py +++ /dev/null @@ -1,4 +0,0 @@ -from flask import Blueprint, jsonify, abort, make_response, request -from app import db - -star_bp = Blueprint("stars", __name__, url_prefix="/stars") \ No newline at end of file