From 86950605619592c55357396dcf0e1ec67307f4af Mon Sep 17 00:00:00 2001 From: Sheung Wan Wong Date: Wed, 14 Dec 2022 11:57:47 -0700 Subject: [PATCH 01/53] wave_01 Planet Class created --- app/model/planet.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 app/model/planet.py diff --git a/app/model/planet.py b/app/model/planet.py new file mode 100644 index 000000000..e69de29bb From 5fa6a0f720a9a487edbbb0cfd70463645df4d8b8 Mon Sep 17 00:00:00 2001 From: Sheung Wan Wong Date: Wed, 14 Dec 2022 13:02:37 -0700 Subject: [PATCH 02/53] wave_01 completed --- app/__init__.py | 2 ++ app/model/planet.py | 11 +++++++++++ app/routes.py | 18 +++++++++++++++++- 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..6596942bd 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -3,5 +3,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/model/planet.py b/app/model/planet.py index e69de29bb..aea188f33 100644 --- a/app/model/planet.py +++ b/app/model/planet.py @@ -0,0 +1,11 @@ +class Planet: + def __init__(self, id, name, description, mass): + self.id = id + self.name = name + self.description = description + self.mass = mass + +planets = [Planet(1, "Neptune", "thick, windy", 1.024e26 ), + Planet(2, "Mars", "dusty, cold desert",6.39e23), + Planet(3, "Earth", "rocky, terrestrial, full of life",5.972e24) + ] \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..9d12d9e54 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,18 @@ -from flask import Blueprint +from flask import Blueprint, jsonify +from .model.planet import planets + +planets_bp = Blueprint("planets", __name__, url_prefix = "/planets") + +@planets_bp.route("",methods= ["GET"]) +def display_planets(): + response_planets = [] + for planet in planets: + response_planets.append({ + "id": planet.id, + "name": planet.name, + "description": planet.description, + "mass": planet.mass + }) + + return jsonify(response_planets) \ No newline at end of file From 3fb0a615c4fc448a422987eb932b848cba5f6fc4 Mon Sep 17 00:00:00 2001 From: larissa Date: Thu, 15 Dec 2022 10:47:20 -0800 Subject: [PATCH 03/53] Added single planet endpoint and handled invalid planet id type and nonexistent planet id --- app/routes.py | 35 +++++++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/app/routes.py b/app/routes.py index 9d12d9e54..63b705bc6 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 from .model.planet import planets @@ -15,4 +15,35 @@ def display_planets(): "mass": planet.mass }) - return jsonify(response_planets) \ No newline at end of file + return jsonify(response_planets) + +# ~~~~~~ Handle planet id errors ~~~~~ +def validate_id(planet_id): + """ + - check for valid id type and if exists + - return planet object if valid planet id + """ + try: + planet_id_int = int(planet_id) + except: + # handling invalid planet id type + abort(make_response({"message": f"{planet_id} is an invalid planet id"}, 400)) + + # collect the planet data if valid id type + for planet in planets: + if planet.id == planet_id_int: + return planet + # handle nonexistant planet id + abort(make_response({"message": f"{planet_id} not found"}, 404)) + + +# ~~~~~~ Single planet endpoint ~~~~~~ +@planets_bp.route("/",methods= ["GET"]) +def display_planet(planet_id): + valid_planet = validate_id(planet_id) + return { + "id": valid_planet.id, + "name": valid_planet.name, + "description": valid_planet.description, + "mass": valid_planet.mass, + } From 978e24707e362b8b31a95e3189ce5d2a5a9f382e Mon Sep 17 00:00:00 2001 From: "echo '# Set PATH, MANPATH, etc., for Homebrew.' /Users/daliaali/.zprofile" Date: Tue, 20 Dec 2022 19:31:04 -0800 Subject: [PATCH 04/53] connected the app to a db. created GET /planets, GET /planets/ and POST /planets routes. refactored the planet_id validation function. --- app/__init__.py | 13 +++ app/model/planet.py | 11 --- app/models/__init__.py | 0 app/models/planet.py | 20 ++++ app/routes.py | 77 ++++++++++----- migrations/README | 1 + migrations/alembic.ini | 45 +++++++++ migrations/env.py | 96 +++++++++++++++++++ migrations/script.py.mako | 24 +++++ .../versions/f86f3dc07f4c_add_planet_model.py | 34 +++++++ 10 files changed, 285 insertions(+), 36 deletions(-) delete mode 100644 app/model/planet.py 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/f86f3dc07f4c_add_planet_model.py diff --git a/app/__init__.py b/app/__init__.py index 6596942bd..e2d158696 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,8 +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' + + from app.models.planet import Planet + + db.init_app(app) + migrate.init_app(app, db) + from .routes import planets_bp app.register_blueprint(planets_bp) diff --git a/app/model/planet.py b/app/model/planet.py deleted file mode 100644 index aea188f33..000000000 --- a/app/model/planet.py +++ /dev/null @@ -1,11 +0,0 @@ -class Planet: - def __init__(self, id, name, description, mass): - self.id = id - self.name = name - self.description = description - self.mass = mass - -planets = [Planet(1, "Neptune", "thick, windy", 1.024e26 ), - Planet(2, "Mars", "dusty, cold desert",6.39e23), - Planet(3, "Earth", "rocky, terrestrial, full of life",5.972e24) - ] \ No newline at end of file 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..1ef792171 --- /dev/null +++ b/app/models/planet.py @@ -0,0 +1,20 @@ +# class Planet: +# def __init__(self, id, name, description, mass): +# self.id = id +# self.name = name +# self.description = description +# self.mass = mass + +# planets = [Planet(1, "Neptune", "thick, windy", 1.024e26 ), +# Planet(2, "Mars", "dusty, cold desert",6.39e23), +# Planet(3, "Earth", "rocky, terrestrial, full of life",5.972e24) +# ] + +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) + mass = db.Column(db.String) + \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 63b705bc6..c4e9bbc80 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,22 +1,10 @@ -from flask import Blueprint, jsonify, abort, make_response -from .model.planet import planets +from app import db +from flask import Blueprint, jsonify, abort, make_response, request +from .models.planet import Planet planets_bp = Blueprint("planets", __name__, url_prefix = "/planets") -@planets_bp.route("",methods= ["GET"]) -def display_planets(): - response_planets = [] - for planet in planets: - response_planets.append({ - "id": planet.id, - "name": planet.name, - "description": planet.description, - "mass": planet.mass - }) - - return jsonify(response_planets) - # ~~~~~~ Handle planet id errors ~~~~~ def validate_id(planet_id): """ @@ -29,21 +17,60 @@ def validate_id(planet_id): # handling invalid planet id type abort(make_response({"message": f"{planet_id} is an invalid planet id"}, 400)) - # collect the planet data if valid id type - for planet in planets: - if planet.id == planet_id_int: - return planet + # return planet data if id in db + planet = Planet.query.get(planet_id) + # handle nonexistant planet id - abort(make_response({"message": f"{planet_id} not found"}, 404)) + if not planet: + abort(make_response({"message": f"{planet_id} not found"}, 404)) + + return planet + + + +@planets_bp.route("",methods= ["GET"]) +def display_all_planets(): + response_planets = [] + planets = Planet.query.all() + for planet in planets: + response_planets.append({ + "id": planet.id, + "name": planet.name, + "description": planet.description, + "mass": planet.mass + }) + + return jsonify(response_planets) # ~~~~~~ Single planet endpoint ~~~~~~ -@planets_bp.route("/",methods= ["GET"]) +@planets_bp.route("/",methods=["GET"]) def display_planet(planet_id): valid_planet = validate_id(planet_id) return { - "id": valid_planet.id, - "name": valid_planet.name, - "description": valid_planet.description, - "mass": valid_planet.mass, + "id": valid_planet.id, + "name": valid_planet.name, + "description": valid_planet.description, + "mass": valid_planet.mass, } + + +@planets_bp.route("", methods=["POST"]) +def create_planet(): + request_body = request.get_json() + + if "name" not in request_body or "description" not in request_body \ + or "mass" not in request_body: + abort(make_response({"message" : \ + "Failed to create a planet because the name and/or description \ + and/or mass are missing"}, 400)) + + new_planet = Planet( + name=request_body["name"], + description=request_body["description"], + mass=request_body["mass"]) + + db.session.add(new_planet) + db.session.commit() + + return make_response({"message":"planet has been created successfully"}, 200) \ 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"} diff --git a/migrations/versions/f86f3dc07f4c_add_planet_model.py b/migrations/versions/f86f3dc07f4c_add_planet_model.py new file mode 100644 index 000000000..13d735b23 --- /dev/null +++ b/migrations/versions/f86f3dc07f4c_add_planet_model.py @@ -0,0 +1,34 @@ +"""add Planet model + +Revision ID: f86f3dc07f4c +Revises: +Create Date: 2022-12-20 11:18:49.218372 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'f86f3dc07f4c' +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('mass', 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 578b1822a59e71911c848347942dc1378be3c868 Mon Sep 17 00:00:00 2001 From: larissa Date: Wed, 21 Dec 2022 11:09:41 -0800 Subject: [PATCH 05/53] Added update_planet functionality for /planets/ endpoint --- app/routes.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index c4e9bbc80..b7f1173df 100644 --- a/app/routes.py +++ b/app/routes.py @@ -6,6 +6,7 @@ planets_bp = Blueprint("planets", __name__, url_prefix = "/planets") # ~~~~~~ Handle planet id errors ~~~~~ +# FUTURE IDEAS: Create separate helper function module or add as class method def validate_id(planet_id): """ - check for valid id type and if exists @@ -73,4 +74,17 @@ def create_planet(): db.session.add(new_planet) db.session.commit() - return make_response({"message":"planet has been created successfully"}, 200) \ No newline at end of file + return make_response({"message":"planet has been created successfully"}, 201) + +@planets_bp.route("/", methods=["PUT"]) +def update_planet(planet_id): + request_body = request.get_json() + planet = validate_id(planet_id) + planet.name = request_body["name"] if "name" in request_body else planet.name + planet.description = request_body["description"] if "description" in request_body else planet.description + planet.mass = request_body["mass"] if "mass" in request_body else planet.mass + db.session.commit() + return make_response( + {"message": f"planet #{planet_id} Updated Successfully"}, 200 + ) + From 33981b512941860cc6ba3167a59d2bd31d354722 Mon Sep 17 00:00:00 2001 From: larissa Date: Wed, 21 Dec 2022 11:43:23 -0800 Subject: [PATCH 06/53] Added delete_planet functionality for /planets/ endpoint --- app/routes.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/app/routes.py b/app/routes.py index b7f1173df..6b749b4bf 100644 --- a/app/routes.py +++ b/app/routes.py @@ -88,3 +88,11 @@ def update_planet(planet_id): {"message": f"planet #{planet_id} Updated Successfully"}, 200 ) +@planets_bp.route("/", methods=["DELETE"]) +def delete_planet(planet_id): + planet = validate_id(planet_id) + db.session.delete(planet) + db.session.commit() + return make_response( + {"message": f"planet #{planet_id} has been deleted successfully"}, 200 + ) From bfd24a2e47295421f1c0e42ec280114a0d1cb2e8 Mon Sep 17 00:00:00 2001 From: larissa Date: Wed, 21 Dec 2022 12:02:54 -0800 Subject: [PATCH 07/53] Refactored parts of update_planet() commented, issue with getting it to commit update to db --- app/routes.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/app/routes.py b/app/routes.py index 6b749b4bf..8c4b2c4d2 100644 --- a/app/routes.py +++ b/app/routes.py @@ -80,6 +80,9 @@ def create_planet(): def update_planet(planet_id): request_body = request.get_json() planet = validate_id(planet_id) + # ~~~ REFACTOR ISSUE ~~~ This line runs but a problem with updating the db + # for attr in request_body: + # planet.attr = request_body[attr] planet.name = request_body["name"] if "name" in request_body else planet.name planet.description = request_body["description"] if "description" in request_body else planet.description planet.mass = request_body["mass"] if "mass" in request_body else planet.mass From 80f74a3017ce001db47a43dbfc1fa5ebc5cf7df4 Mon Sep 17 00:00:00 2001 From: larissa Date: Wed, 21 Dec 2022 14:52:27 -0800 Subject: [PATCH 08/53] Updated model - plural table name and float dtype for mass attribute --- app/models/planet.py | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index 1ef792171..7cfccb58b 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -1,10 +1,3 @@ -# class Planet: -# def __init__(self, id, name, description, mass): -# self.id = id -# self.name = name -# self.description = description -# self.mass = mass - # planets = [Planet(1, "Neptune", "thick, windy", 1.024e26 ), # Planet(2, "Mars", "dusty, cold desert",6.39e23), # Planet(3, "Earth", "rocky, terrestrial, full of life",5.972e24) @@ -16,5 +9,5 @@ class Planet(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String) description = db.Column(db.String) - mass = db.Column(db.String) - \ No newline at end of file + mass = db.Column(db.Float) + __tablename__ = "planets" From 74f7424a6ea9a4d8a33211454be8c244535b7780 Mon Sep 17 00:00:00 2001 From: larissa Date: Wed, 21 Dec 2022 14:53:01 -0800 Subject: [PATCH 09/53] New migration for model updated with plural table name and float dtype for mass --- ...hanged_mass_to_string_datatype_to_float.py | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 migrations/versions/7fa857cd0ba2_changed_mass_to_string_datatype_to_float.py diff --git a/migrations/versions/7fa857cd0ba2_changed_mass_to_string_datatype_to_float.py b/migrations/versions/7fa857cd0ba2_changed_mass_to_string_datatype_to_float.py new file mode 100644 index 000000000..b3e1bb15b --- /dev/null +++ b/migrations/versions/7fa857cd0ba2_changed_mass_to_string_datatype_to_float.py @@ -0,0 +1,42 @@ +"""changed mass to string datatype to Float + +Revision ID: 7fa857cd0ba2 +Revises: f86f3dc07f4c +Create Date: 2022-12-21 14:37:43.515533 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '7fa857cd0ba2' +down_revision = 'f86f3dc07f4c' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('planets', + 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('mass', sa.Float(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.drop_table('planet') + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('planet', + sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), + sa.Column('name', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('description', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('mass', sa.INTEGER(), autoincrement=False, nullable=True), + sa.PrimaryKeyConstraint('id', name='planet_pkey') + ) + op.drop_table('planets') + # ### end Alembic commands ### From b91ca43c2e93203a2ac47371077dcee6d3a8c737 Mon Sep 17 00:00:00 2001 From: "echo '# Set PATH, MANPATH, etc., for Homebrew.' /Users/daliaali/.zprofile" Date: Wed, 21 Dec 2022 17:46:47 -0800 Subject: [PATCH 10/53] changed migrate instance to allow detecting changes in data types. created a migration file for changing the mass datatype to string --- app/__init__.py | 4 +-- app/models/planet.py | 17 +++++----- app/routes.py | 6 ++-- .../68e11332dba2_changed_mass_datatype.py | 34 +++++++++++++++++++ 4 files changed, 47 insertions(+), 14 deletions(-) create mode 100644 migrations/versions/68e11332dba2_changed_mass_datatype.py diff --git a/app/__init__.py b/app/__init__.py index e2d158696..e0dbc77fb 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -3,7 +3,7 @@ from flask_migrate import Migrate db = SQLAlchemy() -migrate = Migrate() +migrate = Migrate(compare_type=True) def create_app(test_config=None): app = Flask(__name__) @@ -12,7 +12,7 @@ def create_app(test_config=None): app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system' from app.models.planet import Planet - + db.init_app(app) migrate.init_app(app, db) diff --git a/app/models/planet.py b/app/models/planet.py index 1ef792171..ea0c3733e 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -1,3 +1,11 @@ +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) + mass = db.Column(db.String) + # class Planet: # def __init__(self, id, name, description, mass): # self.id = id @@ -9,12 +17,3 @@ # Planet(2, "Mars", "dusty, cold desert",6.39e23), # Planet(3, "Earth", "rocky, terrestrial, full of life",5.972e24) # ] - -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) - mass = db.Column(db.String) - \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 8c4b2c4d2..d9d6aee9d 100644 --- a/app/routes.py +++ b/app/routes.py @@ -61,10 +61,10 @@ def create_planet(): request_body = request.get_json() if "name" not in request_body or "description" not in request_body \ - or "mass" not in request_body: + or "mass" not in request_body: abort(make_response({"message" : \ - "Failed to create a planet because the name and/or description \ - and/or mass are missing"}, 400)) + "Failed to create a planet because the name and/or description \ + and/or mass are missing"}, 400)) new_planet = Planet( name=request_body["name"], diff --git a/migrations/versions/68e11332dba2_changed_mass_datatype.py b/migrations/versions/68e11332dba2_changed_mass_datatype.py new file mode 100644 index 000000000..25d38db9c --- /dev/null +++ b/migrations/versions/68e11332dba2_changed_mass_datatype.py @@ -0,0 +1,34 @@ +"""changed mass datatype + +Revision ID: 68e11332dba2 +Revises: f86f3dc07f4c +Create Date: 2022-12-21 17:22:10.875924 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '68e11332dba2' +down_revision = 'f86f3dc07f4c' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.alter_column('planet', 'mass', + existing_type=sa.INTEGER(), + type_=sa.String(), + existing_nullable=True) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.alter_column('planet', 'mass', + existing_type=sa.String(), + type_=sa.INTEGER(), + existing_nullable=True) + # ### end Alembic commands ### From e5b67aea47e2ef3ec5771b8700dd9d2b2265674b Mon Sep 17 00:00:00 2001 From: "echo '# Set PATH, MANPATH, etc., for Homebrew.' /Users/daliaali/.zprofile" Date: Wed, 21 Dec 2022 19:01:23 -0800 Subject: [PATCH 11/53] changed tale name to planets. all columns are not allowed to be null. mass data type is float. --- app/models/planet.py | 7 ++-- ...c_add_planet_model.py => 040c4f56aefe_.py} | 18 ++++---- .../68e11332dba2_changed_mass_datatype.py | 34 --------------- ...hanged_mass_to_string_datatype_to_float.py | 42 ------------------- 4 files changed, 13 insertions(+), 88 deletions(-) rename migrations/versions/{f86f3dc07f4c_add_planet_model.py => 040c4f56aefe_.py} (60%) delete mode 100644 migrations/versions/68e11332dba2_changed_mass_datatype.py delete mode 100644 migrations/versions/7fa857cd0ba2_changed_mass_to_string_datatype_to_float.py diff --git a/app/models/planet.py b/app/models/planet.py index 206ab85b4..180170130 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -1,10 +1,11 @@ from app import db class Planet(db.Model): + __tablename__ = 'planets' id = db.Column(db.Integer, primary_key=True, autoincrement=True) - name = db.Column(db.String) - description = db.Column(db.String) - mass = db.Column(db.String) + name = db.Column(db.String, nullable=False) + description = db.Column(db.String, nullable=False) + mass = db.Column(db.Float, nullable=False) # planets = [Planet(1, "Neptune", "thick, windy", 1.024e26 ), # Planet(2, "Mars", "dusty, cold desert",6.39e23), diff --git a/migrations/versions/f86f3dc07f4c_add_planet_model.py b/migrations/versions/040c4f56aefe_.py similarity index 60% rename from migrations/versions/f86f3dc07f4c_add_planet_model.py rename to migrations/versions/040c4f56aefe_.py index 13d735b23..048f67d14 100644 --- a/migrations/versions/f86f3dc07f4c_add_planet_model.py +++ b/migrations/versions/040c4f56aefe_.py @@ -1,8 +1,8 @@ -"""add Planet model +"""empty message -Revision ID: f86f3dc07f4c +Revision ID: 040c4f56aefe Revises: -Create Date: 2022-12-20 11:18:49.218372 +Create Date: 2022-12-21 18:58:13.305413 """ from alembic import op @@ -10,7 +10,7 @@ # revision identifiers, used by Alembic. -revision = 'f86f3dc07f4c' +revision = '040c4f56aefe' down_revision = None branch_labels = None depends_on = None @@ -18,11 +18,11 @@ def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('planet', + op.create_table('planets', 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('mass', sa.Integer(), nullable=True), + sa.Column('name', sa.String(), nullable=False), + sa.Column('description', sa.String(), nullable=False), + sa.Column('mass', sa.Float(), nullable=False), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### @@ -30,5 +30,5 @@ def upgrade(): def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_table('planet') + op.drop_table('planets') # ### end Alembic commands ### diff --git a/migrations/versions/68e11332dba2_changed_mass_datatype.py b/migrations/versions/68e11332dba2_changed_mass_datatype.py deleted file mode 100644 index 25d38db9c..000000000 --- a/migrations/versions/68e11332dba2_changed_mass_datatype.py +++ /dev/null @@ -1,34 +0,0 @@ -"""changed mass datatype - -Revision ID: 68e11332dba2 -Revises: f86f3dc07f4c -Create Date: 2022-12-21 17:22:10.875924 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = '68e11332dba2' -down_revision = 'f86f3dc07f4c' -branch_labels = None -depends_on = None - - -def upgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.alter_column('planet', 'mass', - existing_type=sa.INTEGER(), - type_=sa.String(), - existing_nullable=True) - # ### end Alembic commands ### - - -def downgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.alter_column('planet', 'mass', - existing_type=sa.String(), - type_=sa.INTEGER(), - existing_nullable=True) - # ### end Alembic commands ### diff --git a/migrations/versions/7fa857cd0ba2_changed_mass_to_string_datatype_to_float.py b/migrations/versions/7fa857cd0ba2_changed_mass_to_string_datatype_to_float.py deleted file mode 100644 index b3e1bb15b..000000000 --- a/migrations/versions/7fa857cd0ba2_changed_mass_to_string_datatype_to_float.py +++ /dev/null @@ -1,42 +0,0 @@ -"""changed mass to string datatype to Float - -Revision ID: 7fa857cd0ba2 -Revises: f86f3dc07f4c -Create Date: 2022-12-21 14:37:43.515533 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = '7fa857cd0ba2' -down_revision = 'f86f3dc07f4c' -branch_labels = None -depends_on = None - - -def upgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.create_table('planets', - 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('mass', sa.Float(), nullable=True), - sa.PrimaryKeyConstraint('id') - ) - op.drop_table('planet') - # ### end Alembic commands ### - - -def downgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.create_table('planet', - sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), - sa.Column('name', sa.VARCHAR(), autoincrement=False, nullable=True), - sa.Column('description', sa.VARCHAR(), autoincrement=False, nullable=True), - sa.Column('mass', sa.INTEGER(), autoincrement=False, nullable=True), - sa.PrimaryKeyConstraint('id', name='planet_pkey') - ) - op.drop_table('planets') - # ### end Alembic commands ### From 3cb1e0670689c1e885c5f0564f5eb8009b3ea9cd Mon Sep 17 00:00:00 2001 From: larissa Date: Thu, 22 Dec 2022 11:01:47 -0800 Subject: [PATCH 12/53] Updated display_all_planets to include query param for planet name --- app/routes.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/app/routes.py b/app/routes.py index d9d6aee9d..8ae75643c 100644 --- a/app/routes.py +++ b/app/routes.py @@ -28,11 +28,14 @@ def validate_id(planet_id): return planet - @planets_bp.route("",methods= ["GET"]) def display_all_planets(): + planet_name_query = request.args.get("name") + if planet_name_query: + planets = Planet.query.filter_by(name=planet_name_query) + else: + planets = Planet.query.all() response_planets = [] - planets = Planet.query.all() for planet in planets: response_planets.append({ "id": planet.id, @@ -80,9 +83,6 @@ def create_planet(): def update_planet(planet_id): request_body = request.get_json() planet = validate_id(planet_id) - # ~~~ REFACTOR ISSUE ~~~ This line runs but a problem with updating the db - # for attr in request_body: - # planet.attr = request_body[attr] planet.name = request_body["name"] if "name" in request_body else planet.name planet.description = request_body["description"] if "description" in request_body else planet.description planet.mass = request_body["mass"] if "mass" in request_body else planet.mass @@ -91,6 +91,7 @@ def update_planet(planet_id): {"message": f"planet #{planet_id} Updated Successfully"}, 200 ) + @planets_bp.route("/", methods=["DELETE"]) def delete_planet(planet_id): planet = validate_id(planet_id) From ad4545482c73830ea747f0bfd640381448376265 Mon Sep 17 00:00:00 2001 From: larissa Date: Thu, 22 Dec 2022 16:20:34 -0800 Subject: [PATCH 13/53] Refactored query params in display_all_planets and added a helper function to separate param kwargs for SQLAlchemy query function --- app/routes.py | 62 ++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 51 insertions(+), 11 deletions(-) diff --git a/app/routes.py b/app/routes.py index 8ae75643c..f0fc78c65 100644 --- a/app/routes.py +++ b/app/routes.py @@ -5,36 +5,76 @@ planets_bp = Blueprint("planets", __name__, url_prefix = "/planets") -# ~~~~~~ Handle planet id errors ~~~~~ -# FUTURE IDEAS: Create separate helper function module or add as class method + +# ~~~~~~ Helper functions ~~~~~ +# TO DO: Create separate helper function module or add as class method # def validate_id(planet_id): """ - - check for valid id type and if exists - - return planet object if valid planet id + Checks if planet id is valid and returns error messages for invalid inputs + :params: + - planet_id (int) + :returns: + - planet (object) if valid planet id valid """ try: planet_id_int = int(planet_id) except: # handling invalid planet id type abort(make_response({"message": f"{planet_id} is an invalid planet id"}, 400)) - + # return planet data if id in db planet = Planet.query.get(planet_id) # handle nonexistant planet id if not planet: abort(make_response({"message": f"{planet_id} not found"}, 404)) - return planet +def process_args(queries): + """ + Separate kwargs from HTTP request into separate dicts based on SQLAlchemy query method + :params: + - queries (dict) + :returns: + - attrs (dict): planet class attributes kwargs for filter_by + ** name, description, mass + - orderby (dict): method kwargs for order_by + ** sort_mass, sort_name + - sels (dict): selected number of results for limit + """ + # turn line 45 into a Planet class method + planet_attrs = [attr for attr in dir(Planet) if not attr.startswith('__')] + order_methods = ["sort"] + attrs = {} + orderby = {} + sels = {} + for kwarg in queries: + if kwarg in planet_attrs: + attrs[kwarg] = queries[kwarg] + elif kwarg in order_methods: + orderby[kwarg] = queries[kwarg] + elif kwarg == "limit": + sels[kwarg] = queries[kwarg] + else: + abort(make_response( + {"message" : f"{kwarg} is an invalid query"}, 400 + )) + return attrs, orderby, sels + @planets_bp.route("",methods= ["GET"]) def display_all_planets(): - planet_name_query = request.args.get("name") - if planet_name_query: - planets = Planet.query.filter_by(name=planet_name_query) - else: - planets = Planet.query.all() + planet_query = Planet.query + attrs, orderby, sels = process_args(request.args.to_dict()) + if attrs: + planet_query = planet_query.filter_by(**attrs) + # TO DO: works but only sorts by name currently ascending - need to add modularity + if orderby: + planet_query = planet_query.order_by(Planet.name.asc()) + if sels: + planet_query = planet_query.limit(**sels) + planets = planet_query.all() + # fill response response_planets = [] for planet in planets: response_planets.append({ From 847b34c4825e117b56cba68f6c8aa21eebe6f958 Mon Sep 17 00:00:00 2001 From: larissa Date: Thu, 22 Dec 2022 16:26:13 -0800 Subject: [PATCH 14/53] Switched function name from process_args() to process_kwargs since more accurate --- app/routes.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/routes.py b/app/routes.py index f0fc78c65..6374e5971 100644 --- a/app/routes.py +++ b/app/routes.py @@ -30,7 +30,7 @@ def validate_id(planet_id): abort(make_response({"message": f"{planet_id} not found"}, 404)) return planet -def process_args(queries): +def process_kwargs(queries): """ Separate kwargs from HTTP request into separate dicts based on SQLAlchemy query method :params: @@ -65,7 +65,7 @@ def process_args(queries): @planets_bp.route("",methods= ["GET"]) def display_all_planets(): planet_query = Planet.query - attrs, orderby, sels = process_args(request.args.to_dict()) + attrs, orderby, sels = process_kwargs(request.args.to_dict()) if attrs: planet_query = planet_query.filter_by(**attrs) # TO DO: works but only sorts by name currently ascending - need to add modularity From 268d98136d3ae6941e3a7e5f22e3b652a6620c01 Mon Sep 17 00:00:00 2001 From: Sheung Wan Wong Date: Tue, 3 Jan 2023 13:00:05 -0700 Subject: [PATCH 15/53] Create .env file, and tests folder with files --- tests/__init__.py | 0 tests/conftest.py | 0 tests/test_routes.py | 0 3 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 tests/__init__.py create mode 100644 tests/conftest.py create mode 100644 tests/test_routes.py diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/test_routes.py b/tests/test_routes.py new file mode 100644 index 000000000..e69de29bb From 3177d396816d8d6b7feecbde9de6f91b22ad292b Mon Sep 17 00:00:00 2001 From: "echo '# Set PATH, MANPATH, etc., for Homebrew.' /Users/daliaali/.zprofile" Date: Tue, 3 Jan 2023 14:40:00 -0800 Subject: [PATCH 16/53] created 3 fixtures:app, client, two_saved_planets.updated app/__init__.py to accept dev and test db. added test_get_all_planets_with_empty_db_returns_empty_list --- app/__init__.py | 10 +++++++++- tests/conftest.py | 33 +++++++++++++++++++++++++++++++++ tests/test_routes.py | 5 +++++ 3 files changed, 47 insertions(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index e0dbc77fb..1350259a3 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,15 +1,23 @@ 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(compare_type=True) +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' + + if test_config: + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("SQLALCHEMY_TEST_DATABASE_URI") + app.config['TESTING'] = True + else: + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("SQLALCHEMY_DATABASE_URI") from app.models.planet import Planet diff --git a/tests/conftest.py b/tests/conftest.py index e69de29bb..81c694a92 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -0,0 +1,33 @@ +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(test_config=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() + +@pytest.fixture +def two_saved_planets(app): + earth = Planet(name="Earth", \ + description="rocky, terrestrial, full of life", mass=5.972e24) + mars = Planet(name="Mars", description="dusty, cold desert", \ + mass=6.39e23) + db.session.add_all([earth, mars]) + db.session.commit() \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py index e69de29bb..b08a9e903 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -0,0 +1,5 @@ +def test_get_all_planets_with_empty_db_returns_empty_list(client): + response = client.get("/planets") + + assert response.status_code == 200 + assert response.get_json() == [] \ No newline at end of file From 732b3c095356245458f9dfd7e13fe0dd4be46c61 Mon Sep 17 00:00:00 2001 From: "echo '# Set PATH, MANPATH, etc., for Homebrew.' /Users/daliaali/.zprofile" Date: Tue, 3 Jan 2023 14:54:35 -0800 Subject: [PATCH 17/53] added db.session.refresh in conftest.py --- tests/conftest.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/conftest.py b/tests/conftest.py index 81c694a92..e5c1f1bd2 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -30,4 +30,6 @@ def two_saved_planets(app): mars = Planet(name="Mars", description="dusty, cold desert", \ mass=6.39e23) db.session.add_all([earth, mars]) - db.session.commit() \ No newline at end of file + db.session.commit() + for planet in [earth, mars]: + db.session.refresh(planet, ["id"]) \ No newline at end of file From 39e731f636699d77e2ba38bb58dda3732c303cd2 Mon Sep 17 00:00:00 2001 From: larissa Date: Tue, 3 Jan 2023 16:46:19 -0800 Subject: [PATCH 18/53] Planets for database --- planets.csv | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 planets.csv diff --git a/planets.csv b/planets.csv new file mode 100644 index 000000000..ad6c2ef2c --- /dev/null +++ b/planets.csv @@ -0,0 +1,8 @@ +1 Neptune thick, windy 1.0239999999999999e+26 +2 Earth rocky, terrestrial, full of life 5.972e+24 +3 Mars dusty, cold desert 6.39e+23 +6 Mercury small, solid & covered with craters 3.285e+23 +7 Venus Bright and solid surface with dome-like volcanoes, rifts, and mountains 4.867e+24 +8 Jupiter Cold, windy clouds of ammonia and water 1.89813e+27 +9 Saturn Massive ball made mostly of hydrogen and helium 5.683e+26 +10 Uranus Hot dense fluid of 'icy' materials - water, methane, and ammonia 8.681e+25 From a8ee6e487e2608c3ad5d6302c58d72bcf520965e Mon Sep 17 00:00:00 2001 From: larissa Date: Tue, 3 Jan 2023 16:47:27 -0800 Subject: [PATCH 19/53] Added get_all_attrs() method to Planet class --- app/models/planet.py | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index 180170130..26bc5261b 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -1,13 +1,25 @@ from app import db +# planets = [Planet(1, "Neptune", "thick, windy", 1.024e26 ), +# Planet(2, "Mars", "dusty, cold desert",6.39e23), +# Planet(3, "Earth", "rocky, terrestrial, full of life",5.972e24) +# ] + class Planet(db.Model): __tablename__ = 'planets' id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String, nullable=False) description = db.Column(db.String, nullable=False) mass = db.Column(db.Float, nullable=False) - -# planets = [Planet(1, "Neptune", "thick, windy", 1.024e26 ), -# Planet(2, "Mars", "dusty, cold desert",6.39e23), -# Planet(3, "Earth", "rocky, terrestrial, full of life",5.972e24) -# ] + # gravity = db.Column(db.Float, nullable=False) + # dist_sun = db.Column(db.Float, nullable=False) + # n_moons = db.Column(db.Integer, nullable=False) + # water + # temperature + # atmosphere + + def get_all_attrs(): + """ + Returns all existing attributes (list) in Planet class + """ + return [attr for attr in dir(Planet) if not attr.startswith('__')] \ No newline at end of file From b06da98c4e0d2ef692a7251fb0759af7f77c2d32 Mon Sep 17 00:00:00 2001 From: larissa Date: Tue, 3 Jan 2023 16:48:44 -0800 Subject: [PATCH 20/53] Updated sort by attribute feature in display_all_planets() and process_kwargs() --- app/routes.py | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/app/routes.py b/app/routes.py index 6374e5971..33838b3e0 100644 --- a/app/routes.py +++ b/app/routes.py @@ -42,9 +42,8 @@ def process_kwargs(queries): ** sort_mass, sort_name - sels (dict): selected number of results for limit """ - # turn line 45 into a Planet class method - planet_attrs = [attr for attr in dir(Planet) if not attr.startswith('__')] - order_methods = ["sort"] + planet_attrs = Planet.get_all_attrs() + order_methods = ["sort", "desc"] attrs = {} orderby = {} sels = {} @@ -64,17 +63,27 @@ def process_kwargs(queries): @planets_bp.route("",methods= ["GET"]) def display_all_planets(): + # collect query & parse kwargs planet_query = Planet.query attrs, orderby, sels = process_kwargs(request.args.to_dict()) if attrs: + # filter by attribute kwargs e.g name=Earth planet_query = planet_query.filter_by(**attrs) - # TO DO: works but only sorts by name currently ascending - need to add modularity - if orderby: - planet_query = planet_query.order_by(Planet.name.asc()) + if "sort" in orderby: + # sort by given attribute e.g.sort=mass + clause = getattr(Planet, orderby["sort"]) + if "desc" in orderby: + # sort in descending order e.g.desc=True + planet_query = planet_query.order_by(clause.desc()) + else: + # default is asc=True + planet_query = planet_query.order_by(clause.asc()) if sels: + # limit selection of planets to view planet_query = planet_query.limit(**sels) + # perform query planets = planet_query.all() - # fill response + # fill http response response_planets = [] for planet in planets: response_planets.append({ @@ -82,8 +91,7 @@ def display_all_planets(): "name": planet.name, "description": planet.description, "mass": planet.mass - }) - + }) return jsonify(response_planets) From 4226c76ac52fc4fa794556bcececa16771522f8a Mon Sep 17 00:00:00 2001 From: "echo '# Set PATH, MANPATH, etc., for Homebrew.' /Users/daliaali/.zprofile" Date: Tue, 3 Jan 2023 21:39:06 -0800 Subject: [PATCH 21/53] added tests for get /planet/ with an empty db, update planet successfully, get planet/ with an invalid id --- tests/conftest.py | 10 +++++++--- tests/test_routes.py | 26 +++++++++++++++++++++++++- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index e5c1f1bd2..01be5b83e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -29,7 +29,11 @@ def two_saved_planets(app): description="rocky, terrestrial, full of life", mass=5.972e24) mars = Planet(name="Mars", description="dusty, cold desert", \ mass=6.39e23) - db.session.add_all([earth, mars]) + planets = [earth, mars] + db.session.add_all(planets) db.session.commit() - for planet in [earth, mars]: - db.session.refresh(planet, ["id"]) \ No newline at end of file + + for planet in planets: + db.session.refresh(planet, ["id"]) + + return planets \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py index b08a9e903..60d66ba60 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -2,4 +2,28 @@ def test_get_all_planets_with_empty_db_returns_empty_list(client): response = client.get("/planets") assert response.status_code == 200 - assert response.get_json() == [] \ No newline at end of file + assert response.get_json() == [] + + +def test_get_planet_by_id_with_empty_db_returns_404(client): + response = client.get("/planets/1") + + assert response.status_code == 404 + assert response.get_json() == {"message" : "1 not found"} + + +def test_update_planet_successfully(client, two_saved_planets): + test_data = {"name" : "earth", + "description" : "terrestrial, full of life", + "mass" : 5.97e24} + response = client.put("planets/1", json=test_data) + + assert response.status_code == 200 + assert response.get_json() == {"message": "planet #1 Updated Successfully"} + + +def test_get_planet_by_invalid_id_returns_400(client, two_saved_planets): + response = client.get("/planets/earth") + + assert response.status_code == 400 + assert response.get_json() == {"message": "earth is an invalid planet id"} \ No newline at end of file From aa928ce4662218b6d7462c7b07af1ceedd3c3aad Mon Sep 17 00:00:00 2001 From: Sheung Wan Wong Date: Tue, 3 Jan 2023 23:47:14 -0700 Subject: [PATCH 22/53] test: Create test_get_one_planet, test_create_one_planet and test_create_one_planet --- tests/conftest.py | 8 +++++--- tests/test_routes.py | 42 +++++++++++++++++++++++++++++++++++++++++- 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index e5c1f1bd2..8d89fec3f 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -29,7 +29,9 @@ def two_saved_planets(app): description="rocky, terrestrial, full of life", mass=5.972e24) mars = Planet(name="Mars", description="dusty, cold desert", \ mass=6.39e23) - db.session.add_all([earth, mars]) + planets = [earth, mars] + db.session.add_all(planets) db.session.commit() - for planet in [earth, mars]: - db.session.refresh(planet, ["id"]) \ No newline at end of file + for planet in planets: + db.session.refresh(planet, ["id"]) + return planets \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py index b08a9e903..7f43aab6a 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -2,4 +2,44 @@ def test_get_all_planets_with_empty_db_returns_empty_list(client): response = client.get("/planets") assert response.status_code == 200 - assert response.get_json() == [] \ No newline at end of file + assert response.get_json() == [] + +def test_get_one_planet(client, two_saved_planets): + # Act + response = client.get("/planets/1") + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert response_body == { + "id" : 1, + "name": "Earth", + "description": "rocky, terrestrial, full of life", + "mass": 5.972e24 + } + +def test_create_one_planet(client): + #Act + response = client.post("/planets", json = { + "name": "Neptune", + "description": "thick, windy", + "mass":1.024e26 + }) + response_body = response.get_json() + + #Assert + assert response.status_code == 201 + assert response_body == {"message":"planet has been created successfully"} + +def test_create_one_planet_missing_mass_return_400(client): + #Act + response = client.post("/planets", json = { + "name": "Neptune", + "description": "thick, windy" + }) + response_body = response.get_json() + #Assert + assert response.status_code == 400 + assert response_body == {"message" : \ + "Failed to create a planet because the name and/or description \ + and/or mass are missing"} \ No newline at end of file From 6b26ea91a8c2ccdb3e1f81688b72f8706dee9a8b Mon Sep 17 00:00:00 2001 From: larissa Date: Wed, 4 Jan 2023 00:38:45 -0800 Subject: [PATCH 23/53] Added unit tests 3, 6, and 3 edge cases for get method with query kwargs in endpoint --- tests/test_routes.py | 61 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 60 insertions(+), 1 deletion(-) diff --git a/tests/test_routes.py b/tests/test_routes.py index 60d66ba60..14040d4db 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -26,4 +26,63 @@ def test_get_planet_by_invalid_id_returns_400(client, two_saved_planets): response = client.get("/planets/earth") assert response.status_code == 400 - assert response.get_json() == {"message": "earth is an invalid planet id"} \ No newline at end of file + assert response.get_json() == {"message": "earth is an invalid planet id"} + +def test_get_planet_by_valid_data_returns_data_and_200(client, two_saved_planets): + response = client.get("/planets") + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == [ + {"name": "Earth", + "description": "rocky, terrestrial, full of life", + "mass": 5.972e24, + "id": 1}, + {"name": "Mars", + "description": "dusty, cold desert", + "mass": 6.39e23, + "id": 2} + ] + +def test_delete_planet_1_with_json_request_body_returns_200(client, two_saved_planets): + response = client.delete("/planets/1", json={ + "name": "Earth", + "description": "rocky, terrestrial, full of life", + "mass": 5.972e24, + "id": 1 + }) + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == {"message": f"planet #1 has been deleted successfully"}, 200 + +def test_get_mass_desc_and_limit_1_returns_data_and_200(client, two_saved_planets): + response = client.get("/planets?sort=mass&desc=True&limit=1") + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == [{ + "name": "Earth", + "description": "rocky, terrestrial, full of life", + "mass": 5.972e24, + "id": 1 + }] + +def test_get_name_desc_and_limit_1_returns_data_and_200(client, two_saved_planets): + response = client.get("/planets?sort=name&desc=True&limit=1") + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == [{ + "name": "Mars", + "description": "dusty, cold desert", + "mass": 6.39e23, + "id": 2 + }] + +def test_get_by_invalid_query_returns_error_message_and_400(client, two_saved_planets): + response = client.get("/planets?hamster=True") + response_body = response.get_json() + + assert response.status_code == 400 + assert response_body == {"message": "hamster is an invalid query"} \ No newline at end of file From a2c0deed1c735890d9dc9282108a835c6e4d335d Mon Sep 17 00:00:00 2001 From: larissa Date: Wed, 4 Jan 2023 12:13:22 -0800 Subject: [PATCH 24/53] Added to_dict() method to Planet class --- app/models/planet.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index 26bc5261b..19cb6e79e 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -1,25 +1,25 @@ from app import db -# planets = [Planet(1, "Neptune", "thick, windy", 1.024e26 ), -# Planet(2, "Mars", "dusty, cold desert",6.39e23), -# Planet(3, "Earth", "rocky, terrestrial, full of life",5.972e24) -# ] - class Planet(db.Model): __tablename__ = 'planets' id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String, nullable=False) description = db.Column(db.String, nullable=False) mass = db.Column(db.Float, nullable=False) - # gravity = db.Column(db.Float, nullable=False) - # dist_sun = db.Column(db.Float, nullable=False) - # n_moons = db.Column(db.Integer, nullable=False) - # water - # temperature - # atmosphere def get_all_attrs(): """ Returns all existing attributes (list) in Planet class """ - return [attr for attr in dir(Planet) if not attr.startswith('__')] \ No newline at end of file + return [attr for attr in dir(Planet) if not attr.startswith('__')] + + def to_dict(self): + """ + Returns dictionary containing Planet instance data + """ + return { + "id": self.id, + "name": self.name, + "description": self.description, + "mass": self.mass + } \ No newline at end of file From 92230750d5abb0526af82767bd200bb7256d69e7 Mon Sep 17 00:00:00 2001 From: larissa Date: Wed, 4 Jan 2023 12:13:52 -0800 Subject: [PATCH 25/53] Refactored routes to make use of Planet.to_dict() method --- app/routes.py | 16 ++-------------- 1 file changed, 2 insertions(+), 14 deletions(-) diff --git a/app/routes.py b/app/routes.py index 33838b3e0..f4f484ce2 100644 --- a/app/routes.py +++ b/app/routes.py @@ -60,7 +60,6 @@ def process_kwargs(queries): )) return attrs, orderby, sels - @planets_bp.route("",methods= ["GET"]) def display_all_planets(): # collect query & parse kwargs @@ -86,12 +85,7 @@ def display_all_planets(): # fill http response response_planets = [] for planet in planets: - response_planets.append({ - "id": planet.id, - "name": planet.name, - "description": planet.description, - "mass": planet.mass - }) + response_planets.append(planet.to_dict()) return jsonify(response_planets) @@ -99,13 +93,7 @@ def display_all_planets(): @planets_bp.route("/",methods=["GET"]) def display_planet(planet_id): valid_planet = validate_id(planet_id) - return { - "id": valid_planet.id, - "name": valid_planet.name, - "description": valid_planet.description, - "mass": valid_planet.mass, - } - + return valid_planet.to_dict() @planets_bp.route("", methods=["POST"]) def create_planet(): From 3625bbfda845585fa02c61c3c96f9300f4162aef Mon Sep 17 00:00:00 2001 From: larissa Date: Wed, 4 Jan 2023 12:14:31 -0800 Subject: [PATCH 26/53] Added unit test to test if dict returned by Planet.to_dict() method in http response --- tests/test_routes.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/test_routes.py b/tests/test_routes.py index 359a02180..fce3988d4 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -127,3 +127,9 @@ def test_get_by_invalid_query_returns_error_message_and_400(client, two_saved_pl assert response.status_code == 400 assert response_body == {"message": "hamster is an invalid query"} + +def test_get_by_planet_id_with_to_dict_method_returns_dict(client, two_saved_planets): + response = client.get("planets/1") + response_body = response.get_json() + + assert type(response_body) == dict \ No newline at end of file From 1c455f296f74d74584e029a5eaff973511fcb638 Mon Sep 17 00:00:00 2001 From: "echo '# Set PATH, MANPATH, etc., for Homebrew.' /Users/daliaali/.zprofile" Date: Wed, 4 Jan 2023 14:17:03 -0800 Subject: [PATCH 27/53] added Planet classmethod from_dict and wrote tests for it in test_models.py --- app/models/planet.py | 8 ++++++- app/routes.py | 10 ++++---- tests/test_models.py | 56 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 69 insertions(+), 5 deletions(-) create mode 100644 tests/test_models.py diff --git a/app/models/planet.py b/app/models/planet.py index 26bc5261b..6381c9902 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -22,4 +22,10 @@ def get_all_attrs(): """ Returns all existing attributes (list) in Planet class """ - return [attr for attr in dir(Planet) if not attr.startswith('__')] \ No newline at end of file + return [attr for attr in dir(Planet) if not attr.startswith('__')] + + @classmethod + def from_dict(cls, dict): + return Planet(name=dict["name"], + description=dict["description"], + mass=dict["mass"]) \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 33838b3e0..33f11cddf 100644 --- a/app/routes.py +++ b/app/routes.py @@ -117,10 +117,12 @@ def create_planet(): "Failed to create a planet because the name and/or description \ and/or mass are missing"}, 400)) - new_planet = Planet( - name=request_body["name"], - description=request_body["description"], - mass=request_body["mass"]) + # new_planet = Planet( + # name=request_body["name"], + # description=request_body["description"], + # mass=request_body["mass"]) + + new_planet = Planet.from_dict(request_body) db.session.add(new_planet) db.session.commit() diff --git a/tests/test_models.py b/tests/test_models.py new file mode 100644 index 000000000..943c5bd83 --- /dev/null +++ b/tests/test_models.py @@ -0,0 +1,56 @@ +from app.models.planet import Planet +import pytest + + +def test_from_dict_with_valid_input(): + test_data = { + "name" : "Neptune", + "description" : "thick, windy", + "mass" : 1.024e26 + } + result = Planet.from_dict(test_data) + + assert result.name == "Neptune" + assert result.description == "thick, windy" + assert result.mass == 1.024e26 + + +def test_from_dict_without_given_name(): + test_data = {"description" : "thick, windy", + "mass" : 1.024e26} + + with pytest.raises(KeyError, match="name"): + Planet.from_dict(test_data) + + +def test_from_dict_without_given_mass(): + test_data = {"description" : "thick, windy", + "name":"Neptune"} + + with pytest.raises(KeyError, match="mass"): + Planet.from_dict(test_data) + +def test_from_dict_without_given_description(): + test_data = { + "name" : "Neptune", + "mass" : 1.024e26 + } + + with pytest.raises(KeyError, match="description"): + Planet.from_dict(test_data) + + +def test_from_dict_with_extra_input(): + test_data = { + "name" : "Neptune", + "description" : "thick, windy", + "mass" : 1.024e26, + "extra1" : "extra info", + "extra2" : "more extra info" + } + + result = Planet.from_dict(test_data) + + assert result.name == "Neptune" + assert result.description == "thick, windy" + assert result.mass == 1.024e26 \ No newline at end of file From dc67112960e0c76ed2fd8c46b6f1f42e694b0b17 Mon Sep 17 00:00:00 2001 From: larissa Date: Wed, 4 Jan 2023 14:25:41 -0800 Subject: [PATCH 28/53] Deleted Planet method to_dict unit test --- tests/test_routes.py | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/tests/test_routes.py b/tests/test_routes.py index fce3988d4..8d8fb0b33 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -22,9 +22,9 @@ def test_get_one_planet(client, two_saved_planets): def test_create_one_planet(client): #Act response = client.post("/planets", json = { - "name": "Neptune", - "description": "thick, windy", - "mass":1.024e26 + "name": "Neptune", + "description": "thick, windy", + "mass":1.024e26 }) response_body = response.get_json() @@ -35,8 +35,8 @@ def test_create_one_planet(client): def test_create_one_planet_missing_mass_return_400(client): #Act response = client.post("/planets", json = { - "name": "Neptune", - "description": "thick, windy" + "name": "Neptune", + "description": "thick, windy" }) response_body = response.get_json() #Assert @@ -127,9 +127,3 @@ def test_get_by_invalid_query_returns_error_message_and_400(client, two_saved_pl assert response.status_code == 400 assert response_body == {"message": "hamster is an invalid query"} - -def test_get_by_planet_id_with_to_dict_method_returns_dict(client, two_saved_planets): - response = client.get("planets/1") - response_body = response.get_json() - - assert type(response_body) == dict \ No newline at end of file From 3456111ed780590597de3ce2097b346f46924379 Mon Sep 17 00:00:00 2001 From: larissa Date: Wed, 4 Jan 2023 19:42:46 -0800 Subject: [PATCH 29/53] Added @classmethod decorator to get_all_attrs() - consistent and clear syntax --- app/models/planet.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/models/planet.py b/app/models/planet.py index cc9731747..67e31747c 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -7,7 +7,8 @@ class Planet(db.Model): description = db.Column(db.String, nullable=False) mass = db.Column(db.Float, nullable=False) - def get_all_attrs(): + @classmethod + def get_all_attrs(cls): """ Returns all existing attributes (list) in Planet class """ From ceb9869b29df23217e960aafdc7b411abdc78486 Mon Sep 17 00:00:00 2001 From: Sheung Wan Wong Date: Wed, 4 Jan 2023 22:59:23 -0700 Subject: [PATCH 30/53] rearrange the tests by Get Post Put Delete and validate_model() --- app/routes.py | 21 +++++---- tests/test_routes.py | 109 +++++++++++++++++++++---------------------- 2 files changed, 64 insertions(+), 66 deletions(-) diff --git a/app/routes.py b/app/routes.py index d5e64bc58..0afb78bb1 100644 --- a/app/routes.py +++ b/app/routes.py @@ -8,7 +8,7 @@ # ~~~~~~ Helper functions ~~~~~ # TO DO: Create separate helper function module or add as class method # -def validate_id(planet_id): +def validate_model(cls, model_id): """ Checks if planet id is valid and returns error messages for invalid inputs :params: @@ -17,18 +17,19 @@ def validate_id(planet_id): - planet (object) if valid planet id valid """ try: - planet_id_int = int(planet_id) + model_id = int(model_id) except: # handling invalid planet id type - abort(make_response({"message": f"{planet_id} is an invalid planet id"}, 400)) + abort(make_response({"message":f"{cls.__name__} {model_id} invalid"}, 400)) + # return planet data if id in db - planet = Planet.query.get(planet_id) + model = cls.query.get(model_id) # handle nonexistant planet id - if not planet: - abort(make_response({"message": f"{planet_id} not found"}, 404)) - return planet + if not model: + abort(make_response({"message":f"{cls.__name__} {model_id} not found"}, 404)) + return model def process_kwargs(queries): """ @@ -92,7 +93,7 @@ def display_all_planets(): # ~~~~~~ Single planet endpoint ~~~~~~ @planets_bp.route("/",methods=["GET"]) def display_planet(planet_id): - valid_planet = validate_id(planet_id) + valid_planet = validate_model(Planet, planet_id) return valid_planet.to_dict() @planets_bp.route("", methods=["POST"]) @@ -120,7 +121,7 @@ def create_planet(): @planets_bp.route("/", methods=["PUT"]) def update_planet(planet_id): request_body = request.get_json() - planet = validate_id(planet_id) + planet = validate_model(Planet, planet_id) planet.name = request_body["name"] if "name" in request_body else planet.name planet.description = request_body["description"] if "description" in request_body else planet.description planet.mass = request_body["mass"] if "mass" in request_body else planet.mass @@ -132,7 +133,7 @@ def update_planet(planet_id): @planets_bp.route("/", methods=["DELETE"]) def delete_planet(planet_id): - planet = validate_id(planet_id) + planet = validate_model(Planet, planet_id) db.session.delete(planet) db.session.commit() return make_response( diff --git a/tests/test_routes.py b/tests/test_routes.py index 8d8fb0b33..877831929 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -1,16 +1,14 @@ +#Tests on GET def test_get_all_planets_with_empty_db_returns_empty_list(client): response = client.get("/planets") assert response.status_code == 200 assert response.get_json() == [] - def test_get_one_planet(client, two_saved_planets): - # Act response = client.get("/planets/1") response_body = response.get_json() - # Assert assert response.status_code == 200 assert response_body == { "id" : 1, @@ -19,55 +17,17 @@ def test_get_one_planet(client, two_saved_planets): "mass": 5.972e24 } -def test_create_one_planet(client): - #Act - response = client.post("/planets", json = { - "name": "Neptune", - "description": "thick, windy", - "mass":1.024e26 - }) - response_body = response.get_json() - - #Assert - assert response.status_code == 201 - assert response_body == {"message":"planet has been created successfully"} - -def test_create_one_planet_missing_mass_return_400(client): - #Act - response = client.post("/planets", json = { - "name": "Neptune", - "description": "thick, windy" - }) - response_body = response.get_json() - #Assert - assert response.status_code == 400 - assert response_body == {"message" : \ - "Failed to create a planet because the name and/or description \ - and/or mass are missing"} - - def test_get_planet_by_id_with_empty_db_returns_404(client): response = client.get("/planets/1") assert response.status_code == 404 - assert response.get_json() == {"message" : "1 not found"} - - -def test_update_planet_successfully(client, two_saved_planets): - test_data = {"name" : "earth", - "description" : "terrestrial, full of life", - "mass" : 5.97e24} - response = client.put("planets/1", json=test_data) - - assert response.status_code == 200 - assert response.get_json() == {"message": "planet #1 Updated Successfully"} - + assert response.get_json() == {"message" : "Planet 1 not found"} def test_get_planet_by_invalid_id_returns_400(client, two_saved_planets): response = client.get("/planets/earth") assert response.status_code == 400 - assert response.get_json() == {"message": "earth is an invalid planet id"} + assert response.get_json() == {"message":"Planet earth invalid"} def test_get_planet_by_valid_data_returns_data_and_200(client, two_saved_planets): response = client.get("/planets") @@ -83,19 +43,7 @@ def test_get_planet_by_valid_data_returns_data_and_200(client, two_saved_planets "description": "dusty, cold desert", "mass": 6.39e23, "id": 2} - ] - -def test_delete_planet_1_with_json_request_body_returns_200(client, two_saved_planets): - response = client.delete("/planets/1", json={ - "name": "Earth", - "description": "rocky, terrestrial, full of life", - "mass": 5.972e24, - "id": 1 - }) - response_body = response.get_json() - - assert response.status_code == 200 - assert response_body == {"message": f"planet #1 has been deleted successfully"}, 200 + ] def test_get_mass_desc_and_limit_1_returns_data_and_200(client, two_saved_planets): response = client.get("/planets?sort=mass&desc=True&limit=1") @@ -127,3 +75,52 @@ def test_get_by_invalid_query_returns_error_message_and_400(client, two_saved_pl assert response.status_code == 400 assert response_body == {"message": "hamster is an invalid query"} + +#Tests on Post +def test_create_one_planet(client): + response = client.post("/planets", json = { + "name": "Neptune", + "description": "thick, windy", + "mass":1.024e26 + }) + response_body = response.get_json() + + assert response.status_code == 201 + assert response_body == {"message":"planet has been created successfully"} + +def test_create_one_planet_missing_mass_return_400(client): + response = client.post("/planets", json = { + "name": "Neptune", + "description": "thick, windy" + }) + response_body = response.get_json() + + assert response.status_code == 400 + assert response_body == {"message" : \ + "Failed to create a planet because the name and/or description \ + and/or mass are missing"} + +#Tests on Put +def test_update_planet_successfully(client, two_saved_planets): + test_data = {"name" : "earth", + "description" : "terrestrial, full of life", + "mass" : 5.97e24} + response = client.put("planets/1", json=test_data) + + assert response.status_code == 200 + assert response.get_json() == {"message": "planet #1 Updated Successfully"} + +#Tests on Delete +def test_delete_planet_1_with_json_request_body_returns_200(client, two_saved_planets): + response = client.delete("/planets/1", json={ + "name": "Earth", + "description": "rocky, terrestrial, full of life", + "mass": 5.972e24, + "id": 1 + }) + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == {"message": f"planet #1 has been deleted successfully"}, 200 + +#Tests on valid_model(cls, model_id) \ No newline at end of file From 0bbabab45b3911db23531c311ef63021d1b89a90 Mon Sep 17 00:00:00 2001 From: Sheung Wan Wong Date: Wed, 4 Jan 2023 23:17:06 -0700 Subject: [PATCH 31/53] refactor: Create 3 new tests on validate_model() --- tests/test_routes.py | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/tests/test_routes.py b/tests/test_routes.py index 877831929..ba04623a5 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -1,3 +1,8 @@ +from werkzeug.exceptions import HTTPException +from app.routes import validate_model +from app.models.planet import Planet +import pytest + #Tests on GET def test_get_all_planets_with_empty_db_returns_empty_list(client): response = client.get("/planets") @@ -123,4 +128,19 @@ def test_delete_planet_1_with_json_request_body_returns_200(client, two_saved_pl assert response.status_code == 200 assert response_body == {"message": f"planet #1 has been deleted successfully"}, 200 -#Tests on valid_model(cls, model_id) \ No newline at end of file +#Tests on valid_model(cls, model_id) +def test_validate_model(two_saved_planets): + result_planet = validate_model(Planet, 1) + + assert result_planet.id == 1 + assert result_planet.name == "Earth" + assert result_planet.description == "rocky, terrestrial, full of life" + assert result_planet.mass == 5.972e24 + +def test_validate_model_missing_record(two_saved_planets): + with pytest.raises(HTTPException): + result_planet = validate_model(Planet, 3) + +def test_validate_model_invalid_id(two_saved_planets): + with pytest.raises(HTTPException): + result_planet = validate_model(Planet, "cat") \ No newline at end of file From 94f050b0486d52167c7a266314f38f4288b4931c Mon Sep 17 00:00:00 2001 From: Sheung Wan Wong Date: Wed, 4 Jan 2023 23:49:15 -0700 Subject: [PATCH 32/53] refactor: Create 4 new tests for Put method --- app/routes.py | 2 +- tests/test_routes.py | 42 +++++++++++++++++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/app/routes.py b/app/routes.py index 0afb78bb1..0a939e871 100644 --- a/app/routes.py +++ b/app/routes.py @@ -127,7 +127,7 @@ def update_planet(planet_id): planet.mass = request_body["mass"] if "mass" in request_body else planet.mass db.session.commit() return make_response( - {"message": f"planet #{planet_id} Updated Successfully"}, 200 + {"message": f"Planet #{planet_id} successfully updated"}, 200 ) diff --git a/tests/test_routes.py b/tests/test_routes.py index ba04623a5..29035c5c1 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -113,7 +113,47 @@ def test_update_planet_successfully(client, two_saved_planets): response = client.put("planets/1", json=test_data) assert response.status_code == 200 - assert response.get_json() == {"message": "planet #1 Updated Successfully"} + assert response.get_json() == {"message": "Planet #1 successfully updated"} + +def test_update_planet_with_extra_keys(client, two_saved_planets): + test_data = {"name" : "earth", + "description" : "terrestrial, full of life", + "mass" : 5.97e24, + "moon": "Moon"} + + response = client.put("planets/1", json=test_data) + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == {"message": "Planet #1 successfully updated"} + + +def test_update_planet_missing_record(client, two_saved_planets): + test_data = { + "name": "Neptune", + "description": "thick, windy", + "mass":1.024e26 + } + + response = client.put("planets/3", json=test_data) + response_body = response.get_json() + + assert response.status_code == 404 + assert response_body == {"message": "Planet 3 not found"} + + +def test_update_planet_invalid_id(client, two_saved_planets): + test_data = { + "name": "Neptune", + "description": "thick, windy", + "mass":1.024e26 + } + + response = client.put("planets/cat", json=test_data) + response_body = response.get_json() + + assert response.status_code == 400 + assert response_body == {"message": "Planet cat invalid"} #Tests on Delete def test_delete_planet_1_with_json_request_body_returns_200(client, two_saved_planets): From c3c6cec9cca17f53550b6a51d1547bd1197bbe4c Mon Sep 17 00:00:00 2001 From: Sheung Wan Wong Date: Wed, 4 Jan 2023 23:56:12 -0700 Subject: [PATCH 33/53] refactor: Create 3 new tests for Delete method --- tests/test_routes.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tests/test_routes.py b/tests/test_routes.py index 29035c5c1..295579ead 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -168,6 +168,20 @@ def test_delete_planet_1_with_json_request_body_returns_200(client, two_saved_pl assert response.status_code == 200 assert response_body == {"message": f"planet #1 has been deleted successfully"}, 200 +def test_delete_planet_missing_record(client, two_saved_planets): + response = client.delete("planets/3") + response_body = response.get_json() + + assert response.status_code == 404 + assert response_body == {"message": "Planet 3 not found"} + +def test_delete_planet_invalid_id(client, two_saved_planets): + response = client.delete("planets/cat") + response_body = response.get_json() + + assert response.status_code == 400 + assert response_body == {"message": "Planet cat invalid"} + #Tests on valid_model(cls, model_id) def test_validate_model(two_saved_planets): result_planet = validate_model(Planet, 1) From d8fe508dad8bc676a16e65454b9b027abd91dbfa Mon Sep 17 00:00:00 2001 From: Sheung Wan Wong Date: Thu, 5 Jan 2023 00:06:36 -0700 Subject: [PATCH 34/53] Correct the return message of the Put end point --- app/routes.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index 0a939e871..5530cad0b 100644 --- a/app/routes.py +++ b/app/routes.py @@ -133,7 +133,7 @@ def update_planet(planet_id): @planets_bp.route("/", methods=["DELETE"]) def delete_planet(planet_id): - planet = validate_model(Planet, planet_id) + planet = validate_model(Planet,planet_id) db.session.delete(planet) db.session.commit() return make_response( From 75e892767b63c43ddf91452c6af7a0b8629fd202 Mon Sep 17 00:00:00 2001 From: Sheung Wan Wong Date: Thu, 5 Jan 2023 11:39:25 -0700 Subject: [PATCH 35/53] corrected syntax on line 169 --- 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 295579ead..1f0414a8b 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -166,7 +166,7 @@ def test_delete_planet_1_with_json_request_body_returns_200(client, two_saved_pl response_body = response.get_json() assert response.status_code == 200 - assert response_body == {"message": f"planet #1 has been deleted successfully"}, 200 + assert response_body == {"message": "planet #1 has been deleted successfully"} def test_delete_planet_missing_record(client, two_saved_planets): response = client.delete("planets/3") From 795ada1b5ac1ac6a1dea3681dd692f877751f89c Mon Sep 17 00:00:00 2001 From: larissa Date: Thu, 5 Jan 2023 11:18:38 -0800 Subject: [PATCH 36/53] Created Moon class and moons table --- app/models/moon.py | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 app/models/moon.py diff --git a/app/models/moon.py b/app/models/moon.py new file mode 100644 index 000000000..fa3fad4e4 --- /dev/null +++ b/app/models/moon.py @@ -0,0 +1,8 @@ +from app import db + +class Moon(db.Model): + __tablename__ = 'moons' + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + name = db.Column(db.String, nullable=False) + planet = db.relationship("Planet", back_populates="moons") + planet_id = db.Column(db.Integer, db.ForeignKey("planets.id")) \ No newline at end of file From a3ef87439a5d25a070edd60565b3381fabcbe52e Mon Sep 17 00:00:00 2001 From: larissa Date: Thu, 5 Jan 2023 11:19:26 -0800 Subject: [PATCH 37/53] Imported Moons class and registered moons_bp --- app/__init__.py | 6 ++- app/routes.py | 141 ------------------------------------------------ 2 files changed, 4 insertions(+), 143 deletions(-) delete mode 100644 app/routes.py diff --git a/app/__init__.py b/app/__init__.py index 1350259a3..b984d3ddb 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -20,11 +20,13 @@ def create_app(test_config=None): app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("SQLALCHEMY_DATABASE_URI") from app.models.planet import Planet - + from app.models.moon import Moon db.init_app(app) migrate.init_app(app, db) - from .routes import planets_bp + from .routes.planets_routes import planets_bp + from .routes.moons_routes import moons_bp app.register_blueprint(planets_bp) + app.register_blueprint(moons_bp) return app diff --git a/app/routes.py b/app/routes.py deleted file mode 100644 index 5530cad0b..000000000 --- a/app/routes.py +++ /dev/null @@ -1,141 +0,0 @@ -from app import db -from flask import Blueprint, jsonify, abort, make_response, request -from .models.planet import Planet - - -planets_bp = Blueprint("planets", __name__, url_prefix = "/planets") - - -# ~~~~~~ Helper functions ~~~~~ -# TO DO: Create separate helper function module or add as class method # -def validate_model(cls, model_id): - """ - Checks if planet id is valid and returns error messages for invalid inputs - :params: - - planet_id (int) - :returns: - - planet (object) if valid planet id valid - """ - try: - model_id = int(model_id) - except: - # handling invalid planet id type - abort(make_response({"message":f"{cls.__name__} {model_id} invalid"}, 400)) - - - # return planet data if id in db - model = cls.query.get(model_id) - - # handle nonexistant planet id - if not model: - abort(make_response({"message":f"{cls.__name__} {model_id} not found"}, 404)) - return model - -def process_kwargs(queries): - """ - Separate kwargs from HTTP request into separate dicts based on SQLAlchemy query method - :params: - - queries (dict) - :returns: - - attrs (dict): planet class attributes kwargs for filter_by - ** name, description, mass - - orderby (dict): method kwargs for order_by - ** sort_mass, sort_name - - sels (dict): selected number of results for limit - """ - planet_attrs = Planet.get_all_attrs() - order_methods = ["sort", "desc"] - attrs = {} - orderby = {} - sels = {} - for kwarg in queries: - if kwarg in planet_attrs: - attrs[kwarg] = queries[kwarg] - elif kwarg in order_methods: - orderby[kwarg] = queries[kwarg] - elif kwarg == "limit": - sels[kwarg] = queries[kwarg] - else: - abort(make_response( - {"message" : f"{kwarg} is an invalid query"}, 400 - )) - return attrs, orderby, sels - -@planets_bp.route("",methods= ["GET"]) -def display_all_planets(): - # collect query & parse kwargs - planet_query = Planet.query - attrs, orderby, sels = process_kwargs(request.args.to_dict()) - if attrs: - # filter by attribute kwargs e.g name=Earth - planet_query = planet_query.filter_by(**attrs) - if "sort" in orderby: - # sort by given attribute e.g.sort=mass - clause = getattr(Planet, orderby["sort"]) - if "desc" in orderby: - # sort in descending order e.g.desc=True - planet_query = planet_query.order_by(clause.desc()) - else: - # default is asc=True - planet_query = planet_query.order_by(clause.asc()) - if sels: - # limit selection of planets to view - planet_query = planet_query.limit(**sels) - # perform query - planets = planet_query.all() - # fill http response - response_planets = [] - for planet in planets: - response_planets.append(planet.to_dict()) - return jsonify(response_planets) - - -# ~~~~~~ Single planet endpoint ~~~~~~ -@planets_bp.route("/",methods=["GET"]) -def display_planet(planet_id): - valid_planet = validate_model(Planet, planet_id) - return valid_planet.to_dict() - -@planets_bp.route("", methods=["POST"]) -def create_planet(): - request_body = request.get_json() - - if "name" not in request_body or "description" not in request_body \ - or "mass" not in request_body: - abort(make_response({"message" : \ - "Failed to create a planet because the name and/or description \ - and/or mass are missing"}, 400)) - - # new_planet = Planet( - # name=request_body["name"], - # description=request_body["description"], - # mass=request_body["mass"]) - - new_planet = Planet.from_dict(request_body) - - db.session.add(new_planet) - db.session.commit() - - return make_response({"message":"planet has been created successfully"}, 201) - -@planets_bp.route("/", methods=["PUT"]) -def update_planet(planet_id): - request_body = request.get_json() - planet = validate_model(Planet, planet_id) - planet.name = request_body["name"] if "name" in request_body else planet.name - planet.description = request_body["description"] if "description" in request_body else planet.description - planet.mass = request_body["mass"] if "mass" in request_body else planet.mass - db.session.commit() - return make_response( - {"message": f"Planet #{planet_id} successfully updated"}, 200 - ) - - -@planets_bp.route("/", methods=["DELETE"]) -def delete_planet(planet_id): - planet = validate_model(Planet,planet_id) - db.session.delete(planet) - db.session.commit() - return make_response( - {"message": f"planet #{planet_id} has been deleted successfully"}, 200 - ) From 54e7aa33a9c8056c01f4e1bf5709dbfaf450d153 Mon Sep 17 00:00:00 2001 From: larissa Date: Thu, 5 Jan 2023 11:20:01 -0800 Subject: [PATCH 38/53] Added moons relationship to planets table and class --- app/models/planet.py | 1 + 1 file changed, 1 insertion(+) diff --git a/app/models/planet.py b/app/models/planet.py index 67e31747c..fd13e0a9a 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -6,6 +6,7 @@ class Planet(db.Model): name = db.Column(db.String, nullable=False) description = db.Column(db.String, nullable=False) mass = db.Column(db.Float, nullable=False) + moons = db.relationship("Moon", back_populates="planet") @classmethod def get_all_attrs(cls): From a577c6350fe0b87ce5dd1ba4fe0a1136fb92cd8c Mon Sep 17 00:00:00 2001 From: larissa Date: Thu, 5 Jan 2023 11:20:23 -0800 Subject: [PATCH 39/53] restructured separate routes - moons and planets --- app/routes/moons_routes.py | 9 +++ app/routes/planets_routes.py | 140 +++++++++++++++++++++++++++++++++++ 2 files changed, 149 insertions(+) create mode 100644 app/routes/moons_routes.py create mode 100644 app/routes/planets_routes.py diff --git a/app/routes/moons_routes.py b/app/routes/moons_routes.py new file mode 100644 index 000000000..888b20b1c --- /dev/null +++ b/app/routes/moons_routes.py @@ -0,0 +1,9 @@ +from app import db +from flask import Blueprint, jsonify, abort, make_response, request +from ..models.moon import Moon + +moons_bp = Blueprint("moons", __name__, url_prefix = "/moons") + +# Add nested routes for the endpoint `/planets//moons` to: +# Create a Moon and link it to an existing Planet record +# Fetch all Moons that a Planet is associated with diff --git a/app/routes/planets_routes.py b/app/routes/planets_routes.py new file mode 100644 index 000000000..fecd3e10e --- /dev/null +++ b/app/routes/planets_routes.py @@ -0,0 +1,140 @@ +from app import db +from flask import Blueprint, jsonify, abort, make_response, request +from app.models.planet import Planet + + +planets_bp = Blueprint("planets", __name__, url_prefix = "/planets") + +# ~~~~~~ Helper functions ~~~~~ +# TO DO: Create separate helper function module or add as class method # +def validate_model(cls, model_id): + """ + Checks if planet id is valid and returns error messages for invalid inputs + :params: + - planet_id (int) + :returns: + - planet (object) if valid planet id valid + """ + try: + model_id = int(model_id) + except: + # handling invalid planet id type + abort(make_response({"message":f"{cls.__name__} {model_id} invalid"}, 400)) + + + # return planet data if id in db + model = cls.query.get(model_id) + + # handle nonexistant planet id + if not model: + abort(make_response({"message":f"{cls.__name__} {model_id} not found"}, 404)) + return model + +def process_kwargs(queries): + """ + Separate kwargs from HTTP request into separate dicts based on SQLAlchemy query method + :params: + - queries (dict) + :returns: + - attrs (dict): planet class attributes kwargs for filter_by + ** name, description, mass + - orderby (dict): method kwargs for order_by + ** sort_mass, sort_name + - sels (dict): selected number of results for limit + """ + planet_attrs = Planet.get_all_attrs() + order_methods = ["sort", "desc"] + attrs = {} + orderby = {} + sels = {} + for kwarg in queries: + if kwarg in planet_attrs: + attrs[kwarg] = queries[kwarg] + elif kwarg in order_methods: + orderby[kwarg] = queries[kwarg] + elif kwarg == "limit": + sels[kwarg] = queries[kwarg] + else: + abort(make_response( + {"message" : f"{kwarg} is an invalid query"}, 400 + )) + return attrs, orderby, sels + +@planets_bp.route("",methods= ["GET"]) +def display_all_planets(): + # collect query & parse kwargs + planet_query = Planet.query + attrs, orderby, sels = process_kwargs(request.args.to_dict()) + if attrs: + # filter by attribute kwargs e.g name=Earth + planet_query = planet_query.filter_by(**attrs) + if "sort" in orderby: + # sort by given attribute e.g.sort=mass + clause = getattr(Planet, orderby["sort"]) + if "desc" in orderby: + # sort in descending order e.g.desc=True + planet_query = planet_query.order_by(clause.desc()) + else: + # default is asc=True + planet_query = planet_query.order_by(clause.asc()) + if sels: + # limit selection of planets to view + planet_query = planet_query.limit(**sels) + # perform query + planets = planet_query.all() + # fill http response + response_planets = [] + for planet in planets: + response_planets.append(planet.to_dict()) + return jsonify(response_planets) + + +# ~~~~~~ Single planet endpoint ~~~~~~ +@planets_bp.route("/",methods=["GET"]) +def display_planet(planet_id): + valid_planet = validate_model(Planet, planet_id) + return valid_planet.to_dict() + +@planets_bp.route("", methods=["POST"]) +def create_planet(): + request_body = request.get_json() + + if "name" not in request_body or "description" not in request_body \ + or "mass" not in request_body: + abort(make_response({"message" : \ + "Failed to create a planet because the name and/or description \ + and/or mass are missing"}, 400)) + + # new_planet = Planet( + # name=request_body["name"], + # description=request_body["description"], + # mass=request_body["mass"]) + + new_planet = Planet.from_dict(request_body) + + db.session.add(new_planet) + db.session.commit() + + return make_response({"message":"planet has been created successfully"}, 201) + +@planets_bp.route("/", methods=["PUT"]) +def update_planet(planet_id): + request_body = request.get_json() + planet = validate_model(Planet, planet_id) + planet.name = request_body["name"] if "name" in request_body else planet.name + planet.description = request_body["description"] if "description" in request_body else planet.description + planet.mass = request_body["mass"] if "mass" in request_body else planet.mass + db.session.commit() + return make_response( + {"message": f"Planet #{planet_id} successfully updated"}, 200 + ) + + +@planets_bp.route("/", methods=["DELETE"]) +def delete_planet(planet_id): + planet = validate_model(Planet,planet_id) + db.session.delete(planet) + db.session.commit() + return make_response( + {"message": f"planet #{planet_id} has been deleted successfully"}, 200 + ) From 461fd90902d44681c636000698bd7e63336793c4 Mon Sep 17 00:00:00 2001 From: larissa Date: Thu, 5 Jan 2023 12:08:28 -0800 Subject: [PATCH 40/53] got new moon routes working --- app/models/moon.py | 19 ++++++++++++++ app/routes.py | 25 ++++++++++++++++++- app/routes/moons_routes.py | 14 +++++++++++ ...329eb8e0b_brand_new_migrations_woo_hoo.py} | 17 ++++++++++--- 4 files changed, 70 insertions(+), 5 deletions(-) create mode 100644 app/models/moon.py create mode 100644 app/routes/moons_routes.py rename migrations/versions/{040c4f56aefe_.py => ffa329eb8e0b_brand_new_migrations_woo_hoo.py} (61%) diff --git a/app/models/moon.py b/app/models/moon.py new file mode 100644 index 000000000..c58d00170 --- /dev/null +++ b/app/models/moon.py @@ -0,0 +1,19 @@ +from app import db + +class Moon(db.Model): + __tablename__ = 'moons' + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + name = db.Column(db.String, nullable=False) + planet = db.relationship("Planet", back_populates="moons") + planet_id = db.Column(db.Integer, db.ForeignKey("planets.id")) + + def to_dict(self): + """ + Returns dictionary containing Planet instance data + """ + return { + "id": self.id, + "name": self.name, + "planet_id": self.planet_id, + "planet": self.planet.name, + } \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 5530cad0b..3573198f7 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,6 +1,11 @@ from app import db from flask import Blueprint, jsonify, abort, make_response, request +<<<<<<< Updated upstream:app/routes.py from .models.planet import Planet +======= +from app.models.planet import Planet +from app.models.moon import Moon +>>>>>>> Stashed changes:app/routes/planets_routes.py planets_bp = Blueprint("planets", __name__, url_prefix = "/planets") @@ -133,9 +138,27 @@ def update_planet(planet_id): @planets_bp.route("/", methods=["DELETE"]) def delete_planet(planet_id): - planet = validate_model(Planet,planet_id) + planet = validate_model(Planet, planet_id) db.session.delete(planet) db.session.commit() return make_response( {"message": f"planet #{planet_id} has been deleted successfully"}, 200 ) + +# nested routes`/planets//moons` to: +# Create a Moon and link it to an existing Planet record +# Fetch all Moons that a Planet is associated with +@planets_bp.route("//moons", methods=["POST"]) +def create_moon(planet_id): + planet = validate_model(Planet, planet_id) + request_body = request.get_json() + new_moon = Moon( + name=request_body["name"], + planet_id=planet_id, + planet=planet + ) + db.session.add(new_moon) + db.session.commit() + return make_response({ + "message": f"Moon {new_moon.name} for Planet {planet.name} successfully created" + }, 201) \ No newline at end of file diff --git a/app/routes/moons_routes.py b/app/routes/moons_routes.py new file mode 100644 index 000000000..9c831d777 --- /dev/null +++ b/app/routes/moons_routes.py @@ -0,0 +1,14 @@ +from app import db +from flask import Blueprint, jsonify, abort, make_response, request +from ..models.moon import Moon + +moons_bp = Blueprint("moons", __name__, url_prefix = "/moons") + +@moons_bp.route("", methods=["GET"]) +def display_all_moons(): + moons = Moon.query.all() + # fill http response + response_moons = [] + for moon in moons: + response_moons.append(moon.to_dict()) + return jsonify(response_moons) \ No newline at end of file diff --git a/migrations/versions/040c4f56aefe_.py b/migrations/versions/ffa329eb8e0b_brand_new_migrations_woo_hoo.py similarity index 61% rename from migrations/versions/040c4f56aefe_.py rename to migrations/versions/ffa329eb8e0b_brand_new_migrations_woo_hoo.py index 048f67d14..d872919e1 100644 --- a/migrations/versions/040c4f56aefe_.py +++ b/migrations/versions/ffa329eb8e0b_brand_new_migrations_woo_hoo.py @@ -1,8 +1,9 @@ -"""empty message +"""Brand new migrations. Woo hoo -Revision ID: 040c4f56aefe + +Revision ID: ffa329eb8e0b Revises: -Create Date: 2022-12-21 18:58:13.305413 +Create Date: 2023-01-05 11:47:27.099655 """ from alembic import op @@ -10,7 +11,7 @@ # revision identifiers, used by Alembic. -revision = '040c4f56aefe' +revision = 'ffa329eb8e0b' down_revision = None branch_labels = None depends_on = None @@ -25,10 +26,18 @@ def upgrade(): sa.Column('mass', sa.Float(), nullable=False), sa.PrimaryKeyConstraint('id') ) + op.create_table('moons', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('planet_id', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['planet_id'], ['planets.id'], ), + sa.PrimaryKeyConstraint('id') + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('moons') op.drop_table('planets') # ### end Alembic commands ### From b6cd501b45e39df3e8f0b875b249dbcb1a880b0c Mon Sep 17 00:00:00 2001 From: larissa Date: Thu, 5 Jan 2023 12:16:33 -0800 Subject: [PATCH 41/53] corrected conflict --- app/routes.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/app/routes.py b/app/routes.py index 3573198f7..705461b24 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,11 +1,7 @@ from app import db from flask import Blueprint, jsonify, abort, make_response, request -<<<<<<< Updated upstream:app/routes.py -from .models.planet import Planet -======= from app.models.planet import Planet from app.models.moon import Moon ->>>>>>> Stashed changes:app/routes/planets_routes.py planets_bp = Blueprint("planets", __name__, url_prefix = "/planets") From 2bfa6b57b029297d432bedd95f3b76f311cebbe5 Mon Sep 17 00:00:00 2001 From: "echo '# Set PATH, MANPATH, etc., for Homebrew.' /Users/daliaali/.zprofile" Date: Thu, 5 Jan 2023 19:30:41 -0800 Subject: [PATCH 42/53] added attributes:size, description and discovery_date to the moon model, changed the imports test_routes file to reflect the routes directory restructuring, added an __init__.py file to routes directory --- app/models/moon.py | 6 ++++++ app/routes/__init__.py | 0 ...nd_new_migrations_woo_hoo.py => bc96d5e6f467_.py} | 12 +++++++----- tests/test_routes.py | 2 +- 4 files changed, 14 insertions(+), 6 deletions(-) create mode 100644 app/routes/__init__.py rename migrations/versions/{ffa329eb8e0b_brand_new_migrations_woo_hoo.py => bc96d5e6f467_.py} (79%) diff --git a/app/models/moon.py b/app/models/moon.py index c58d00170..98317dd76 100644 --- a/app/models/moon.py +++ b/app/models/moon.py @@ -4,6 +4,9 @@ class Moon(db.Model): __tablename__ = 'moons' id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String, nullable=False) + size = db.Column(db.String, nullable=False) + description = db.Column(db.String, nullable=False) + discovery_date = db.Column(db.DateTime, nullable=False) planet = db.relationship("Planet", back_populates="moons") planet_id = db.Column(db.Integer, db.ForeignKey("planets.id")) @@ -14,6 +17,9 @@ def to_dict(self): return { "id": self.id, "name": self.name, + "size": self.size, + "description": self.description, + "discovery_date": self.discovery_date, "planet_id": self.planet_id, "planet": self.planet.name, } \ 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/migrations/versions/ffa329eb8e0b_brand_new_migrations_woo_hoo.py b/migrations/versions/bc96d5e6f467_.py similarity index 79% rename from migrations/versions/ffa329eb8e0b_brand_new_migrations_woo_hoo.py rename to migrations/versions/bc96d5e6f467_.py index d872919e1..9ed44389b 100644 --- a/migrations/versions/ffa329eb8e0b_brand_new_migrations_woo_hoo.py +++ b/migrations/versions/bc96d5e6f467_.py @@ -1,9 +1,8 @@ -"""Brand new migrations. Woo hoo +"""empty message - -Revision ID: ffa329eb8e0b +Revision ID: bc96d5e6f467 Revises: -Create Date: 2023-01-05 11:47:27.099655 +Create Date: 2023-01-05 19:08:01.063060 """ from alembic import op @@ -11,7 +10,7 @@ # revision identifiers, used by Alembic. -revision = 'ffa329eb8e0b' +revision = 'bc96d5e6f467' down_revision = None branch_labels = None depends_on = None @@ -29,6 +28,9 @@ def upgrade(): op.create_table('moons', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), sa.Column('name', sa.String(), nullable=False), + sa.Column('size', sa.String(), nullable=False), + sa.Column('description', sa.String(), nullable=False), + sa.Column('discovery_date', sa.DateTime(), nullable=False), sa.Column('planet_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['planet_id'], ['planets.id'], ), sa.PrimaryKeyConstraint('id') diff --git a/tests/test_routes.py b/tests/test_routes.py index 1f0414a8b..434d294a9 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -1,5 +1,5 @@ from werkzeug.exceptions import HTTPException -from app.routes import validate_model +from app.routes.planets_routes import validate_model from app.models.planet import Planet import pytest From 7613730c735ec5ae36852d8c03162757d957b8bf Mon Sep 17 00:00:00 2001 From: "echo '# Set PATH, MANPATH, etc., for Homebrew.' /Users/daliaali/.zprofile" Date: Thu, 5 Jan 2023 20:07:38 -0800 Subject: [PATCH 43/53] updated POST planets//moons to reflect changes made in the moon model and added a validation to make sure the request body has all the required attributes for the moon --- app/routes/planets_routes.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/app/routes/planets_routes.py b/app/routes/planets_routes.py index e71e9f366..3b1e2b84d 100644 --- a/app/routes/planets_routes.py +++ b/app/routes/planets_routes.py @@ -147,8 +147,19 @@ def delete_planet(planet_id): def create_moon(planet_id): planet = validate_model(Planet, planet_id) request_body = request.get_json() + required_attributes = ["name", "size", "description", "discovery_date"] + + for attr in required_attributes: + if attr not in request_body: + abort(make_response(jsonify({ + "message":f"{attr} must be included to add a moon" + }), 400)) + new_moon = Moon( name=request_body["name"], + size=request_body["size"], + description=request_body["description"], + discovery_date=request_body["discovery_date"], planet_id=planet_id, planet=planet ) From 8f342db0fbb27aa9843b93b0f89e077fc1954469 Mon Sep 17 00:00:00 2001 From: Sheung Wan Wong Date: Thu, 5 Jan 2023 23:47:04 -0700 Subject: [PATCH 44/53] feat: Create nested route - Get all moons by planed_id --- app/routes/planets_routes.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/app/routes/planets_routes.py b/app/routes/planets_routes.py index 3b1e2b84d..2a5c71dc6 100644 --- a/app/routes/planets_routes.py +++ b/app/routes/planets_routes.py @@ -154,7 +154,8 @@ def create_moon(planet_id): abort(make_response(jsonify({ "message":f"{attr} must be included to add a moon" }), 400)) - + + # TO DO: refactor using from_dict new_moon = Moon( name=request_body["name"], size=request_body["size"], @@ -167,4 +168,14 @@ def create_moon(planet_id): db.session.commit() return make_response({ "message": f"Moon {new_moon.name} for Planet {planet.name} successfully created" - }, 201) \ No newline at end of file + }, 201) + +#nested routes GET `/planets//moons` +@planets_bp.route("//moons", methods=["GET"]) +def read_moons(planet_id): + planet = validate_model(Planet, planet_id) + + moons_response = [] + for moon in planet.moons: + moons_response.append(moon.to_dict()) + return jsonify(moons_response) \ No newline at end of file From d04aa822d19469d7761374fbd4fef91d229ba73c Mon Sep 17 00:00:00 2001 From: larissa Date: Fri, 6 Jan 2023 14:34:24 -0800 Subject: [PATCH 45/53] re-initialized migrations --- ...2e9f4c3f0c72_redoing_migrations_to_debug_errors.py} | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) rename migrations/versions/{bc96d5e6f467_.py => 2e9f4c3f0c72_redoing_migrations_to_debug_errors.py} (86%) diff --git a/migrations/versions/bc96d5e6f467_.py b/migrations/versions/2e9f4c3f0c72_redoing_migrations_to_debug_errors.py similarity index 86% rename from migrations/versions/bc96d5e6f467_.py rename to migrations/versions/2e9f4c3f0c72_redoing_migrations_to_debug_errors.py index 9ed44389b..1526c7daa 100644 --- a/migrations/versions/bc96d5e6f467_.py +++ b/migrations/versions/2e9f4c3f0c72_redoing_migrations_to_debug_errors.py @@ -1,8 +1,8 @@ -"""empty message +"""Redoing migrations to debug errors -Revision ID: bc96d5e6f467 +Revision ID: 2e9f4c3f0c72 Revises: -Create Date: 2023-01-05 19:08:01.063060 +Create Date: 2023-01-06 12:22:34.301088 """ from alembic import op @@ -10,7 +10,7 @@ # revision identifiers, used by Alembic. -revision = 'bc96d5e6f467' +revision = '2e9f4c3f0c72' down_revision = None branch_labels = None depends_on = None @@ -28,7 +28,7 @@ def upgrade(): op.create_table('moons', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), sa.Column('name', sa.String(), nullable=False), - sa.Column('size', sa.String(), nullable=False), + sa.Column('size', sa.Float(), nullable=False), sa.Column('description', sa.String(), nullable=False), sa.Column('discovery_date', sa.DateTime(), nullable=False), sa.Column('planet_id', sa.Integer(), nullable=True), From 67b832bde93476699b92af73621f5e9ec9f6594c Mon Sep 17 00:00:00 2001 From: larissa Date: Fri, 6 Jan 2023 14:36:13 -0800 Subject: [PATCH 46/53] added from_dict moon class method --- app/models/moon.py | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/app/models/moon.py b/app/models/moon.py index 98317dd76..5665bb65d 100644 --- a/app/models/moon.py +++ b/app/models/moon.py @@ -4,12 +4,30 @@ class Moon(db.Model): __tablename__ = 'moons' id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String, nullable=False) - size = db.Column(db.String, nullable=False) + size = db.Column(db.Float, nullable=False) description = db.Column(db.String, nullable=False) discovery_date = db.Column(db.DateTime, nullable=False) planet = db.relationship("Planet", back_populates="moons") planet_id = db.Column(db.Integer, db.ForeignKey("planets.id")) + @classmethod + def get_all_attrs(cls): + """ + Returns all existing attributes (list) in Planet class + """ + return [attr for attr in dir(cls) if callable(attr)] + + @classmethod + def from_dict(cls, dict, planet, planet_id): + return Moon( + name=dict["name"], + size=dict["size"], + description=dict["description"], + discovery_date=dict["discovery_date"], + planet=planet, + planet_id=planet_id, + ) + def to_dict(self): """ Returns dictionary containing Planet instance data @@ -21,5 +39,5 @@ def to_dict(self): "description": self.description, "discovery_date": self.discovery_date, "planet_id": self.planet_id, - "planet": self.planet.name, + #"planet": self.planet.name, } \ No newline at end of file From d9f96e21503b100e60b4dd9d30c59568135269a3 Mon Sep 17 00:00:00 2001 From: larissa Date: Fri, 6 Jan 2023 14:37:01 -0800 Subject: [PATCH 47/53] refactored code to make use of Moon.from_dict() --- app/routes/planets_routes.py | 54 ++++++++++++------------------------ 1 file changed, 18 insertions(+), 36 deletions(-) diff --git a/app/routes/planets_routes.py b/app/routes/planets_routes.py index 2a5c71dc6..576290ef2 100644 --- a/app/routes/planets_routes.py +++ b/app/routes/planets_routes.py @@ -6,8 +6,7 @@ planets_bp = Blueprint("planets", __name__, url_prefix = "/planets") -# ~~~~~~ Helper functions ~~~~~ -# TO DO: Create separate helper function module or add as class method # +# ~~~~~~ Validation Checkers ~~~~~ def validate_model(cls, model_id): """ Checks if planet id is valid and returns error messages for invalid inputs @@ -21,16 +20,14 @@ def validate_model(cls, model_id): except: # handling invalid planet id type abort(make_response({"message":f"{cls.__name__} {model_id} invalid"}, 400)) - - # return planet data if id in db model = cls.query.get(model_id) - # handle nonexistant planet id if not model: abort(make_response({"message":f"{cls.__name__} {model_id} not found"}, 404)) return model + def process_kwargs(queries): """ Separate kwargs from HTTP request into separate dicts based on SQLAlchemy query method @@ -61,6 +58,8 @@ def process_kwargs(queries): )) return attrs, orderby, sels + +# ~~~~~~ Planet Routes ~~~~~ @planets_bp.route("",methods= ["GET"]) def display_all_planets(): # collect query & parse kwargs @@ -96,28 +95,22 @@ def display_planet(planet_id): valid_planet = validate_model(Planet, planet_id) return valid_planet.to_dict() + @planets_bp.route("", methods=["POST"]) def create_planet(): request_body = request.get_json() - - if "name" not in request_body or "description" not in request_body \ - or "mass" not in request_body: - abort(make_response({"message" : \ - "Failed to create a planet because the name and/or description \ - and/or mass are missing"}, 400)) - - # new_planet = Planet( - # name=request_body["name"], - # description=request_body["description"], - # mass=request_body["mass"]) - + attribute_requirements = ["name", "decription", "mass"] + for req in attribute_requirements: + if req not in request_body: + abort(make_response({ + "message" : f"Failed to create a planet because {req} missing" + }, 400)) new_planet = Planet.from_dict(request_body) - db.session.add(new_planet) db.session.commit() - return make_response({"message":"planet has been created successfully"}, 201) + @planets_bp.route("/", methods=["PUT"]) def update_planet(planet_id): request_body = request.get_json() @@ -140,42 +133,31 @@ def delete_planet(planet_id): {"message": f"planet #{planet_id} has been deleted successfully"}, 200 ) -# nested routes`/planets//moons` to: -# Create a Moon and link it to an existing Planet record -# Fetch all Moons that a Planet is associated with + @planets_bp.route("//moons", methods=["POST"]) def create_moon(planet_id): planet = validate_model(Planet, planet_id) request_body = request.get_json() - required_attributes = ["name", "size", "description", "discovery_date"] - + required_attributes = Moon.get_all_attrs() + # check for all required post attributes in request body for attr in required_attributes: if attr not in request_body: abort(make_response(jsonify({ "message":f"{attr} must be included to add a moon" }), 400)) - - # TO DO: refactor using from_dict - new_moon = Moon( - name=request_body["name"], - size=request_body["size"], - description=request_body["description"], - discovery_date=request_body["discovery_date"], - planet_id=planet_id, - planet=planet - ) + new_moon = Moon.from_dict(request_body, planet, planet_id) db.session.add(new_moon) db.session.commit() return make_response({ "message": f"Moon {new_moon.name} for Planet {planet.name} successfully created" }, 201) + #nested routes GET `/planets//moons` @planets_bp.route("//moons", methods=["GET"]) def read_moons(planet_id): planet = validate_model(Planet, planet_id) - moons_response = [] for moon in planet.moons: moons_response.append(moon.to_dict()) - return jsonify(moons_response) \ No newline at end of file + return jsonify(moons_response) From 45f64cdde2ece2340a370a2e429b7192df09f4d6 Mon Sep 17 00:00:00 2001 From: larissa Date: Fri, 6 Jan 2023 14:37:18 -0800 Subject: [PATCH 48/53] small refactors --- app/models/planet.py | 2 +- app/routes/moons_routes.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/app/models/planet.py b/app/models/planet.py index fd13e0a9a..46140b168 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -13,7 +13,7 @@ def get_all_attrs(cls): """ Returns all existing attributes (list) in Planet class """ - return [attr for attr in dir(Planet) if not attr.startswith('__')] + return [attr for attr in dir(Planet) if callable(attr)] @classmethod def from_dict(cls, dict): diff --git a/app/routes/moons_routes.py b/app/routes/moons_routes.py index 65e7a5665..4754a300f 100644 --- a/app/routes/moons_routes.py +++ b/app/routes/moons_routes.py @@ -4,6 +4,7 @@ moons_bp = Blueprint("moons", __name__, url_prefix = "/moons") +# ~~~~~~ Planet Routes ~~~~~ @moons_bp.route("", methods=["GET"]) def display_all_moons(): moons = Moon.query.all() From 3efb4e031832fba0539009778cddb72a50538204 Mon Sep 17 00:00:00 2001 From: Sheung Wan Wong Date: Sun, 8 Jan 2023 21:22:37 -0700 Subject: [PATCH 49/53] correct typo to description --- app/routes/moons_routes.py | 9 ++++++++- app/routes/planets_routes.py | 2 +- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/app/routes/moons_routes.py b/app/routes/moons_routes.py index 4754a300f..28be14e03 100644 --- a/app/routes/moons_routes.py +++ b/app/routes/moons_routes.py @@ -1,7 +1,7 @@ from app import db from flask import Blueprint, jsonify, abort, make_response, request from ..models.moon import Moon - +from app.routes.planets_routes import validate_model moons_bp = Blueprint("moons", __name__, url_prefix = "/moons") # ~~~~~~ Planet Routes ~~~~~ @@ -13,3 +13,10 @@ def display_all_moons(): for moon in moons: response_moons.append(moon.to_dict()) return jsonify(response_moons) + +@moons_bp.route("/",methods=["GET"]) +def display_moon(moon_id): + moon = validate_model(Moon, moon_id) + return moon.to_dict() + + diff --git a/app/routes/planets_routes.py b/app/routes/planets_routes.py index 576290ef2..0143ea3ac 100644 --- a/app/routes/planets_routes.py +++ b/app/routes/planets_routes.py @@ -99,7 +99,7 @@ def display_planet(planet_id): @planets_bp.route("", methods=["POST"]) def create_planet(): request_body = request.get_json() - attribute_requirements = ["name", "decription", "mass"] + attribute_requirements = ["name", "description", "mass"] for req in attribute_requirements: if req not in request_body: abort(make_response({ From e3b398cffa1ce98d6814b54b9734a4fefd10ec22 Mon Sep 17 00:00:00 2001 From: Sheung Wan Wong Date: Sun, 8 Jan 2023 21:49:24 -0700 Subject: [PATCH 50/53] didn't update moon model or planet model, only add GET moon by id endpoint and POST moons endpoint --- app/models/moon.py | 3 ++- app/models/planet.py | 8 ++++++-- app/routes/moons_routes.py | 20 ++++++++++++++++++++ 3 files changed, 28 insertions(+), 3 deletions(-) diff --git a/app/models/moon.py b/app/models/moon.py index 5665bb65d..97b42c133 100644 --- a/app/models/moon.py +++ b/app/models/moon.py @@ -40,4 +40,5 @@ def to_dict(self): "discovery_date": self.discovery_date, "planet_id": self.planet_id, #"planet": self.planet.name, - } \ No newline at end of file + } + \ No newline at end of file diff --git a/app/models/planet.py b/app/models/planet.py index 46140b168..4e3bb6f09 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -16,7 +16,7 @@ def get_all_attrs(cls): return [attr for attr in dir(Planet) if callable(attr)] @classmethod - def from_dict(cls, dict): + def from_dict(cls, dict, planet_id): return Planet(name=dict["name"], description=dict["description"], mass=dict["mass"]) @@ -30,4 +30,8 @@ def to_dict(self): "name": self.name, "description": self.description, "mass": self.mass - } \ No newline at end of file + } + # @classmethod + # def get_planet_by_id(cls, id): + # return cls.query.get(id) + \ No newline at end of file diff --git a/app/routes/moons_routes.py b/app/routes/moons_routes.py index 28be14e03..68d0506be 100644 --- a/app/routes/moons_routes.py +++ b/app/routes/moons_routes.py @@ -1,6 +1,7 @@ from app import db from flask import Blueprint, jsonify, abort, make_response, request from ..models.moon import Moon +from ..models.planet import Planet from app.routes.planets_routes import validate_model moons_bp = Blueprint("moons", __name__, url_prefix = "/moons") @@ -20,3 +21,22 @@ def display_moon(moon_id): return moon.to_dict() +@moons_bp.route("", methods=["POST"]) +def create_moon(): + request_body = request.get_json() + + #required request body: name, description, size, discovery_date, planet_id + attribute_requirements = ["name", "description", "size", "discovery_date", "planet_id"] + + for req in attribute_requirements: + if req not in request_body: + abort(make_response({ + "message" : f"Failed to create a planet because {req} missing" + }, 400)) + + planet_id = request_body["planet_id"] + planet = validate_model(Planet, planet_id) + new_moon = Moon.from_dict(request_body, planet, planet_id) + db.session.add(new_moon) + db.session.commit() + return make_response({"message": "moon has been created successfully"}, 201) \ No newline at end of file From 346386c25b930f32b12786e3624f4b686239d7d5 Mon Sep 17 00:00:00 2001 From: Sheung Wan Wong Date: Sun, 8 Jan 2023 21:56:37 -0700 Subject: [PATCH 51/53] corrct the assert response_body part of test_create_one_planet_missing_mass_return_400 --- app/models/planet.py | 2 +- tests/test_routes.py | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index 4e3bb6f09..b37161785 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -16,7 +16,7 @@ def get_all_attrs(cls): return [attr for attr in dir(Planet) if callable(attr)] @classmethod - def from_dict(cls, dict, planet_id): + def from_dict(cls, dict): return Planet(name=dict["name"], description=dict["description"], mass=dict["mass"]) diff --git a/tests/test_routes.py b/tests/test_routes.py index 434d294a9..930820f2f 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -102,8 +102,7 @@ def test_create_one_planet_missing_mass_return_400(client): assert response.status_code == 400 assert response_body == {"message" : \ - "Failed to create a planet because the name and/or description \ - and/or mass are missing"} + "Failed to create a planet because mass missing"} #Tests on Put def test_update_planet_successfully(client, two_saved_planets): From ab7ca3bce15738728d5ad070587f28d6c6fb1d12 Mon Sep 17 00:00:00 2001 From: Sheung Wan Wong Date: Mon, 9 Jan 2023 11:07:07 -0700 Subject: [PATCH 52/53] gunicorn to the requirements.t xt --- requirements.txt | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/requirements.txt b/requirements.txt index fba2b3e38..3e19aa0b1 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,18 +1,25 @@ alembic==1.5.4 +attrs==22.2.0 autopep8==1.5.5 blinker==1.4 certifi==2020.12.5 chardet==4.0.0 click==7.1.2 +coverage==7.0.3 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==22.0 +pluggy==1.0.0 psycopg2-binary==2.9.4 +py==1.11.0 pycodestyle==2.6.0 pytest==7.1.1 pytest-cov==2.12.1 @@ -23,5 +30,6 @@ requests==2.25.1 six==1.15.0 SQLAlchemy==1.3.23 toml==0.10.2 +tomli==2.0.1 urllib3==1.26.4 Werkzeug==1.0.1 From 28dbcf09c390dd31d505973eb694d81cbc24e9ba Mon Sep 17 00:00:00 2001 From: Sheung Wan Wong Date: Mon, 9 Jan 2023 11:10:42 -0700 Subject: [PATCH 53/53] Create a Procfile for Heroku --- Procfile | 1 + 1 file changed, 1 insertion(+) create mode 100644 Procfile diff --git a/Procfile b/Procfile new file mode 100644 index 000000000..62e430aca --- /dev/null +++ b/Procfile @@ -0,0 +1 @@ +web: gunicorn 'app:create_app()' \ No newline at end of file