From 149f21ced6f4fb73cb0bdb5e52bf75b7af94bf4e Mon Sep 17 00:00:00 2001 From: Danica Date: Fri, 21 Apr 2023 11:42:49 -0700 Subject: [PATCH 01/12] Wave 1 commit --- app/routes.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..c0852d18c 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,17 @@ from flask import Blueprint +class Planet: + def __init__(self, id, name, description, color): + self.id = id + self.name = name + self.description = description + self.color = color + +planets = [ + Planet(1, "Earth", "habitable", "blue & green"), + Planet(2, "Venus", "hot", "yellowy orange"), + Planet(3, "Saturn", "beautiful ringlets", "light yellow"), + Planet(4, "Neptune", "furthest from the sun", "blue") +] + +planets_bp = Blueprint("planets", __name__, url_prefix="/planets") \ No newline at end of file From f6edf5fc166df49c5a63b02a975461c99bc231a7 Mon Sep 17 00:00:00 2001 From: Danica Date: Mon, 24 Apr 2023 15:12:57 -0700 Subject: [PATCH 02/12] Wave 1 & Wave 2 commits --- app/__init__.py | 5 ++++- app/routes.py | 44 ++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..dabc106ee 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -3,5 +3,8 @@ def create_app(test_config=None): app = Flask(__name__) + + from .routes import planets_bp + app.register_blueprint(planets_bp) - return app + return app \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index c0852d18c..55a4c5b3f 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,4 +1,4 @@ -from flask import Blueprint +from flask import Blueprint, jsonify, abort, make_response class Planet: def __init__(self, id, name, description, color): @@ -14,4 +14,44 @@ def __init__(self, id, name, description, color): Planet(4, "Neptune", "furthest from the sun", "blue") ] -planets_bp = Blueprint("planets", __name__, url_prefix="/planets") \ No newline at end of file +planets_bp = Blueprint("planets", __name__, url_prefix="/planets") + + +def validate_planet(planet_id): + try: + planet_id = int(planet_id) + except: + abort(make_response({"message":f"planet {planet_id} invalid"}, 400)) + + for planet in planets: + if planet.id == planet_id: + return planet + + abort(make_response({"message":f"planet {planet_id} not found"}, 404)) + + +# Endpoint to get all planets +@planets_bp.route("", methods=["GET"]) +def handle_planets(): + planets_response = [] + for planet in planets: + planets_response.append({ + "id": planet.id, + "name": planet.name, + "description": planet.description, + "color": planet.color + }) + return jsonify(planets_response), 200 + +# Endpoint to get a planet +@planets_bp.route("/", methods=["GET"]) +def handle_planet(planet_id): + planet = validate_planet(planet_id) + + return { + "id": planet.id, + "name": planet.name, + "description": planet.description, + "color": planet.color, + } + From 27268df61346e700d6437a3d353da7cbe0bafdea Mon Sep 17 00:00:00 2001 From: Danica Date: Fri, 28 Apr 2023 11:23:39 -0700 Subject: [PATCH 03/12] working on wave 3 --- app/models/planet.py | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 app/models/planet.py diff --git a/app/models/planet.py b/app/models/planet.py new file mode 100644 index 000000000..eb796ba2e --- /dev/null +++ b/app/models/planet.py @@ -0,0 +1,7 @@ +from app import db + +class Planet(db.Model): + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + name = db.Column(db.String) + description = db.Column(db.String) + color = db.Column(db.String) \ No newline at end of file From efd399ffe0aa7db6cea18f68fff5bbba388212b0 Mon Sep 17 00:00:00 2001 From: Danica Date: Fri, 28 Apr 2023 11:37:52 -0700 Subject: [PATCH 04/12] debugged flask db init in wave 3 --- app/__init__.py | 14 ++++++ app/routes.py | 99 ++++++++++++++++++++------------------- migrations/README | 1 + migrations/alembic.ini | 45 ++++++++++++++++++ migrations/env.py | 96 +++++++++++++++++++++++++++++++++++++ migrations/script.py.mako | 24 ++++++++++ 6 files changed, 230 insertions(+), 49 deletions(-) create mode 100644 migrations/README create mode 100644 migrations/alembic.ini create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako diff --git a/app/__init__.py b/app/__init__.py index dabc106ee..eccb2e109 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,10 +1,24 @@ from flask import Flask +from flask_sqlalchemy import SQLAlchemy +from flask_migrate import Migrate + +db = SQLAlchemy() +migrate = Migrate() def create_app(test_config=None): app = Flask(__name__) + app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False + app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system_development' + + db.init_app(app) + migrate.init_app(app, db) + + from .routes import planets_bp app.register_blueprint(planets_bp) + # from app.models.planet import Planet + return app \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 55a4c5b3f..f2f4a6c98 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,57 +1,58 @@ from flask import Blueprint, jsonify, abort, make_response - -class Planet: - def __init__(self, id, name, description, color): - self.id = id - self.name = name - self.description = description - self.color = color - -planets = [ - Planet(1, "Earth", "habitable", "blue & green"), - Planet(2, "Venus", "hot", "yellowy orange"), - Planet(3, "Saturn", "beautiful ringlets", "light yellow"), - Planet(4, "Neptune", "furthest from the sun", "blue") -] +from app.models.planet import Planet + +# class Planet: +# def __init__(self, id, name, description, color): +# self.id = id +# self.name = name +# self.description = description +# self.color = color + +# planets = [ +# Planet(1, "Earth", "habitable", "blue & green"), +# Planet(2, "Venus", "hot", "yellowy orange"), +# Planet(3, "Saturn", "beautiful ringlets", "light yellow"), +# Planet(4, "Neptune", "furthest from the sun", "blue") +# ] planets_bp = Blueprint("planets", __name__, url_prefix="/planets") -def validate_planet(planet_id): - try: - planet_id = int(planet_id) - except: - abort(make_response({"message":f"planet {planet_id} invalid"}, 400)) +# 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)) - - -# Endpoint to get all planets -@planets_bp.route("", methods=["GET"]) -def handle_planets(): - planets_response = [] - for planet in planets: - planets_response.append({ - "id": planet.id, - "name": planet.name, - "description": planet.description, - "color": planet.color - }) - return jsonify(planets_response), 200 - -# Endpoint to get a planet -@planets_bp.route("/", methods=["GET"]) -def handle_planet(planet_id): - planet = validate_planet(planet_id) - - return { - "id": planet.id, - "name": planet.name, - "description": planet.description, - "color": planet.color, - } +# abort(make_response({"message":f"planet {planet_id} not found"}, 404)) + + +# # Endpoint to get all planets +# @planets_bp.route("", methods=["GET"]) +# def handle_planets(): +# planets_response = [] +# for planet in planets: +# planets_response.append({ +# "id": planet.id, +# "name": planet.name, +# "description": planet.description, +# "color": planet.color +# }) +# return jsonify(planets_response), 200 + +# # Endpoint to get a planet +# @planets_bp.route("/", methods=["GET"]) +# def handle_planet(planet_id): +# planet = validate_planet(planet_id) + +# return { +# "id": planet.id, +# "name": planet.name, +# "description": planet.description, +# "color": planet.color, +# } diff --git a/migrations/README b/migrations/README new file mode 100644 index 000000000..98e4f9c44 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 000000000..f8ed4801f --- /dev/null +++ b/migrations/alembic.ini @@ -0,0 +1,45 @@ +# A generic, single database configuration. + +[alembic] +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 000000000..8b3fb3353 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,96 @@ +from __future__ import with_statement + +import logging +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool +from flask import current_app + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) +logger = logging.getLogger('alembic.env') + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +config.set_main_option( + 'sqlalchemy.url', + str(current_app.extensions['migrate'].db.engine.url).replace('%', '%%')) +target_metadata = current_app.extensions['migrate'].db.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, target_metadata=target_metadata, literal_binds=True + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + # this callback is used to prevent an auto-migration from being generated + # when there are no changes to the schema + # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html + def process_revision_directives(context, revision, directives): + if getattr(config.cmd_opts, 'autogenerate', False): + script = directives[0] + if script.upgrade_ops.is_empty(): + directives[:] = [] + logger.info('No changes in schema detected.') + + connectable = engine_from_config( + config.get_section(config.config_ini_section), + prefix='sqlalchemy.', + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=target_metadata, + process_revision_directives=process_revision_directives, + **current_app.extensions['migrate'].configure_args + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 000000000..2c0156303 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,24 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} From 3f43d48827ccebd5d10833b529e163133e24dac7 Mon Sep 17 00:00:00 2001 From: Danica Date: Mon, 1 May 2023 12:47:18 -0700 Subject: [PATCH 05/12] wave 3 --- app/routes.py | 26 +++++++++++++- .../a24052900216_adds_planet_model.py | 34 +++++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 migrations/versions/a24052900216_adds_planet_model.py diff --git a/app/routes.py b/app/routes.py index f2f4a6c98..43ff98fd4 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,4 +1,5 @@ -from flask import Blueprint, jsonify, abort, make_response +from app import db +from flask import Blueprint, jsonify, abort, make_response, request from app.models.planet import Planet # class Planet: @@ -17,7 +18,30 @@ planets_bp = Blueprint("planets", __name__, url_prefix="/planets") +@planets_bp.route("", methods=["GET", "POST"]) +def handle_planets(): + if request.method == "GET": + planets = Planet.query.all() + planets_response = [] + for planet in planets: + planets_response.append({ + "id": planet.id, + "name": planet.name, + "description": planet.description, + "color": planet.color + }) + return jsonify(planets_response) + elif request.method == "POST": + request_body = request.get_json() + new_planet = Planet(name=request_body["name"], + description=request_body["description"], + color=request_body["color"]) + + + db.session.add(new_planet) + db.session.commit() + return make_response(f"Planet {new_planet.name} successfully created.", 201) # def validate_planet(planet_id): # try: # planet_id = int(planet_id) diff --git a/migrations/versions/a24052900216_adds_planet_model.py b/migrations/versions/a24052900216_adds_planet_model.py new file mode 100644 index 000000000..369061609 --- /dev/null +++ b/migrations/versions/a24052900216_adds_planet_model.py @@ -0,0 +1,34 @@ +"""adds Planet model + +Revision ID: a24052900216 +Revises: +Create Date: 2023-05-01 12:26:00.266000 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'a24052900216' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('planet', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('name', sa.String(), nullable=True), + sa.Column('description', sa.String(), nullable=True), + sa.Column('color', sa.String(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('planet') + # ### end Alembic commands ### From 173fb9d9b47094bf3372560b6d8e7e305ca9e6f8 Mon Sep 17 00:00:00 2001 From: Carline Date: Mon, 1 May 2023 14:34:10 -0700 Subject: [PATCH 06/12] models/init was never on git --- app/models/__init__.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 app/models/__init__.py diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 000000000..e69de29bb From 1489bf65504d892def7cdafc49371fe3ab06c45c Mon Sep 17 00:00:00 2001 From: Danica Date: Tue, 2 May 2023 10:45:41 -0700 Subject: [PATCH 07/12] checks wave 3 commits --- 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 eb796ba2e..8b6df41f0 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -4,4 +4,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) - color = db.Column(db.String) \ No newline at end of file + color = db.Column(db.String) + From 7f9f35d4c08258d130e28c68668d50d30dde1b78 Mon Sep 17 00:00:00 2001 From: Danica Date: Tue, 2 May 2023 11:40:17 -0700 Subject: [PATCH 08/12] reads, creates, deletes one endpoint (wave 4) --- app/routes.py | 64 ++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 58 insertions(+), 6 deletions(-) diff --git a/app/routes.py b/app/routes.py index 43ff98fd4..8ad777ec6 100644 --- a/app/routes.py +++ b/app/routes.py @@ -17,6 +17,58 @@ # ] planets_bp = Blueprint("planets", __name__, url_prefix="/planets") +#VALIDATE PLANET HELPER FN +def validate_planet(planet_id): + try: + planet_id = int(planet_id) + except: + abort(make_response({"message":f"planet {planet_id} invalid"}, 400)) + + planet = Planet.query.get(planet_id) + + if not planet: + abort(make_response({"message":f"planet {planet_id} not found"}, 404)) + + return planet + +# GET ONE ENDPOINT +@planets_bp.route("/", methods=["GET"]) +def handle_planet(planet_id): + # planet = Planet.query.get(planet_id) + planet = validate_planet(planet_id) + + return { + "id": planet.id, + "name": planet.name, + "description": planet.description, + "color": planet.color + }, 200 + +# UPDATE ONE ENDPOINT +@planets_bp.route("/", methods=["PUT"]) +def update_planet(planet_id): + planet = validate_planet(planet_id) + + request_body = request.get_json() + + planet.name = request_body["name"] + planet.description = request_body["description"] + planet.color = request_body["color"] + + db.session.commit() + + return make_response(f"Planet {planet.id} successfully updated!"), 200 + +# DELETE ONE ENDPOINT +@planets_bp.route("/", methods=["DELETE"]) +def delete_planet(planet_id): + planet = validate_planet(planet_id) + + db.session.delete(planet) + db.session.commit() + + return make_response(f"Planet {planet.id} successfully deleted!"), 200 + @planets_bp.route("", methods=["GET", "POST"]) def handle_planets(): @@ -37,23 +89,23 @@ def handle_planets(): description=request_body["description"], color=request_body["color"]) - db.session.add(new_planet) db.session.commit() return make_response(f"Planet {new_planet.name} successfully created.", 201) + # 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)) +# planet = Planet.query.get(planet_id) +# if not planet: +# abort(make_response({"message":f"planet {planet_id} not found"}, 404)) + +# return planet # # Endpoint to get all planets # @planets_bp.route("", methods=["GET"]) From 8780703f52808691df90e98b7da49ceae777c82f Mon Sep 17 00:00:00 2001 From: Danica Date: Wed, 3 May 2023 12:04:02 -0700 Subject: [PATCH 09/12] updates the create_app() function on wave 6 --- app/__init__.py | 18 +++++++++++++++--- requirements.txt | 4 ++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index eccb2e109..d170b8cfc 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,6 +1,9 @@ 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() @@ -9,16 +12,25 @@ 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 app.models.planet import Planet + from .routes import planets_bp app.register_blueprint(planets_bp) - # from app.models.planet import Planet return app \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index ae59e7b55..5f31c67bc 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,14 +4,18 @@ blinker==1.4 certifi==2020.12.5 chardet==4.0.0 click==7.1.2 +coverage==7.2.3 Flask==1.1.2 Flask-Migrate==2.6.0 Flask-SQLAlchemy==2.4.4 idna==2.10 +iniconfig==2.0.0 itsdangerous==1.1.0 Jinja2==2.11.3 Mako==1.1.4 MarkupSafe==1.1.1 +packaging==23.1 +pluggy==1.0.0 psycopg2-binary==2.9.5 pycodestyle==2.6.0 pytest==7.3.1 From 66686c0c2230612d7f29143eff04de9db42aba8e Mon Sep 17 00:00:00 2001 From: Danica Date: Wed, 3 May 2023 17:34:52 -0700 Subject: [PATCH 10/12] creates tests for wave 6 --- app/__init__.py | 1 + app/routes.py | 6 ++-- tests/__init__.py | 0 tests/conftest.py | 39 ++++++++++++++++++++++++ tests/test_routes.py | 71 ++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 114 insertions(+), 3 deletions(-) create mode 100644 tests/__init__.py create mode 100644 tests/conftest.py create mode 100644 tests/test_routes.py diff --git a/app/__init__.py b/app/__init__.py index d170b8cfc..f71864e55 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -7,6 +7,7 @@ db = SQLAlchemy() migrate = Migrate() +load_dotenv() def create_app(test_config=None): diff --git a/app/routes.py b/app/routes.py index 8ad777ec6..8da68e970 100644 --- a/app/routes.py +++ b/app/routes.py @@ -18,7 +18,7 @@ planets_bp = Blueprint("planets", __name__, url_prefix="/planets") #VALIDATE PLANET HELPER FN -def validate_planet(planet_id): +def validate_planet(planet_id): # ONLY TO GET & PUT ONE PLANET_ID try: planet_id = int(planet_id) except: @@ -28,7 +28,7 @@ def validate_planet(planet_id): if not planet: abort(make_response({"message":f"planet {planet_id} not found"}, 404)) - + #potentially thinking of making a loop to go through each PLANET in planetS return planet # GET ONE ENDPOINT @@ -70,7 +70,7 @@ def delete_planet(planet_id): return make_response(f"Planet {planet.id} successfully deleted!"), 200 -@planets_bp.route("", methods=["GET", "POST"]) +@planets_bp.route("", methods=["GET", "POST"]) # Refactor & split into 2 methods # Validation for POST dictionary def handle_planets(): if request.method == "GET": planets = Planet.query.all() 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..2a9a53b36 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,39 @@ +import pytest +from app import create_app +from app import db +from flask.signals import request_finished +from app.models.planet import Planet + + +@pytest.fixture +def app(): + app = create_app({"TESTING": True}) + + @request_finished.connect_via(app) + def expire_session(sender, response, **extra): + db.session.remove() + + with app.app_context(): + db.create_all() + yield app + + with app.app_context(): + db.drop_all() + + +@pytest.fixture +def client(app): + return app.test_client() + +@pytest.fixture +def two_saved_planets(app): +#Arrange + venus_planet = Planet(id=1,name="Venus",description="hot enough to melt lead n ur heart Date: Thu, 4 May 2023 12:30:07 -0700 Subject: [PATCH 11/12] refactors the routes.py file and creates to_dict() function --- app/models/planet.py | 8 +++++ app/routes.py | 61 +++++++++++++++++++------------------ tests/conftest.py | 1 - tests/test_models.py | 71 ++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 109 insertions(+), 32 deletions(-) create mode 100644 tests/test_models.py diff --git a/app/models/planet.py b/app/models/planet.py index 8b6df41f0..f31b805aa 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -6,3 +6,11 @@ class Planet(db.Model): description = db.Column(db.String) color = db.Column(db.String) + def to_dict(self): + planet_as_dict = {} + planet_as_dict["id"] = self.id + planet_as_dict["name"] = self.name + planet_as_dict["description"] = self.description + planet_as_dict["color"] = self.color + + return planet_as_dict \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 8da68e970..0449b459b 100644 --- a/app/routes.py +++ b/app/routes.py @@ -31,18 +31,6 @@ def validate_planet(planet_id): # ONLY TO GET & PUT ONE PLANET_ID #potentially thinking of making a loop to go through each PLANET in planetS return planet -# GET ONE ENDPOINT -@planets_bp.route("/", methods=["GET"]) -def handle_planet(planet_id): - # planet = Planet.query.get(planet_id) - planet = validate_planet(planet_id) - - return { - "id": planet.id, - "name": planet.name, - "description": planet.description, - "color": planet.color - }, 200 # UPDATE ONE ENDPOINT @planets_bp.route("/", methods=["PUT"]) @@ -69,30 +57,41 @@ def delete_planet(planet_id): return make_response(f"Planet {planet.id} successfully deleted!"), 200 - -@planets_bp.route("", methods=["GET", "POST"]) # Refactor & split into 2 methods # Validation for POST dictionary -def handle_planets(): - if request.method == "GET": - planets = Planet.query.all() +# Reads all planets +@planets_bp.route("", methods=["GET"]) +def read_all_planets(): + + name_query = request.args.get("name") + if name_query: + planets = Planet.query.filter_by(name=name_query) + else: + planets = Planet.query.all() + + planets_response = [] for planet in planets: - planets_response.append({ - "id": planet.id, - "name": planet.name, - "description": planet.description, - "color": planet.color - }) + planets_response.append(planet.to_dict()) return jsonify(planets_response) - elif request.method == "POST": - request_body = request.get_json() - new_planet = Planet(name=request_body["name"], - description=request_body["description"], - color=request_body["color"]) + +# GET ONE PLANET +@planets_bp.route("/", methods=["GET"]) +def read_one_planet(planet_id): + planet = validate_planet(planet_id) + return planet.to_dict(), 200 + + +@planets_bp.route("", methods=["POST"]) # Validation for POST dictionary +def create_planet(): + request_body = request.get_json() + new_planet = Planet(name=request_body["name"], + description=request_body["description"], + color=request_body["color"]) + - db.session.add(new_planet) - db.session.commit() + db.session.add(new_planet) + db.session.commit() - return make_response(f"Planet {new_planet.name} successfully created.", 201) + return make_response(f"Planet {new_planet.name} successfully created.", 201) # def validate_planet(planet_id): # try: diff --git a/tests/conftest.py b/tests/conftest.py index 2a9a53b36..fbf245b0a 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -36,4 +36,3 @@ def two_saved_planets(app): db.session.add(venus_planet) db.session.add(saturn_planet) db.session.commit() - diff --git a/tests/test_models.py b/tests/test_models.py new file mode 100644 index 000000000..a142759b7 --- /dev/null +++ b/tests/test_models.py @@ -0,0 +1,71 @@ +from app.models.planet import Planet + + +def test_to_dict_no_missing_data(): + # Arrange + + test_data = Planet(id = 1, + name = "Venus", + description = "hot enough to melt lead n ur heart Date: Thu, 4 May 2023 16:14:21 -0700 Subject: [PATCH 12/12] refactors all code and passes all implemented tests --- app/__init__.py | 2 - app/models/planet.py | 14 ++++++- app/routes.py | 95 ++++++++++---------------------------------- tests/conftest.py | 3 +- tests/test_models.py | 46 ++++++++++++++++++++- tests/test_routes.py | 92 ++++++++++++++++++++++++++++++++++-------- 6 files changed, 155 insertions(+), 97 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index f71864e55..88376ee8a 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -29,9 +29,7 @@ def create_app(test_config=None): from app.models.planet import Planet - from .routes import planets_bp app.register_blueprint(planets_bp) - return app \ No newline at end of file diff --git a/app/models/planet.py b/app/models/planet.py index f31b805aa..e8b44f588 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -1,3 +1,4 @@ + from app import db class Planet(db.Model): @@ -6,6 +7,7 @@ class Planet(db.Model): description = db.Column(db.String) color = db.Column(db.String) +#Helper fns converting and pulling dicts def to_dict(self): planet_as_dict = {} planet_as_dict["id"] = self.id @@ -13,4 +15,14 @@ def to_dict(self): planet_as_dict["description"] = self.description planet_as_dict["color"] = self.color - return planet_as_dict \ No newline at end of file + return planet_as_dict + + @classmethod + def from_dict(cls, planet_data): + new_planet = Planet(name=planet_data["name"], + description=planet_data["description"], + color=planet_data["color"] + ) + return new_planet + + \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 0449b459b..fc1a4cd72 100644 --- a/app/routes.py +++ b/app/routes.py @@ -2,40 +2,27 @@ from flask import Blueprint, jsonify, abort, make_response, request from app.models.planet import Planet -# class Planet: -# def __init__(self, id, name, description, color): -# self.id = id -# self.name = name -# self.description = description -# self.color = color - -# planets = [ -# Planet(1, "Earth", "habitable", "blue & green"), -# Planet(2, "Venus", "hot", "yellowy orange"), -# Planet(3, "Saturn", "beautiful ringlets", "light yellow"), -# Planet(4, "Neptune", "furthest from the sun", "blue") -# ] - planets_bp = Blueprint("planets", __name__, url_prefix="/planets") -#VALIDATE PLANET HELPER FN -def validate_planet(planet_id): # ONLY TO GET & PUT ONE PLANET_ID + +# HELPER FUNCTION +def validate_model(cls, model_id): try: - planet_id = int(planet_id) + model_id = int(model_id) except: - abort(make_response({"message":f"planet {planet_id} invalid"}, 400)) + abort(make_response({"message":f"{cls.__name__} {model_id} invalid"}, 400)) - planet = Planet.query.get(planet_id) + model = cls.query.get(model_id) + + if not model: + abort(make_response({"message":f"{cls.__name__} {model_id} not found"}, 404)) - if not planet: - abort(make_response({"message":f"planet {planet_id} not found"}, 404)) - #potentially thinking of making a loop to go through each PLANET in planetS - return planet + return model -# UPDATE ONE ENDPOINT +# UPDATES ONE ENDPOINT @planets_bp.route("/", methods=["PUT"]) def update_planet(planet_id): - planet = validate_planet(planet_id) + planet = validate_model(Planet, planet_id) request_body = request.get_json() @@ -47,17 +34,17 @@ def update_planet(planet_id): return make_response(f"Planet {planet.id} successfully updated!"), 200 -# DELETE ONE ENDPOINT +# DELETES ONE ENDPOINT @planets_bp.route("/", methods=["DELETE"]) def delete_planet(planet_id): - planet = validate_planet(planet_id) + planet = validate_model(Planet, planet_id) db.session.delete(planet) db.session.commit() return make_response(f"Planet {planet.id} successfully deleted!"), 200 -# Reads all planets +# READS ALL PLANETS @planets_bp.route("", methods=["GET"]) def read_all_planets(): @@ -73,61 +60,21 @@ def read_all_planets(): planets_response.append(planet.to_dict()) return jsonify(planets_response) -# GET ONE PLANET +# GETS ONE PLANET @planets_bp.route("/", methods=["GET"]) def read_one_planet(planet_id): - planet = validate_planet(planet_id) + planet = validate_model(Planet, planet_id) return planet.to_dict(), 200 - -@planets_bp.route("", methods=["POST"]) # Validation for POST dictionary +# CREATES ONE PLANET +@planets_bp.route("", methods=["POST"]) def create_planet(): request_body = request.get_json() - new_planet = Planet(name=request_body["name"], - description=request_body["description"], - color=request_body["color"]) + new_planet = Planet.from_dict(request_body) db.session.add(new_planet) db.session.commit() return make_response(f"Planet {new_planet.name} successfully created.", 201) - -# def validate_planet(planet_id): -# try: -# planet_id = int(planet_id) -# except: -# abort(make_response({"message":f"planet {planet_id} invalid"}, 400)) - -# planet = Planet.query.get(planet_id) - -# if not planet: -# abort(make_response({"message":f"planet {planet_id} not found"}, 404)) - -# return planet - -# # Endpoint to get all planets -# @planets_bp.route("", methods=["GET"]) -# def handle_planets(): -# planets_response = [] -# for planet in planets: -# planets_response.append({ -# "id": planet.id, -# "name": planet.name, -# "description": planet.description, -# "color": planet.color -# }) -# return jsonify(planets_response), 200 - -# # Endpoint to get a planet -# @planets_bp.route("/", methods=["GET"]) -# def handle_planet(planet_id): -# planet = validate_planet(planet_id) - -# return { -# "id": planet.id, -# "name": planet.name, -# "description": planet.description, -# "color": planet.color, -# } - + \ No newline at end of file diff --git a/tests/conftest.py b/tests/conftest.py index fbf245b0a..771dd9e78 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -27,9 +27,8 @@ def client(app): @pytest.fixture def two_saved_planets(app): -#Arrange + venus_planet = Planet(id=1,name="Venus",description="hot enough to melt lead n ur heart