From 9a447572057bc4b8428a1c6525e9b46d3f12d1c8 Mon Sep 17 00:00:00 2001 From: Anika Stephen Wilbur Date: Fri, 21 Oct 2022 11:04:02 -0700 Subject: [PATCH 01/29] Create Planet class and start planets endpoint --- app/routes.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..f814dab62 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,21 @@ from flask import Blueprint +class Planet: + def __init__(self, id, name, description, moons): + self.id = id + self.name = name + self.description = description + self.moons = moons + + +planets = [ + Planet(1, "Mercury", "solid", 0), + Planet(2, "Venus", "bright and volcanic", 0), + Planet(3, "Earth", "half and half", 1) +] + +planets_bp = Blueprint("planets", __name__, url_defaults="/planets") + +@planets_bp.route("", methods=["GET"]) +def planets_endpoint(): + pass \ No newline at end of file From 1c49aa964184d58e6489feae2fd79e16fd5738ec Mon Sep 17 00:00:00 2001 From: Anika Stephen Wilbur Date: Fri, 21 Oct 2022 11:05:50 -0700 Subject: [PATCH 02/29] Register planets_bp --- app/__init__.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..ab9eee40e 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -4,4 +4,7 @@ def create_app(test_config=None): app = Flask(__name__) + from .routes import planets_bp + app.register_blueprint(planets_bp) + return app From 90963d7a01c34c96b2fa01345b4bbbe1123401d0 Mon Sep 17 00:00:00 2001 From: Anika Stephen Wilbur Date: Fri, 21 Oct 2022 11:10:04 -0700 Subject: [PATCH 03/29] Built out planets_endpoint --- app/routes.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/app/routes.py b/app/routes.py index f814dab62..928e53bb8 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,4 +1,4 @@ -from flask import Blueprint +from flask import Blueprint, jsonify class Planet: def __init__(self, id, name, description, moons): @@ -18,4 +18,12 @@ def __init__(self, id, name, description, moons): @planets_bp.route("", methods=["GET"]) def planets_endpoint(): - pass \ No newline at end of file + response = [] + for planet in planets: + response.append(dict( + id = planet.id, + name = planet.name, + description = planet.description, + moons = planet.moons + )) + return jsonify(response) \ No newline at end of file From b3eabbc84818939ea4acde1d0c4722222122e957 Mon Sep 17 00:00:00 2001 From: Annie Date: Fri, 21 Oct 2022 12:21:09 -0600 Subject: [PATCH 04/29] fixed bug on line 17 - url_default -> url_prefix --- app/routes.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index 928e53bb8..4798f9012 100644 --- a/app/routes.py +++ b/app/routes.py @@ -14,7 +14,7 @@ def __init__(self, id, name, description, moons): Planet(3, "Earth", "half and half", 1) ] -planets_bp = Blueprint("planets", __name__, url_defaults="/planets") +planets_bp = Blueprint("planets", __name__, url_prefix="/planets") @planets_bp.route("", methods=["GET"]) def planets_endpoint(): From d72019b17f1395cdfdc886003890559bdb187264 Mon Sep 17 00:00:00 2001 From: Anika Stephen Wilbur Date: Fri, 21 Oct 2022 11:23:26 -0700 Subject: [PATCH 05/29] Pushing to pull --- app/routes.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/app/routes.py b/app/routes.py index 928e53bb8..b62aa9a53 100644 --- a/app/routes.py +++ b/app/routes.py @@ -20,10 +20,12 @@ def __init__(self, id, name, description, moons): def planets_endpoint(): response = [] for planet in planets: - response.append(dict( - id = planet.id, - name = planet.name, - description = planet.description, - moons = planet.moons - )) + response.append( + dict( + id = planet.id, + name = planet.name, + description = planet.description, + moons = planet.moons + ) + ) return jsonify(response) \ No newline at end of file From f7af76654ac03629243dbd968b9ec91935363859 Mon Sep 17 00:00:00 2001 From: Annie Date: Mon, 24 Oct 2022 12:30:53 -0600 Subject: [PATCH 06/29] updated planets_endpoint to use list comprehension --- app/routes.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/app/routes.py b/app/routes.py index 4798f9012..38c8f1bce 100644 --- a/app/routes.py +++ b/app/routes.py @@ -18,12 +18,9 @@ def __init__(self, id, name, description, moons): @planets_bp.route("", methods=["GET"]) def planets_endpoint(): - response = [] - for planet in planets: - response.append(dict( - id = planet.id, + response = [dict(id = planet.id, name = planet.name, description = planet.description, moons = planet.moons - )) + ) for planet in planets] return jsonify(response) \ No newline at end of file From 799e620aa2bfadd4ed228c26e9b5d2c3bcd4a1e2 Mon Sep 17 00:00:00 2001 From: Annie Date: Mon, 24 Oct 2022 12:38:59 -0600 Subject: [PATCH 07/29] added single planet endpoint --- app/routes.py | 34 +++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/app/routes.py b/app/routes.py index 38c8f1bce..b883a2674 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,4 +1,4 @@ -from flask import Blueprint, jsonify +from flask import Blueprint, jsonify, abort, make_response class Planet: def __init__(self, id, name, description, moons): @@ -7,6 +7,12 @@ def __init__(self, id, name, description, moons): self.description = description self.moons = moons + def to_json(self): + dict(id = self.id, + name = self.name, + description = self.description, + moons = self.moons + ) planets = [ Planet(1, "Mercury", "solid", 0), @@ -18,9 +24,23 @@ def __init__(self, id, name, description, moons): @planets_bp.route("", methods=["GET"]) def planets_endpoint(): - response = [dict(id = planet.id, - name = planet.name, - description = planet.description, - moons = planet.moons - ) for planet in planets] - return jsonify(response) \ No newline at end of file + response = [planet.to_json for planet in planets] + return jsonify(response) + +@planets_bp.route("/", methods=["GET"]) +def planet_endpoint(planet_id): + planet = validate_planet(planet_id) + + return jsonify(planet.to_json) + +def validate_planet(planet_id): + try: + planet_id = int(planet_id) + except: + abort(make_response({"message":f"planet {planet_id} invalid"}, 400)) + + for planet in planets: + if planet.id == planet_id: + return planet + + abort(make_response({"message":f"planet {planet_id} not found"}, 404)) \ No newline at end of file From a2489d99cf416bdd0616d4f964e7535d3eb91d03 Mon Sep 17 00:00:00 2001 From: Annie Date: Mon, 24 Oct 2022 12:42:12 -0600 Subject: [PATCH 08/29] fixed bug that didn't allow for planets to return --- app/routes.py | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/app/routes.py b/app/routes.py index b883a2674..8287e9017 100644 --- a/app/routes.py +++ b/app/routes.py @@ -7,12 +7,6 @@ def __init__(self, id, name, description, moons): self.description = description self.moons = moons - def to_json(self): - dict(id = self.id, - name = self.name, - description = self.description, - moons = self.moons - ) planets = [ Planet(1, "Mercury", "solid", 0), @@ -24,14 +18,22 @@ def to_json(self): @planets_bp.route("", methods=["GET"]) def planets_endpoint(): - response = [planet.to_json for planet in planets] + response = [dict(id = planet.id, + name = planet.name, + description = planet.description, + moons = planet.moons + ) for planet in planets] return jsonify(response) @planets_bp.route("/", methods=["GET"]) def planet_endpoint(planet_id): planet = validate_planet(planet_id) - return jsonify(planet.to_json) + return dict(id = planet.id, + name = planet.name, + description = planet.description, + moons = planet.moons + ) def validate_planet(planet_id): try: From c9edea6ff25ed63ba0114acb96ac3b76ec8d8d4b Mon Sep 17 00:00:00 2001 From: Annie Date: Mon, 24 Oct 2022 12:49:47 -0600 Subject: [PATCH 09/29] added to_json() method in Planet class and updated responses in endpoint to utilize method --- app/routes.py | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/app/routes.py b/app/routes.py index 8287e9017..439d653c1 100644 --- a/app/routes.py +++ b/app/routes.py @@ -7,6 +7,12 @@ def __init__(self, id, name, description, moons): self.description = description self.moons = moons + def to_json(self): + return dict(id = self.id, + name = self.name, + description = self.description, + moons = self.moons + ) planets = [ Planet(1, "Mercury", "solid", 0), @@ -18,22 +24,14 @@ def __init__(self, id, name, description, moons): @planets_bp.route("", methods=["GET"]) def planets_endpoint(): - response = [dict(id = planet.id, - name = planet.name, - description = planet.description, - moons = planet.moons - ) for planet in planets] + response = [planet.to_json() for planet in planets] return jsonify(response) @planets_bp.route("/", methods=["GET"]) def planet_endpoint(planet_id): planet = validate_planet(planet_id) - return dict(id = planet.id, - name = planet.name, - description = planet.description, - moons = planet.moons - ) + return jsonify(planet.to_json()) def validate_planet(planet_id): try: From cf97af15f210e2b825e3c49fe2c60786811f0dfc Mon Sep 17 00:00:00 2001 From: Anika Stephen Wilbur Date: Tue, 25 Oct 2022 14:04:44 -0700 Subject: [PATCH 10/29] Anika completes wave 02 --- app/routes.py | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/app/routes.py b/app/routes.py index 795070ec7..f7d18e2a9 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,4 +1,4 @@ -from flask import Blueprint, jsonify +from flask import Blueprint, jsonify, abort, make_response class Planet: def __init__(self, id, name, description, moons): @@ -28,4 +28,26 @@ def planets_endpoint(): moons = planet.moons ) ) - return jsonify(response) \ No newline at end of file + return jsonify(response) + +@planets_bp.route("/", methods=["GET"]) +def planet_endpoint(planet_id): + planet = validate_planet(planet_id) + return dict( + id = planet.id, + name = planet.name, + description = planet.description, + moons = planet.moons + ) + +def validate_planet(planet_id): + try: + planet_id = int(planet_id) + except: + abort(make_response({"message":f"planet {planet_id} invalid"}, 400)) + + for planet in planets: + if planet.id == planet_id: + return planet + + abort(make_response({"message":f"planet {planet_id} not found"}, 404)) \ No newline at end of file From 210f5443a9c41799ec0f93b825db03f71ccd57f6 Mon Sep 17 00:00:00 2001 From: Anika Stephen Wilbur Date: Fri, 28 Oct 2022 11:08:08 -0700 Subject: [PATCH 11/29] Creates planet model, updates app to link to db, creates POST endpoint, creates migrations directory --- app/__init__.py | 12 ++++ app/models/__init__.py | 0 app/models/planet.py | 15 +++++ app/routes.py | 72 ++++++++++----------- migrations/README | 1 + migrations/alembic.ini | 45 +++++++++++++ migrations/env.py | 96 ++++++++++++++++++++++++++++ migrations/script.py.mako | 24 +++++++ migrations/versions/33b260a3e13d_.py | 34 ++++++++++ 9 files changed, 261 insertions(+), 38 deletions(-) create mode 100644 app/models/__init__.py create mode 100644 app/models/planet.py create mode 100644 migrations/README create mode 100644 migrations/alembic.ini create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/33b260a3e13d_.py diff --git a/app/__init__.py b/app/__init__.py index ab9eee40e..464ab8588 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,10 +1,22 @@ from flask import Flask +from flask_sqlalchemy import SQLAlchemy +from flask_migrate import Migrate +db = SQLAlchemy() +migrate = Migrate() def create_app(test_config=None): app = Flask(__name__) + app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False + app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system' + + db.init_app(app) + migrate.init_app(app, db) + from .routes import planets_bp app.register_blueprint(planets_bp) + from app.models.planet import Planet + return app diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/app/models/planet.py b/app/models/planet.py new file mode 100644 index 000000000..912d1da71 --- /dev/null +++ b/app/models/planet.py @@ -0,0 +1,15 @@ +from app import db + +class Planet(db.Model): + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + name = db.Column(db.String, nullable=False) + description = db.Column(db.String, nullable=False) + moons = db.Column(db.Integer, nullable=False) + + def to_dict(self): + return dict( + id = self.id, + name = self.name, + description = self.description, + moons = self.moons + ) \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 032d24b8b..900b44efd 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,47 +1,43 @@ -from flask import Blueprint, jsonify, abort, make_response - -class Planet: - def __init__(self, id, name, description, moons): - self.id = id - self.name = name - self.description = description - self.moons = moons - - def to_json(self): - return dict(id = self.id, - name = self.name, - description = self.description, - moons = self.moons - ) - -planets = [ - Planet(1, "Mercury", "solid", 0), - Planet(2, "Venus", "bright and volcanic", 0), - Planet(3, "Earth", "half and half", 1) -] +from flask import Blueprint, jsonify, abort, make_response, request +from app import db +from app.models.planet import Planet + +# planets = [ +# Planet(1, "Mercury", "solid", 0), +# Planet(2, "Venus", "bright and volcanic", 0), +# Planet(3, "Earth", "half and half", 1) +# ] planets_bp = Blueprint("planets", __name__, url_prefix="/planets") -@planets_bp.route("", methods=["GET"]) -def planets_endpoint(): - response = [planet.to_json() for planet in planets] +@planets_bp.route("", methods=["POST"]) +def create_planet(): + request_body = request.get_json() + new_planet = Planet(name=request_body["name"], description=request_body["description"], moons=request_body["moons"]) + db.session.add(new_planet) + db.session.commit() + return make_response(f"Planet {new_planet.name} has been created successfully", 201) + +# @planets_bp.route("", methods=["GET"]) +# def planets_endpoint(): +# response = [planet.to_json() for planet in planets] - return jsonify(response) +# return jsonify(response) -@planets_bp.route("/", methods=["GET"]) -def planet_endpoint(planet_id): - planet = validate_planet(planet_id) +# @planets_bp.route("/", methods=["GET"]) +# def planet_endpoint(planet_id): +# planet = validate_planet(planet_id) - return jsonify(planet.to_json()) +# return jsonify(planet.to_json()) -def validate_planet(planet_id): - try: - planet_id = int(planet_id) - except: - abort(make_response({"message":f"planet {planet_id} invalid"}, 400)) +# def validate_planet(planet_id): +# try: +# planet_id = int(planet_id) +# except: +# abort(make_response({"message":f"planet {planet_id} invalid"}, 400)) - for planet in planets: - if planet.id == planet_id: - return planet +# for planet in planets: +# if planet.id == planet_id: +# return planet - abort(make_response({"message":f"planet {planet_id} not found"}, 404)) \ No newline at end of file +# abort(make_response({"message":f"planet {planet_id} not found"}, 404)) \ 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/33b260a3e13d_.py b/migrations/versions/33b260a3e13d_.py new file mode 100644 index 000000000..c167ec432 --- /dev/null +++ b/migrations/versions/33b260a3e13d_.py @@ -0,0 +1,34 @@ +"""empty message + +Revision ID: 33b260a3e13d +Revises: +Create Date: 2022-10-28 10:51:13.569118 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '33b260a3e13d' +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=False), + sa.Column('description', sa.String(), nullable=False), + sa.Column('moons', sa.Integer(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('planet') + # ### end Alembic commands ### From 91f71d31277d74621444a7794f6622d269115d0f Mon Sep 17 00:00:00 2001 From: Anika Stephen Wilbur Date: Fri, 28 Oct 2022 11:13:58 -0700 Subject: [PATCH 12/29] creates GET endpoint --- app/routes.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/app/routes.py b/app/routes.py index 900b44efd..a35c0f1b2 100644 --- a/app/routes.py +++ b/app/routes.py @@ -18,6 +18,12 @@ def create_planet(): db.session.commit() return make_response(f"Planet {new_planet.name} has been created successfully", 201) +@planets_bp.route("", methods=["GET"]) +def read_all_planets(): + planets = Planet.query.all() + planets_response = [planet.to_dict() for planet in planets] + return jsonify(planets_response) + # @planets_bp.route("", methods=["GET"]) # def planets_endpoint(): # response = [planet.to_json() for planet in planets] From a4ff6dcacb61fb1e8355f7adb7d8060e7a8fdb2a Mon Sep 17 00:00:00 2001 From: Anika Stephen Wilbur Date: Fri, 28 Oct 2022 11:22:42 -0700 Subject: [PATCH 13/29] Anika adds migrations to newly created solar_system_development db --- app/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index 464ab8588..8cb530f9b 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -9,7 +9,7 @@ def create_app(test_config=None): app = Flask(__name__) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False - app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system' + app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system_development' db.init_app(app) migrate.init_app(app, db) From 9a5239318557d66274ace52e8210965114bf5ade Mon Sep 17 00:00:00 2001 From: Annie Date: Fri, 28 Oct 2022 12:37:46 -0600 Subject: [PATCH 14/29] updated formatting to multiple lines for new_planet --- app/routes.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index a35c0f1b2..136a4ed03 100644 --- a/app/routes.py +++ b/app/routes.py @@ -13,7 +13,9 @@ @planets_bp.route("", methods=["POST"]) def create_planet(): request_body = request.get_json() - new_planet = Planet(name=request_body["name"], description=request_body["description"], moons=request_body["moons"]) + new_planet = Planet(name=request_body["name"], + description=request_body["description"], + moons=request_body["moons"]) db.session.add(new_planet) db.session.commit() return make_response(f"Planet {new_planet.name} has been created successfully", 201) From 8025e6882267a3e4ed99ce0bb56f3f3a8c9a0e1d Mon Sep 17 00:00:00 2001 From: Anika Stephen Wilbur Date: Tue, 1 Nov 2022 10:48:49 -0700 Subject: [PATCH 15/29] Adds PUT and DELETE methods --- app/routes.py | 51 +++++++++++++++++++++++++++++++++------------------ 1 file changed, 33 insertions(+), 18 deletions(-) diff --git a/app/routes.py b/app/routes.py index 136a4ed03..8ba56a5dd 100644 --- a/app/routes.py +++ b/app/routes.py @@ -26,26 +26,41 @@ def read_all_planets(): planets_response = [planet.to_dict() for planet in planets] return jsonify(planets_response) -# @planets_bp.route("", methods=["GET"]) -# def planets_endpoint(): -# response = [planet.to_json() for planet in planets] - -# return jsonify(response) +@planets_bp.route("/", methods=["GET"]) +def planet_endpoint(planet_id): + planet = validate_planet(planet_id) + + return jsonify(planet.to_dict()) -# @planets_bp.route("/", methods=["GET"]) -# def planet_endpoint(planet_id): -# planet = validate_planet(planet_id) +@planets_bp.route("/", methods=["PUT"]) +def planet_update(planet_id): + planet = validate_planet(planet_id) + request_body = request.get_json() + planet.name = request_body["name"] + planet.description = request_body["description"] + planet.moons = request_body["moons"] + + db.session.commit() + return make_response(f"Planet {planet.name} has been updated successfully", 200) -# return jsonify(planet.to_json()) +@planets_bp.route("/", methods=["DELETE"]) +def planet_delete(planet_id): + planet = validate_planet(planet_id) -# def validate_planet(planet_id): -# try: -# planet_id = int(planet_id) -# except: -# abort(make_response({"message":f"planet {planet_id} invalid"}, 400)) + db.session.delete(planet) + db.session.commit() + + return make_response(f"Planet {planet.name} has been deleted successfully", 200) + +def validate_planet(planet_id): + try: + planet_id = int(planet_id) + except: + abort(make_response({"message":f"planet {planet_id} invalid"}, 400)) + + planet = Planet.query.get(planet_id) -# for planet in planets: -# if planet.id == planet_id: -# return planet + if not planet: + abort(make_response({"message":f"planet {planet_id} not found"}, 404)) -# abort(make_response({"message":f"planet {planet_id} not found"}, 404)) \ No newline at end of file + return planet \ No newline at end of file From 062d52339d9910c6d6da7b414e8baddd461ec640 Mon Sep 17 00:00:00 2001 From: Annie Date: Thu, 3 Nov 2022 12:21:56 -0600 Subject: [PATCH 16/29] added query params to GET all planets endpoint --- app/routes.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index 8ba56a5dd..b95fce76d 100644 --- a/app/routes.py +++ b/app/routes.py @@ -22,7 +22,20 @@ def create_planet(): @planets_bp.route("", methods=["GET"]) def read_all_planets(): - planets = Planet.query.all() + name_query = request.args.get("name") + moons_query = request.args.get("moons") + description_query = request.args.get("description") + + planet_query = Planet.query + if name_query: + planet_query = Planet.query.filter_by(name=name_query) + if moons_query: + planet_query = Planet.query.filter_by(moons=moons_query) + if description_query: + planet_query = Planet.query.filter_by(description=description_query) + + planets = planet_query.all() + planets_response = [planet.to_dict() for planet in planets] return jsonify(planets_response) From 2ce92d1fb27d11069dbc8e7076afed90cee35243 Mon Sep 17 00:00:00 2001 From: Anika Stephen Wilbur Date: Thu, 3 Nov 2022 11:22:38 -0700 Subject: [PATCH 17/29] Adds query params to routes.py --- app/routes.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index 8ba56a5dd..924bc56c4 100644 --- a/app/routes.py +++ b/app/routes.py @@ -22,8 +22,22 @@ def create_planet(): @planets_bp.route("", methods=["GET"]) def read_all_planets(): - planets = Planet.query.all() + name_query = request.args.get("name") + moons_query = request.args.get("moons") + description_query = request.args.get("description") + planet_query = Planet.query + if name_query: + planet_query = Planet.query.filter_by(name=name_query) + if moons_query: + planet_query = Planet.query.filter_by(moons=moons_query) + if description_query: + planet_query = Planet.query.filter_by(description=description_query) + + + + planets = planet_query.all() planets_response = [planet.to_dict() for planet in planets] + return jsonify(planets_response) @planets_bp.route("/", methods=["GET"]) From 948d8ba1a19c0feea1ef0bc60425581b12c895bc Mon Sep 17 00:00:00 2001 From: Anika Stephen Wilbur Date: Thu, 3 Nov 2022 13:51:01 -0700 Subject: [PATCH 18/29] Adds test configuration flag --- app/__init__.py | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 8cb530f9b..d86c6f0cd 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,16 +1,26 @@ from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate +from dotenv import load_dotenv +import os db = SQLAlchemy() migrate = Migrate() +load_dotenv() def create_app(test_config=None): app = Flask(__name__) - app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False - app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system_development' - + if not test_config: + app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get( + "SQLALCHEMY_DATABASE_URI") + else: + app.config["TESTING"] = True + app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False + app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( + "SQLALCHEMY_TEST_DATABASE_URI") + db.init_app(app) migrate.init_app(app, db) From f0fa591fcaa580db9235d46703a4efaed6ad5037 Mon Sep 17 00:00:00 2001 From: Anika Stephen Wilbur Date: Thu, 3 Nov 2022 13:53:27 -0700 Subject: [PATCH 19/29] Adds test directory and three test files --- tests/__init__.py | 0 tests/conftest.py | 40 ++++++++++++++++++++++++++++++++++++++++ tests/test_routes.py | 0 3 files changed, 40 insertions(+) create mode 100644 tests/__init__.py create mode 100644 tests/conftest.py create mode 100644 tests/test_routes.py diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 000000000..f55ea08ba --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,40 @@ +import pytest +from app import create_app +from app import db +from flask.signals import request_finished +from app.models.book import Book + +@pytest.fixture +def app(): + app = create_app({"TESTING": True}) + + @request_finished.connect_via(app) + def expire_session(sender, response, **extra): + db.session.remove() + + with app.app_context(): + db.create_all() + yield app + + with app.app_context(): + db.drop_all() + + +@pytest.fixture +def client(app): + return app.test_client() + + +@pytest.fixture +def two_saved_books(app): + # Arrange + ocean_book = Book(title="Ocean Book", + description="watr 4evr") + mountain_book = Book(title="Mountain Book", + description="i luv 2 climb rocks") + + db.session.add_all([ocean_book, mountain_book]) + # Alternatively, we could do + # db.session.add(ocean_book) + # db.session.add(mountain_book) + db.session.commit() \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py new file mode 100644 index 000000000..e69de29bb From b903ac95cc7f3999eafbfb099c4f7159ea01434f Mon Sep 17 00:00:00 2001 From: Anika Stephen Wilbur Date: Thu, 3 Nov 2022 13:57:41 -0700 Subject: [PATCH 20/29] Updates conftest.py to remove unneeded test and add one test to test_routes.py --- tests/conftest.py | 19 ++----------------- tests/test_routes.py | 10 ++++++++++ 2 files changed, 12 insertions(+), 17 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index f55ea08ba..8c851f0a1 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -2,7 +2,7 @@ from app import create_app from app import db from flask.signals import request_finished -from app.models.book import Book +from app.models.planet import Planet @pytest.fixture def app(): @@ -22,19 +22,4 @@ def expire_session(sender, response, **extra): @pytest.fixture def client(app): - return app.test_client() - - -@pytest.fixture -def two_saved_books(app): - # Arrange - ocean_book = Book(title="Ocean Book", - description="watr 4evr") - mountain_book = Book(title="Mountain Book", - description="i luv 2 climb rocks") - - db.session.add_all([ocean_book, mountain_book]) - # Alternatively, we could do - # db.session.add(ocean_book) - # db.session.add(mountain_book) - db.session.commit() \ No newline at end of file + return app.test_client() \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py index e69de29bb..9026091c9 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -0,0 +1,10 @@ +import pytest + +def test_get_all_planets_with_no_records(client): + # Act + response = client.get("/planets") + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert response_body == [] \ No newline at end of file From 2647fe149ce3def426f51efa98f2a86fc33e3c54 Mon Sep 17 00:00:00 2001 From: Annie Date: Thu, 3 Nov 2022 15:05:39 -0600 Subject: [PATCH 21/29] added new fixture to populate 2 planets for testing --- tests/conftest.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/tests/conftest.py b/tests/conftest.py index 8c851f0a1..afa40af65 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -22,4 +22,18 @@ def expire_session(sender, response, **extra): @pytest.fixture def client(app): - return app.test_client() \ No newline at end of file + return app.test_client() + +# planets = [ +# Planet(1, "Mercury", "solid", 0), +# Planet(2, "Venus", "bright and volcanic", 0), +# Planet(3, "Earth", "half and half", 1) +# ] + +@pytest.fixture +def two_saved_planets(app): + mercury = Planet(name="Mercury", description="solid", moons=0) + venus = Planet(name="Venus", description="bright and volcanic", moons=0) + + db.session.add_all([mercury, venus]) + db.session.commit() \ No newline at end of file From 9e344e44ab65f90d9e6ecf717b73836794cde894 Mon Sep 17 00:00:00 2001 From: Annie Date: Thu, 3 Nov 2022 15:06:17 -0600 Subject: [PATCH 22/29] wrote test to get a planet --- tests/test_routes.py | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/tests/test_routes.py b/tests/test_routes.py index 9026091c9..aa2122d07 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -7,4 +7,25 @@ def test_get_all_planets_with_no_records(client): # Assert assert response.status_code == 200 - assert response_body == [] \ No newline at end of file + assert response_body == [] + +## Writing Tests + +# Create test fixtures and unit tests for the following test cases: + +# 1. `GET` `/planets/1` returns a response body that matches our fixture +def test_get_one_planet(client, two_saved_planets): + response = client.get("/planets/1") + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == { + "id": 1, + "name":"Mercury", + "description":"solid", + "moons":0 + } + +# 1. `GET` `/planets/1` with no data in test database (no fixture) returns a `404` +# 1. `GET` `/planets` with valid test data (fixtures) returns a `200` with an array including appropriate test data +# 1. `POST` `/planets` with a JSON request body returns a `201` \ No newline at end of file From 53aa8dc1cf5702029ae4ecda05fe913456efa67f Mon Sep 17 00:00:00 2001 From: Annie Date: Thu, 3 Nov 2022 15:15:13 -0600 Subject: [PATCH 23/29] added jsonify to allow tests to run correctly --- app/routes.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/app/routes.py b/app/routes.py index 6404ae475..8a9b431db 100644 --- a/app/routes.py +++ b/app/routes.py @@ -18,7 +18,7 @@ def create_planet(): moons=request_body["moons"]) db.session.add(new_planet) db.session.commit() - return make_response(f"Planet {new_planet.name} has been created successfully", 201) + return make_response(jsonify(f"Planet {new_planet.name} has been created successfully"), 201) @planets_bp.route("", methods=["GET"]) def read_all_planets(): @@ -54,7 +54,7 @@ def planet_update(planet_id): planet.moons = request_body["moons"] db.session.commit() - return make_response(f"Planet {planet.name} has been updated successfully", 200) + return make_response(jsonify(f"Planet {planet.name} has been updated successfully"), 200) @planets_bp.route("/", methods=["DELETE"]) def planet_delete(planet_id): @@ -63,17 +63,17 @@ def planet_delete(planet_id): db.session.delete(planet) db.session.commit() - return make_response(f"Planet {planet.name} has been deleted successfully", 200) + return make_response(jsonify(f"Planet {planet.name} has been deleted successfully"), 200) def validate_planet(planet_id): try: planet_id = int(planet_id) except: - abort(make_response({"message":f"planet {planet_id} invalid"}, 400)) + abort(make_response(jsonify({"message":f"planet {planet_id} invalid"}), 400)) planet = Planet.query.get(planet_id) if not planet: - abort(make_response({"message":f"planet {planet_id} not found"}, 404)) + abort(make_response(jsonify({"message":f"planet {planet_id} not found"}), 404)) return planet \ No newline at end of file From 07ad213eb82a8f70fd422369ffb8071680563add Mon Sep 17 00:00:00 2001 From: Annie Date: Thu, 3 Nov 2022 15:16:08 -0600 Subject: [PATCH 24/29] added tests to get planet with no data, get multiple planets, and post a new planet --- tests/test_routes.py | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/tests/test_routes.py b/tests/test_routes.py index aa2122d07..7061613e4 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -27,5 +27,40 @@ def test_get_one_planet(client, two_saved_planets): } # 1. `GET` `/planets/1` with no data in test database (no fixture) returns a `404` +def test_get_one_planet_no_data(client): + response = client.get("/planets/1") + response_body = response.get_json() + + assert response.status_code == 404 + assert response_body == {'message': 'planet 1 not found'} + # 1. `GET` `/planets` with valid test data (fixtures) returns a `200` with an array including appropriate test data -# 1. `POST` `/planets` with a JSON request body returns a `201` \ No newline at end of file +def test_get_planets(client, two_saved_planets): + response = client.get("/planets/1") + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == { + "id": 1, + "name":"Mercury", + "description":"solid", + "moons":0 + } + { + "id": 2, + "name":"Venus", + "description":"bright and volcanic", + "moons":0 + } + +# 1. `POST` `/planets` with a JSON request body returns a `201` +def test_create_one_planet(client): + response = client.post("/planets", json={ + "name": "Earth", + "description": "half and half", + "moons": 1 + }) + response_body = response.get_json() + + assert response.status_code == 201 + assert response_body == "Planet Earth has been created successfully" \ No newline at end of file From df19563f0960ba6b894e0ec8a0a34b33de8ccd38 Mon Sep 17 00:00:00 2001 From: Annie Date: Thu, 3 Nov 2022 15:16:45 -0600 Subject: [PATCH 25/29] removed unnecessary comments --- tests/test_routes.py | 8 -------- 1 file changed, 8 deletions(-) diff --git a/tests/test_routes.py b/tests/test_routes.py index 7061613e4..1e484b363 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -9,11 +9,6 @@ def test_get_all_planets_with_no_records(client): assert response.status_code == 200 assert response_body == [] -## Writing Tests - -# Create test fixtures and unit tests for the following test cases: - -# 1. `GET` `/planets/1` returns a response body that matches our fixture def test_get_one_planet(client, two_saved_planets): response = client.get("/planets/1") response_body = response.get_json() @@ -26,7 +21,6 @@ def test_get_one_planet(client, two_saved_planets): "moons":0 } -# 1. `GET` `/planets/1` with no data in test database (no fixture) returns a `404` def test_get_one_planet_no_data(client): response = client.get("/planets/1") response_body = response.get_json() @@ -34,7 +28,6 @@ def test_get_one_planet_no_data(client): assert response.status_code == 404 assert response_body == {'message': 'planet 1 not found'} -# 1. `GET` `/planets` with valid test data (fixtures) returns a `200` with an array including appropriate test data def test_get_planets(client, two_saved_planets): response = client.get("/planets/1") response_body = response.get_json() @@ -53,7 +46,6 @@ def test_get_planets(client, two_saved_planets): "moons":0 } -# 1. `POST` `/planets` with a JSON request body returns a `201` def test_create_one_planet(client): response = client.post("/planets", json={ "name": "Earth", From eef413f7685ecad83a60e0849477ded873d1ce42 Mon Sep 17 00:00:00 2001 From: Annie Date: Thu, 3 Nov 2022 15:28:37 -0600 Subject: [PATCH 26/29] updated validate_planet function to be broader for any model validation --- app/models/planet.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/app/models/planet.py b/app/models/planet.py index 912d1da71..a703aff65 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -6,6 +6,13 @@ class Planet(db.Model): description = db.Column(db.String, nullable=False) moons = db.Column(db.Integer, nullable=False) + @classmethod + def from_dict(cls, planet_data): + new_planet = cls(name=planet_data["name"], + description=planet_data["description"], + moons=planet_data["moons"]) + return new_planet + def to_dict(self): return dict( id = self.id, From 7b8a16bb0d86615eeb27fc4e1afc2da4f49effe6 Mon Sep 17 00:00:00 2001 From: Annie Date: Thu, 3 Nov 2022 15:28:57 -0600 Subject: [PATCH 27/29] updated validate_planet function to be broader for any model validation --- app/routes.py | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/app/routes.py b/app/routes.py index 8a9b431db..dc2615f99 100644 --- a/app/routes.py +++ b/app/routes.py @@ -13,9 +13,7 @@ @planets_bp.route("", methods=["POST"]) def create_planet(): request_body = request.get_json() - new_planet = Planet(name=request_body["name"], - description=request_body["description"], - moons=request_body["moons"]) + new_planet = Planet.from_dict(request_body) db.session.add(new_planet) db.session.commit() return make_response(jsonify(f"Planet {new_planet.name} has been created successfully"), 201) @@ -41,13 +39,13 @@ def read_all_planets(): @planets_bp.route("/", methods=["GET"]) def planet_endpoint(planet_id): - planet = validate_planet(planet_id) + planet = validate_model(Planet, planet_id) return jsonify(planet.to_dict()) @planets_bp.route("/", methods=["PUT"]) def planet_update(planet_id): - planet = validate_planet(planet_id) + planet = validate_model(Planet, planet_id) request_body = request.get_json() planet.name = request_body["name"] planet.description = request_body["description"] @@ -58,22 +56,22 @@ def planet_update(planet_id): @planets_bp.route("/", methods=["DELETE"]) def planet_delete(planet_id): - planet = validate_planet(planet_id) + planet = validate_model(Planet, planet_id) db.session.delete(planet) db.session.commit() return make_response(jsonify(f"Planet {planet.name} has been deleted successfully"), 200) -def validate_planet(planet_id): +def validate_model(cls, model_id): try: - planet_id = int(planet_id) + model_id = int(model_id) except: - abort(make_response(jsonify({"message":f"planet {planet_id} invalid"}), 400)) + abort(make_response(jsonify({"message":f"{cls.__name__} {model_id} invalid"}), 400)) - planet = Planet.query.get(planet_id) + model = cls.query.get(model_id) - if not planet: - abort(make_response(jsonify({"message":f"planet {planet_id} not found"}), 404)) + if not model: + abort(make_response(jsonify({"message":f"{cls.__name__} {model_id} not found"}), 404)) - return planet \ No newline at end of file + return model \ No newline at end of file From eb4ee10199d3baa02f2f987d451c75f09eb1954b Mon Sep 17 00:00:00 2001 From: Annie Date: Thu, 3 Nov 2022 15:29:39 -0600 Subject: [PATCH 28/29] fixed bug that was causing test to fail when we changed validate_model --- 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 1e484b363..2c990ea3b 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -26,7 +26,7 @@ def test_get_one_planet_no_data(client): response_body = response.get_json() assert response.status_code == 404 - assert response_body == {'message': 'planet 1 not found'} + assert response_body == {'message': 'Planet 1 not found'} def test_get_planets(client, two_saved_planets): response = client.get("/planets/1") From 00b5452a2dac2e5e14e76b682952dc9848c1756c Mon Sep 17 00:00:00 2001 From: Annie Date: Sun, 6 Nov 2022 12:05:17 -0700 Subject: [PATCH 29/29] added is_complete as a boolean to Task class --- app/routes.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/routes.py b/app/routes.py index dc2615f99..8417e48e3 100644 --- a/app/routes.py +++ b/app/routes.py @@ -25,11 +25,11 @@ def read_all_planets(): description_query = request.args.get("description") planet_query = Planet.query if name_query: - planet_query = Planet.query.filter_by(name=name_query) + planet_query = planet_query.filter_by(name=name_query) if moons_query: - planet_query = Planet.query.filter_by(moons=moons_query) + planet_query = planet_query.filter_by(moons=moons_query) if description_query: - planet_query = Planet.query.filter_by(description=description_query) + planet_query = planet_query.filter_by(description=description_query) planets = planet_query.all()