From 72951d3532ac1861b4698de4c0036ceed3205c02 Mon Sep 17 00:00:00 2001 From: Sel Date: Thu, 20 Apr 2023 12:03:44 -0700 Subject: [PATCH 01/15] Wave_1 completed --- app/__init__.py | 4 ++++ app/routes.py | 23 ++++++++++++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..de4b869bb 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -4,4 +4,8 @@ def create_app(test_config=None): app = Flask(__name__) + from flask import Blueprint + from .routes import planets_bp + app.register_blueprint(planets_bp) + return app diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..8c205fa1d 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,23 @@ -from flask import Blueprint +from flask import Blueprint, jsonify +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","Only planet with liquid water", "blue"), + Planet(2,"Jupiter","Twice as massive tha the other planets combined","pink"), + Planet(3,"Mars","Is where aliens live","orange") + ] + +planets_bp = Blueprint("planets", __name__, url_prefix="/planets") + +@planets_bp.route("",methods=["GET"]) +def list_planets(): + planets_response = [vars(planet) for planet in planets] + + return jsonify(planets_response), 200 + \ No newline at end of file From 1f744232bfddd5af46a35ca6a4741ed792edcef1 Mon Sep 17 00:00:00 2001 From: Sel Date: Fri, 21 Apr 2023 11:41:49 -0700 Subject: [PATCH 02/15] Look for single_planet function --- app/routes.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/app/routes.py b/app/routes.py index 8c205fa1d..e84a636a6 100644 --- a/app/routes.py +++ b/app/routes.py @@ -20,4 +20,16 @@ def list_planets(): planets_response = [vars(planet) for planet in planets] return jsonify(planets_response), 200 + +@planets_bp.route("/", methods=["GET"]) +def single_planet(planet_id): + planet_id = int(planet_id) + for planet in planets: + if planet.id == planet_id: + return { + "id":planet.id, + "name":planet.name, + "description":planet.description, + "color":planet.color + } \ No newline at end of file From d58ab81e25fdabd9c80338c12bfe607a6ec189a5 Mon Sep 17 00:00:00 2001 From: Sel Date: Fri, 21 Apr 2023 11:51:09 -0700 Subject: [PATCH 03/15] Implemented of wave_02: read one book and errors --- app/routes.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index e84a636a6..212a68f99 100644 --- a/app/routes.py +++ b/app/routes.py @@ -23,7 +23,10 @@ def list_planets(): @planets_bp.route("/", methods=["GET"]) def single_planet(planet_id): - planet_id = int(planet_id) + try: + planet_id = int(planet_id) + except: return { "message":f"planet {planet_id} invalid"}, 400 + for planet in planets: if planet.id == planet_id: return { @@ -32,4 +35,6 @@ def single_planet(planet_id): "description":planet.description, "color":planet.color } + + return { "message":f"planet {planet_id} not found"}, 404 \ No newline at end of file From 5bb6883a45ad75fd807210b94f80cf6bd8231efc Mon Sep 17 00:00:00 2001 From: Sel Date: Fri, 21 Apr 2023 12:12:01 -0700 Subject: [PATCH 04/15] Libraries make_response and abort added to wave_02 --- app/routes.py | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/app/routes.py b/app/routes.py index 212a68f99..3fd68dcd2 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, color): @@ -15,6 +15,22 @@ def __init__(self, id, name, description, color): planets_bp = Blueprint("planets", __name__, url_prefix="/planets") +def validate_planet(planet_id): + #handle invalid planet_id, return 400 + try: + planet_id = int(planet_id) + except: + abort(make_response({ "message":f"planet {planet_id} invalid"}, 400)) + + #search for planet_in in data, return planet + for planet in planets: + if planet.id == planet_id: + return planet + + #return a 404 for non-existing planet + abort(make_response({"message":f"planet {planet_id} not found"}, 404)) + + @planets_bp.route("",methods=["GET"]) def list_planets(): planets_response = [vars(planet) for planet in planets] @@ -23,18 +39,12 @@ def list_planets(): @planets_bp.route("/", methods=["GET"]) def single_planet(planet_id): - try: - planet_id = int(planet_id) - except: return { "message":f"planet {planet_id} invalid"}, 400 - - for planet in planets: - if planet.id == planet_id: - return { + planet = validate_planet(planet_id) + + return { "id":planet.id, "name":planet.name, "description":planet.description, "color":planet.color } - - return { "message":f"planet {planet_id} not found"}, 404 \ No newline at end of file From 7445f1906127e8f24cec7cdaf3557e3807d66c3c Mon Sep 17 00:00:00 2001 From: Sel Date: Thu, 27 Apr 2023 15:00:10 -0700 Subject: [PATCH 05/15] Wave_03 added, create planet and read all planets --- app/__init__.py | 12 +++ app/models/planet.py | 7 ++ app/routes.py | 86 ++++++++++------- migrations/README | 1 + migrations/alembic.ini | 45 +++++++++ migrations/env.py | 96 +++++++++++++++++++ migrations/script.py.mako | 24 +++++ .../5d0608e7a702_model_planet_added.py | 33 +++++++ ...25f9866148_add_atribute_to_planet_color.py | 28 ++++++ 9 files changed, 298 insertions(+), 34 deletions(-) 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/5d0608e7a702_model_planet_added.py create mode 100644 migrations/versions/f925f9866148_add_atribute_to_planet_color.py diff --git a/app/__init__.py b/app/__init__.py index de4b869bb..2f3fa5b84 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,9 +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_development' + + from app.models.planet import Planet + + db.init_app(app) + migrate.init_app(app, db) + from flask import Blueprint from .routes import planets_bp app.register_blueprint(planets_bp) 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 diff --git a/app/routes.py b/app/routes.py index 3fd68dcd2..32c152c08 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,50 +1,68 @@ -from flask import Blueprint, jsonify, abort, make_response +from flask import Blueprint, jsonify, abort, make_response, request +from app import db +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","Only planet with liquid water", "blue"), - Planet(2,"Jupiter","Twice as massive tha the other planets combined","pink"), - Planet(3,"Mars","Is where aliens live","orange") - ] +# 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","Only planet with liquid water", "blue"), +# Planet(2,"Jupiter","Twice as massive tha the other planets combined","pink"), +# Planet(3,"Mars","Is where aliens live","orange") +# ] planets_bp = Blueprint("planets", __name__, url_prefix="/planets") -def validate_planet(planet_id): - #handle invalid planet_id, return 400 - try: - planet_id = int(planet_id) - except: - abort(make_response({ "message":f"planet {planet_id} invalid"}, 400)) +# def validate_planet(planet_id): +# #handle invalid planet_id, return 400 +# try: +# planet_id = int(planet_id) +# except: +# abort(make_response({ "message":f"planet {planet_id} invalid"}, 400)) - #search for planet_in in data, return planet - for planet in planets: - if planet.id == planet_id: - return planet +# #search for planet_in in data, return planet +# for planet in planets: +# if planet.id == planet_id: +# return planet - #return a 404 for non-existing planet - abort(make_response({"message":f"planet {planet_id} not found"}, 404)) +# #return a 404 for non-existing planet +# abort(make_response({"message":f"planet {planet_id} not found"}, 404)) + +@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"]) + db.session.add(new_planet) + db.session.commit() + + return make_response(f"Planet {new_planet.name} successfully created", 201) + @planets_bp.route("",methods=["GET"]) -def list_planets(): +def read_all_planets(): + + planets = Planet.query.all() + planets_response = [vars(planet) for planet in planets] return jsonify(planets_response), 200 -@planets_bp.route("/", methods=["GET"]) -def single_planet(planet_id): - planet = validate_planet(planet_id) +# @planets_bp.route("/", methods=["GET"]) +# def single_planet(planet_id): +# planet = validate_planet(planet_id) - return { - "id":planet.id, - "name":planet.name, - "description":planet.description, - "color":planet.color - } +# return { +# "id":planet.id, +# "name":planet.name, +# "description":planet.description, +# "color":planet.color +# } \ 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/5d0608e7a702_model_planet_added.py b/migrations/versions/5d0608e7a702_model_planet_added.py new file mode 100644 index 000000000..b5f2b8bdd --- /dev/null +++ b/migrations/versions/5d0608e7a702_model_planet_added.py @@ -0,0 +1,33 @@ +"""Model planet added + +Revision ID: 5d0608e7a702 +Revises: +Create Date: 2023-04-27 14:06:51.826748 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '5d0608e7a702' +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.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('planet') + # ### end Alembic commands ### diff --git a/migrations/versions/f925f9866148_add_atribute_to_planet_color.py b/migrations/versions/f925f9866148_add_atribute_to_planet_color.py new file mode 100644 index 000000000..650e8f61e --- /dev/null +++ b/migrations/versions/f925f9866148_add_atribute_to_planet_color.py @@ -0,0 +1,28 @@ +"""Add atribute to planet color + +Revision ID: f925f9866148 +Revises: 5d0608e7a702 +Create Date: 2023-04-27 14:48:28.481212 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'f925f9866148' +down_revision = '5d0608e7a702' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('planet', sa.Column('color', sa.String(), nullable=True)) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_column('planet', 'color') + # ### end Alembic commands ### From 6943176ce57dab68f7529d739fe8f80508a6c315 Mon Sep 17 00:00:00 2001 From: Sel Date: Mon, 1 May 2023 14:29:52 -0700 Subject: [PATCH 06/15] Read, update and delete one planet --- app/routes.py | 96 +++++++++++++++++++++++++++++++-------------------- 1 file changed, 58 insertions(+), 38 deletions(-) diff --git a/app/routes.py b/app/routes.py index 32c152c08..52abf2b0c 100644 --- a/app/routes.py +++ b/app/routes.py @@ -3,35 +3,23 @@ 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","Only planet with liquid water", "blue"), -# Planet(2,"Jupiter","Twice as massive tha the other planets combined","pink"), -# Planet(3,"Mars","Is where aliens live","orange") -# ] - planets_bp = Blueprint("planets", __name__, url_prefix="/planets") -# def validate_planet(planet_id): -# #handle invalid planet_id, return 400 -# try: -# planet_id = int(planet_id) -# except: -# abort(make_response({ "message":f"planet {planet_id} invalid"}, 400)) +def validate_planet(planet_id): + #handle invalid planet_id, return 400 + 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)) -# #search for planet_in in data, return planet -# for planet in planets: -# if planet.id == planet_id: -# return planet + #search for planet_in in data, return planet + return planet -# #return a 404 for non-existing planet -# abort(make_response({"message":f"planet {planet_id} not found"}, 404)) @planets_bp.route("", methods=["POST"]) def create_planet(): @@ -46,23 +34,55 @@ def create_planet(): return make_response(f"Planet {new_planet.name} successfully created", 201) -@planets_bp.route("",methods=["GET"]) +@planets_bp.route("", methods=["GET"]) def read_all_planets(): + planets_response = [] planets = Planet.query.all() - planets_response = [vars(planet) for planet in planets] + for planet in planets: + planets_response.append({ + "id": planet.id, + "title": planet.name, + "description": planet.description, + "color": planet.color + }) return jsonify(planets_response), 200 -# @planets_bp.route("/", methods=["GET"]) -# def single_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 + +@planets_bp.route("/", methods=["GET"]) +def single_planet(planet_id): + planet = validate_planet(planet_id) + + return { + "id": planet.id, + "name": planet.name, + "description": planet.description, + "color": planet.color + } + +@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(jsonify(f"Planet #{planet.id} successfully updated")) + + +@planets_bp.route("/", methods=["DELETE"]) +def delete_planet(planet_id): + planet = validate_planet(planet_id) + + db.session.delete(planet) + db.session.commit() + + return make_response(f"Planet #{planet.id} successfully deleted") + From 1897af495092e6a448527fa6a548cd6152a9a36b Mon Sep 17 00:00:00 2001 From: Sel Date: Tue, 2 May 2023 11:55:04 -0700 Subject: [PATCH 07/15] Query params added, filter by color --- app/routes.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/app/routes.py b/app/routes.py index 52abf2b0c..eec209a78 100644 --- a/app/routes.py +++ b/app/routes.py @@ -36,14 +36,18 @@ def create_planet(): @planets_bp.route("", methods=["GET"]) def read_all_planets(): - planets_response = [] - - planets = Planet.query.all() + color_query = request.args.get("color") + + if color_query: + planets = Planet.query.filter_by(color=color_query) + else: + planets = Planet.query.all() + planets_response = [] for planet in planets: planets_response.append({ "id": planet.id, - "title": planet.name, + "name": planet.name, "description": planet.description, "color": planet.color }) From 5e6a80fc189f097ac16f02dc157c39d3dfac2828 Mon Sep 17 00:00:00 2001 From: Sel Date: Tue, 2 May 2023 12:13:47 -0700 Subject: [PATCH 08/15] Creating .env and testing configuration --- app/__init__.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 2f3fa5b84..6a913ed3b 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,15 +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") + from app.models.planet import Planet From 15336bce8038f9f632c70a872e4c0d52f70001bf Mon Sep 17 00:00:00 2001 From: Sel Date: Wed, 3 May 2023 14:15:12 -0700 Subject: [PATCH 09/15] Tests added: get one planet, get all planets and post planet --- app/routes.py | 2 +- tests/__init__.py | 0 tests/conftest.py | 45 ++++++++++++++++++++++++++++++++++++++++ tests/test_routes.py | 49 ++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 95 insertions(+), 1 deletion(-) create mode 100644 tests/__init__.py create mode 100644 tests/conftest.py create mode 100644 tests/test_routes.py diff --git a/app/routes.py b/app/routes.py index eec209a78..60f1c76f8 100644 --- a/app/routes.py +++ b/app/routes.py @@ -31,7 +31,7 @@ def create_planet(): db.session.add(new_planet) db.session.commit() - return make_response(f"Planet {new_planet.name} successfully created", 201) + return make_response(jsonify(f"Planet {new_planet.name} successfully created"), 201) @planets_bp.route("", methods=["GET"]) 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..bf2b5cc7e --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,45 @@ +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 + mars = Planet( + name="Mars", + description="where aliens live", + color="red") + jupiter = Planet( + name="Jupiter", + description="really big", + color="orange") + + db.session.add_all([mars, jupiter]) + db. session.commit() + diff --git a/tests/test_routes.py b/tests/test_routes.py new file mode 100644 index 000000000..138f771ea --- /dev/null +++ b/tests/test_routes.py @@ -0,0 +1,49 @@ +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":"Mars", + "description":"where aliens live", + "color":"red" + } + +def test_get_one_planet_empty_db_returns_404(client): + response = client.get("/planets/1") + + assert response.status_code == 404 + +def test_get_all_planets(client, two_saved_planets): + # Act + response = client.get("/planets") + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert response_body == [{ + "id":1, + "name":"Mars", + "description":"where aliens live", + "color":"red"}, + {"id":2, + "name":"Jupiter", + "description":"really big", + "color":"orange"}] + +def test_create_one_planet(client): + # Act + response = client.post("/planets", json={ + "name":"Pluto", + "description":"very small", + "color":"grey" + }) + response_body = response.get_json() + + + # Assert + assert response.status_code == 201 + assert response_body == "Planet Pluto successfully created" \ No newline at end of file From ce0e58e81a09ba3b16e4e35e22f4ceffcfcdeca7 Mon Sep 17 00:00:00 2001 From: Jennifer Tam Date: Fri, 5 May 2023 15:04:50 -0700 Subject: [PATCH 10/15] refactored - added model tests --- app/models/planet.py | 17 +++++- app/routes.py | 42 ++++++--------- tests/test_models.py | 120 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 151 insertions(+), 28 deletions(-) create mode 100644 tests/test_models.py diff --git a/app/models/planet.py b/app/models/planet.py index eb796ba2e..ee3951c90 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -4,4 +4,19 @@ 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) + + 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 + + @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 60f1c76f8..cfcf1ebd7 100644 --- a/app/routes.py +++ b/app/routes.py @@ -5,28 +5,26 @@ planets_bp = Blueprint("planets", __name__, url_prefix="/planets") -def validate_planet(planet_id): - #handle invalid planet_id, return 400 +def validate_model(cls, model_id): + #handle invalid model_id, return 400 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 planet: - abort(make_response({"message":f"planet {planet_id} not found"}, 404)) + if not model: + abort(make_response({"message":f"{cls.__name__} {model_id} not found"}, 404)) - #search for planet_in in data, return planet - return planet + #search for model_in in data, return planet + return model @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() @@ -45,30 +43,20 @@ def read_all_planets(): 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), 200 @planets_bp.route("/", methods=["GET"]) def single_planet(planet_id): - planet = validate_planet(planet_id) + planet = validate_model(Planet, planet_id) - return { - "id": planet.id, - "name": planet.name, - "description": planet.description, - "color": planet.color - } + return planet.to_dict() @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() @@ -83,7 +71,7 @@ def update_planet(planet_id): @planets_bp.route("/", methods=["DELETE"]) def delete_planet(planet_id): - planet = validate_planet(planet_id) + planet = validate_model(Planet, planet_id) db.session.delete(planet) db.session.commit() diff --git a/tests/test_models.py b/tests/test_models.py new file mode 100644 index 000000000..8690f045f --- /dev/null +++ b/tests/test_models.py @@ -0,0 +1,120 @@ +from app.models.planet import Planet +import pytest + +def test_to_dict_no_missing_data(): + # Arrange + test_data = Planet(id = 1, + name="Mars", + description="where aliens live", + color="red") + + # Act + result = test_data.to_dict() + + # Assert + assert len(result) == 4 + assert result["id"] == 1 + assert result["name"] == "Mars" + assert result["description"] == "where aliens live" + assert result["color"] == "red" + +def test_to_dict_missing_id(): + # Arrange + test_data = Planet(name="Mars", + description="where aliens live", + color="red") + + # Act + result = test_data.to_dict() + + # Assert + assert len(result) == 4 + assert result["id"] is None + assert result["name"] == "Mars" + assert result["description"] == "where aliens live" + assert result["color"] == "red" + +def test_to_dict_missing_name(): + # Arrange + test_data = Planet(id=1, + description="where aliens live", + color="red") + + # Act + result = test_data.to_dict() + + # Assert + assert len(result) == 4 + assert result["id"] == 1 + assert result["name"] is None + assert result["description"] == "where aliens live" + +def test_to_dict_missing_description(): + # Arrange + test_data = Planet(id = 1, + name="Mars", + color="red") + + # Act + result = test_data.to_dict() + + # Assert + assert len(result) == 4 + assert result["id"] == 1 + assert result["name"] == "Mars" + assert result["description"] is None + assert result["color"] == "red" + +def test_from_dict_returns_planet(): + # Arrange + planet_data = { + "name": "New Planet", + "description": "The Best Planet!", + "color": "pink" + } + + # Act + new_planet = Planet.from_dict(planet_data) + + # Assert + assert new_planet.name == "New Planet" + assert new_planet.description == "The Best Planet!" + assert new_planet.color == "pink" + +def test_from_dict_with_no_name(): + # Arrange + planet_data = { + "description": "The Best Planet!", + "color": "pink" + } + + # Act & Assert + with pytest.raises(KeyError, match = 'name'): + new_planet = Planet.from_dict(planet_data) + +def test_from_dict_with_no_description(): + # Arrange + planet_data = { + "name": "New planet", + "color": "pink" + } + + # Act & Assert + with pytest.raises(KeyError, match = 'description'): + new_planet = Planet.from_dict(planet_data) + +def test_from_dict_with_extra_keys(): + # Arrange + planet_data = { + "extra": "some stuff", + "name": "New Planet", + "description": "The Best Planet!", + "another": "last value" + } + + # Act + new_planet = Planet.from_dict(planet_data) + + # Assert + assert new_planet.name == "New Planet" + assert new_planet.description == "The Best Planet!" \ No newline at end of file From 2eac8e861070ad20c2550177a83e483f9c86adff Mon Sep 17 00:00:00 2001 From: Jennifer Tam Date: Fri, 5 May 2023 15:26:48 -0700 Subject: [PATCH 11/15] fixed keyError --- tests/test_models.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/test_models.py b/tests/test_models.py index 8690f045f..03d79f84d 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -109,6 +109,7 @@ def test_from_dict_with_extra_keys(): "extra": "some stuff", "name": "New Planet", "description": "The Best Planet!", + "color": "pink", "another": "last value" } @@ -117,4 +118,4 @@ def test_from_dict_with_extra_keys(): # Assert assert new_planet.name == "New Planet" - assert new_planet.description == "The Best Planet!" \ No newline at end of file + assert new_planet.description == "The Best Planet!" From fa6b0acec190e24155d8838a8aacdbe37c852183 Mon Sep 17 00:00:00 2001 From: Sel Date: Tue, 9 May 2023 11:36:28 -0700 Subject: [PATCH 12/15] Adding db --- app/__init__.py | 4 ++-- requirements.txt | 7 +++++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 6a913ed3b..49eedd669 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -13,8 +13,8 @@ def create_app(test_config=None): if not test_config: app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False - app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get( - "SQLALCHEMY_DATABASE_URI") + app.config['RENDER_DATABASE_URI'] = os.environ.get( + "RENDER_DATABASE_URI") else: app.config['TESTING'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False diff --git a/requirements.txt b/requirements.txt index ae59e7b55..f4ff77124 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,14 +4,20 @@ blinker==1.4 certifi==2020.12.5 chardet==4.0.0 click==7.1.2 +coverage==7.2.3 +exceptiongroup==1.1.1 Flask==1.1.2 Flask-Migrate==2.6.0 Flask-SQLAlchemy==2.4.4 +gunicorn==20.1.0 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 @@ -23,5 +29,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 4b2116d1a3701aee5f201c12e17fb4bf717a3ee5 Mon Sep 17 00:00:00 2001 From: Jennifer Tam Date: Tue, 9 May 2023 11:37:35 -0700 Subject: [PATCH 13/15] render database uri --- app/__init__.py | 10 ++++++---- app/routes.py | 3 +-- requirements.txt | 7 +++++++ 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 6a913ed3b..4a25ee5ac 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -11,15 +11,17 @@ def create_app(test_config=None): app = Flask(__name__) +# RENDER_DATABASE_URI + if not test_config: app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False - app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get( - "SQLALCHEMY_DATABASE_URI") + app.config['RENDER_DATABASE_URI'] = os.environ.get("RENDER_DATABASE_URI") + # 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") + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("SQLALCHEMY_TEST_DATABASE_URI") from app.models.planet import Planet diff --git a/app/routes.py b/app/routes.py index cfcf1ebd7..7ccd49db3 100644 --- a/app/routes.py +++ b/app/routes.py @@ -76,5 +76,4 @@ def delete_planet(planet_id): db.session.delete(planet) db.session.commit() - return make_response(f"Planet #{planet.id} successfully deleted") - + return make_response(f"Planet #{planet.id} successfully deleted") \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index ae59e7b55..f4ff77124 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,14 +4,20 @@ blinker==1.4 certifi==2020.12.5 chardet==4.0.0 click==7.1.2 +coverage==7.2.3 +exceptiongroup==1.1.1 Flask==1.1.2 Flask-Migrate==2.6.0 Flask-SQLAlchemy==2.4.4 +gunicorn==20.1.0 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 @@ -23,5 +29,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 f15a25d7a11c4071a5416a540e493364d3723149 Mon Sep 17 00:00:00 2001 From: Sel Date: Tue, 9 May 2023 17:12:25 -0700 Subject: [PATCH 14/15] Create again migrations --- ...model_planet_added.py => f0a0fe8b2e9b_.py} | 9 +++--- ...25f9866148_add_atribute_to_planet_color.py | 28 ------------------- 2 files changed, 5 insertions(+), 32 deletions(-) rename migrations/versions/{5d0608e7a702_model_planet_added.py => f0a0fe8b2e9b_.py} (80%) delete mode 100644 migrations/versions/f925f9866148_add_atribute_to_planet_color.py diff --git a/migrations/versions/5d0608e7a702_model_planet_added.py b/migrations/versions/f0a0fe8b2e9b_.py similarity index 80% rename from migrations/versions/5d0608e7a702_model_planet_added.py rename to migrations/versions/f0a0fe8b2e9b_.py index b5f2b8bdd..a4dcf8c9a 100644 --- a/migrations/versions/5d0608e7a702_model_planet_added.py +++ b/migrations/versions/f0a0fe8b2e9b_.py @@ -1,8 +1,8 @@ -"""Model planet added +"""empty message -Revision ID: 5d0608e7a702 +Revision ID: f0a0fe8b2e9b Revises: -Create Date: 2023-04-27 14:06:51.826748 +Create Date: 2023-05-09 17:10:51.530155 """ from alembic import op @@ -10,7 +10,7 @@ # revision identifiers, used by Alembic. -revision = '5d0608e7a702' +revision = 'f0a0fe8b2e9b' down_revision = None branch_labels = None depends_on = None @@ -22,6 +22,7 @@ def upgrade(): 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 ### diff --git a/migrations/versions/f925f9866148_add_atribute_to_planet_color.py b/migrations/versions/f925f9866148_add_atribute_to_planet_color.py deleted file mode 100644 index 650e8f61e..000000000 --- a/migrations/versions/f925f9866148_add_atribute_to_planet_color.py +++ /dev/null @@ -1,28 +0,0 @@ -"""Add atribute to planet color - -Revision ID: f925f9866148 -Revises: 5d0608e7a702 -Create Date: 2023-04-27 14:48:28.481212 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = 'f925f9866148' -down_revision = '5d0608e7a702' -branch_labels = None -depends_on = None - - -def upgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.add_column('planet', sa.Column('color', sa.String(), nullable=True)) - # ### end Alembic commands ### - - -def downgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.drop_column('planet', 'color') - # ### end Alembic commands ### From 30a812bc1f27d72c6b13a667e1cf04bab7d6cd17 Mon Sep 17 00:00:00 2001 From: Sel Date: Tue, 9 May 2023 19:33:13 -0700 Subject: [PATCH 15/15] Change the render uri --- app/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index bc66e1144..51772f00a 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -17,7 +17,7 @@ def create_app(test_config=None): app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("SQLALCHEMY_DATABASE_URI") - app.config['RENDER_DATABASE_URI'] = os.environ.get("RENDER_DATABASE_URI") + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("RENDER_DATABASE_URI") else: app.config['TESTING'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False