From db1722547dbe8a3884edc4b62a5d3a17d870b921 Mon Sep 17 00:00:00 2001 From: Cristal Date: Fri, 21 Oct 2022 11:31:06 -0700 Subject: [PATCH 01/16] wave one complete --- app/__init__.py | 5 +++++ app/routes.py | 28 +++++++++++++++++++++++++++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..a1ade2bc2 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -4,4 +4,9 @@ def create_app(test_config=None): app = Flask(__name__) + from .routes import planet_bp + app.register_blueprint(planet_bp) + return app + + \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..3fad96cd0 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,28 @@ -from flask import Blueprint +from flask import Blueprint, jsonify +class Planet: + def __init__(self, id, name, description, flag): + self.id = id + self.name = name + self.description = description + self.flag = flag + +planets = [ +Planet(0, "jupiter", "largest planet in solar system", False), +Planet(1, "mercury", "smallest planet in solar system", False), +Planet(2, "mars", "most explored planet in solar system", True) +] + +planet_bp = Blueprint("planets", __name__, url_prefix="/planets") + +@planet_bp.route("", methods=["GET"]) +def list_planets(): + planet_list = [] + for planet in planets: + planet_list.append(dict( + id = planet.id, + name = planet.name, + description = planet.description, + flag = planet.flag + )) + return jsonify(planet_list) \ No newline at end of file From 4f70d960cb28f9509ad1fd17c4b89d3abd4bf169 Mon Sep 17 00:00:00 2001 From: francescafr Date: Mon, 24 Oct 2022 11:52:02 -0700 Subject: [PATCH 02/16] completed wave 2 --- app/routes.py | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/app/routes.py b/app/routes.py index 3fad96cd0..e8d7b48d7 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, flag): @@ -25,4 +25,24 @@ def list_planets(): description = planet.description, flag = planet.flag )) - return jsonify(planet_list) \ No newline at end of file + return jsonify(planet_list) + +@planet_bp.route("/", methods=["GET"]) +def get_planet(id): + planet = validate_planet(id) + return jsonify(dict( + id = planet.id, + name = planet.name, + description = planet.description, + flag = planet.flag, + )) + +def validate_planet(id): + try: + planet_id = int(id) + except: + abort(make_response({"message": f"planet {id} is invalid"}, 400)) + for planet in planets: + if planet.id == planet_id: + return planet + abort(make_response({"message": f"{planet_id} not found"}, 404)) \ No newline at end of file From 5f3e630c62d1232115adb4826d99189919dc7f51 Mon Sep 17 00:00:00 2001 From: Cristal Date: Mon, 31 Oct 2022 16:41:41 -0700 Subject: [PATCH 03/16] completed wave 03 --- app/__init__.py | 16 +++ app/models/planet.py | 9 ++ app/routes.py | 113 +++++++++++------- migrations/README | 1 + migrations/alembic.ini | 45 +++++++ migrations/env.py | 96 +++++++++++++++ migrations/script.py.mako | 24 ++++ .../versions/5b317c8c141e_removed_flag.py | 28 +++++ .../dc8232bcbf6e_adds_planet_model.py | 34 ++++++ .../versions/eaeb0e236b3c_re_added_flag.py | 28 +++++ 10 files changed, 351 insertions(+), 43 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/5b317c8c141e_removed_flag.py create mode 100644 migrations/versions/dc8232bcbf6e_adds_planet_model.py create mode 100644 migrations/versions/eaeb0e236b3c_re_added_flag.py diff --git a/app/__init__.py b/app/__init__.py index a1ade2bc2..f3a97f903 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,12 +1,28 @@ 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 app.models.planet import Planet + from .routes import planet_bp app.register_blueprint(planet_bp) + return app + \ No newline at end of file diff --git a/app/models/planet.py b/app/models/planet.py new file mode 100644 index 000000000..bae7cccbb --- /dev/null +++ b/app/models/planet.py @@ -0,0 +1,9 @@ +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) + flag = db.Column(db.Boolean) + diff --git a/app/routes.py b/app/routes.py index e8d7b48d7..60fd8038c 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,48 +1,75 @@ -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, flag): - self.id = id - self.name = name - self.description = description - self.flag = flag +# class Planet: +# def __init__(self, id, name, description, flag): +# self.id = id +# self.name = name +# self.description = description +# self.flag = flag -planets = [ -Planet(0, "jupiter", "largest planet in solar system", False), -Planet(1, "mercury", "smallest planet in solar system", False), -Planet(2, "mars", "most explored planet in solar system", True) -] +# planets = [ +# Planet(0, "jupiter", "largest planet in solar system", False), +# Planet(1, "mercury", "smallest planet in solar system", False), +# Planet(2, "mars", "most explored planet in solar system", True) +# ] planet_bp = Blueprint("planets", __name__, url_prefix="/planets") -@planet_bp.route("", methods=["GET"]) -def list_planets(): - planet_list = [] - for planet in planets: - planet_list.append(dict( - id = planet.id, - name = planet.name, - description = planet.description, - flag = planet.flag - )) - return jsonify(planet_list) - -@planet_bp.route("/", methods=["GET"]) -def get_planet(id): - planet = validate_planet(id) - return jsonify(dict( - id = planet.id, - name = planet.name, - description = planet.description, - flag = planet.flag, - )) - -def validate_planet(id): - try: - planet_id = int(id) - except: - abort(make_response({"message": f"planet {id} is invalid"}, 400)) - for planet in planets: - if planet.id == planet_id: - return planet - abort(make_response({"message": f"{planet_id} not found"}, 404)) \ No newline at end of file +@planet_bp.route("", methods=["GET", "POST"]) +def handle_planets(): + if request.method == "POST": + request_body = request.get_json() + new_planet = Planet(name=request_body["name"], + description=request_body["description"], + flag=request_body["flag"]) + db.session.add(new_planet) + db.session.commit() + return make_response("yay!", 201) + elif 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, + "flag": planet.flag}) + return jsonify(planets_response) + + + + + + +# @planet_bp.route("", methods=["GET"]) +# def list_planets(): +# planet_list = [] +# for planet in planets: +# planet_list.append(dict( +# id = planet.id, +# name = planet.name, +# description = planet.description, +# flag = planet.flag +# )) +# return jsonify(planet_list) + +# @planet_bp.route("/", methods=["GET"]) +# def get_planet(id): +# planet = validate_planet(id) +# return jsonify(dict( +# id = planet.id, +# name = planet.name, +# description = planet.description, +# flag = planet.flag, +# )) + +# def validate_planet(id): +# try: +# planet_id = int(id) +# except: +# abort(make_response({"message": f"planet {id} is invalid"}, 400)) +# for planet in planets: +# if planet.id == planet_id: +# return planet +# abort(make_response({"message": f"{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/5b317c8c141e_removed_flag.py b/migrations/versions/5b317c8c141e_removed_flag.py new file mode 100644 index 000000000..5cc6b7344 --- /dev/null +++ b/migrations/versions/5b317c8c141e_removed_flag.py @@ -0,0 +1,28 @@ +"""removed flag + +Revision ID: 5b317c8c141e +Revises: dc8232bcbf6e +Create Date: 2022-10-31 16:20:55.928060 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '5b317c8c141e' +down_revision = 'dc8232bcbf6e' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_column('planet', 'flag') + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('planet', sa.Column('flag', sa.BOOLEAN(), autoincrement=False, nullable=True)) + # ### end Alembic commands ### diff --git a/migrations/versions/dc8232bcbf6e_adds_planet_model.py b/migrations/versions/dc8232bcbf6e_adds_planet_model.py new file mode 100644 index 000000000..ca68b33bb --- /dev/null +++ b/migrations/versions/dc8232bcbf6e_adds_planet_model.py @@ -0,0 +1,34 @@ +"""adds planet model + +Revision ID: dc8232bcbf6e +Revises: +Create Date: 2022-10-31 16:12:09.052492 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'dc8232bcbf6e' +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('flag', sa.Boolean(), 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/eaeb0e236b3c_re_added_flag.py b/migrations/versions/eaeb0e236b3c_re_added_flag.py new file mode 100644 index 000000000..2f1cdff94 --- /dev/null +++ b/migrations/versions/eaeb0e236b3c_re_added_flag.py @@ -0,0 +1,28 @@ +"""re-added flag + +Revision ID: eaeb0e236b3c +Revises: 5b317c8c141e +Create Date: 2022-10-31 16:30:08.673148 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'eaeb0e236b3c' +down_revision = '5b317c8c141e' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('planet', sa.Column('flag', sa.Boolean(), nullable=True)) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_column('planet', 'flag') + # ### end Alembic commands ### From db623ceb9e2a5236a1aa9d170014df5fc56c7480 Mon Sep 17 00:00:00 2001 From: francescafr Date: Tue, 1 Nov 2022 11:01:52 -0700 Subject: [PATCH 04/16] Wave 4 complete --- app/routes.py | 47 +++++++++++++++++++++++++++++++++++++---------- 1 file changed, 37 insertions(+), 10 deletions(-) diff --git a/app/routes.py b/app/routes.py index 60fd8038c..a2b5e5dd7 100644 --- a/app/routes.py +++ b/app/routes.py @@ -17,6 +17,19 @@ planet_bp = Blueprint("planets", __name__, url_prefix="/planets") +def validate_planet(id): + try: + id = int(id) + except: + abort(make_response({"message": f"planet '{id}' is invalid"}, 400)) + + planet = Planet.query.get(id) + + if not planet: + abort(make_response({"message": f"Planet {id} not found"}, 404)) + + return planet + @planet_bp.route("", methods=["GET", "POST"]) def handle_planets(): if request.method == "POST": @@ -37,9 +50,32 @@ def handle_planets(): "flag": planet.flag}) return jsonify(planets_response) +@planet_bp.route("/", methods=["GET"]) +def get_one_planet(id): + validate_planet(id) + planet = Planet.query.get(id) + return {"id": planet.id, + "name": planet.name, + "description": planet.description, + "flag": planet.flag} +@planet_bp.route("/", methods=["PUT"]) +def update_planet(id): + planet = validate_planet(id) + request_body = request.get_json() + planet.name = request_body["name"] + planet.description = request_body["description"] + planet.flag = request_body["flag"] + + db.session.commit() + return make_response(f"Planet #{id} successfully updated!", 200) - +@planet_bp.route("/", methods=["DELETE"]) +def delete_planet(id): + planet = validate_planet(id) + db.session.delete(planet) + db.session.commit() + return make_response(f"Planet #{id} successfully deleted!", 200) # @planet_bp.route("", methods=["GET"]) @@ -64,12 +100,3 @@ def handle_planets(): # flag = planet.flag, # )) -# def validate_planet(id): -# try: -# planet_id = int(id) -# except: -# abort(make_response({"message": f"planet {id} is invalid"}, 400)) -# for planet in planets: -# if planet.id == planet_id: -# return planet -# abort(make_response({"message": f"{planet_id} not found"}, 404)) \ No newline at end of file From a8c91b5ec5c8789e7c7ffdd70a59631b7f7a3654 Mon Sep 17 00:00:00 2001 From: Cristal Date: Wed, 2 Nov 2022 14:33:22 -0700 Subject: [PATCH 05/16] wave 05 --- app/models/planet.py | 7 +++++++ app/routes.py | 6 +----- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index bae7cccbb..e68fbbae1 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -7,3 +7,10 @@ class Planet(db.Model): description = db.Column(db.String) flag = db.Column(db.Boolean) + @classmethod + def to_dict(self): + return dict( + id=self.id, + name=self.name, + description=self.description, + flag=self.flag) \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 60fd8038c..0fd76a664 100644 --- a/app/routes.py +++ b/app/routes.py @@ -30,11 +30,7 @@ def handle_planets(): elif 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, - "flag": planet.flag}) + planets_response.append([planet.to_dict() for planet in planets]) return jsonify(planets_response) From e6ad48941c362cec8cba32f78b6498a7038314f4 Mon Sep 17 00:00:00 2001 From: francescafr Date: Wed, 2 Nov 2022 15:29:16 -0700 Subject: [PATCH 06/16] added to_dict and from_dict helper functions to planet.py --- app/models/planet.py | 14 ++++++++++---- app/routes.py | 11 +++-------- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index e68fbbae1..e21490164 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -8,9 +8,15 @@ class Planet(db.Model): flag = db.Column(db.Boolean) @classmethod + def from_dict(cls,input_data): + return cls(name=input_data["name"], + description=input_data["description"], + flag=input_data["flag"]) + def to_dict(self): return dict( - id=self.id, - name=self.name, - description=self.description, - flag=self.flag) \ No newline at end of file + id=self.id, + name=self.name, + description=self.description, + flag=self.flag + ) \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 0fd76a664..8ee269637 100644 --- a/app/routes.py +++ b/app/routes.py @@ -21,23 +21,18 @@ def handle_planets(): if request.method == "POST": request_body = request.get_json() - new_planet = Planet(name=request_body["name"], - description=request_body["description"], - flag=request_body["flag"]) + new_planet = Planet.from_dict(request_body) db.session.add(new_planet) db.session.commit() return make_response("yay!", 201) + elif request.method == "GET": - planets = Planet.query.all() + planets = Planet.query.all() planets_response = [] planets_response.append([planet.to_dict() for planet in planets]) return jsonify(planets_response) - - - - # @planet_bp.route("", methods=["GET"]) # def list_planets(): # planet_list = [] From 1f5ad44ab37a3cc317c0f785b64f628fea84a05a Mon Sep 17 00:00:00 2001 From: Cristal Date: Wed, 2 Nov 2022 15:52:22 -0700 Subject: [PATCH 07/16] validate model function --- app/routes.py | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/app/routes.py b/app/routes.py index 8ee269637..191daa2e5 100644 --- a/app/routes.py +++ b/app/routes.py @@ -21,18 +21,37 @@ def handle_planets(): if request.method == "POST": request_body = request.get_json() - new_planet = Planet.from_dict(request_body) + new_planet = Planet(name=request_body["name"], + description=request_body["description"], + flag=request_body["flag"]) db.session.add(new_planet) db.session.commit() return make_response("yay!", 201) - elif request.method == "GET": - planets = Planet.query.all() + planets = Planet.query.all() planets_response = [] planets_response.append([planet.to_dict() for planet in planets]) return jsonify(planets_response) +def validate_model(cls, model_id): + try: + model_id = int(model_id) + except: + abort(make_response({"message": f"object {model_id} is invalid"}, 400)) + + model = cls.query.get(model_id) + if not model: + abort(make_response({"message": f"{model_id} not found"}, 404)) + + +@planet_bp.route("/", methods=["GET"]) +def get_planet(id): + validate_model(Planet, id) + planet = Planet.query.get(id) + return jsonify(planet.to_dict()) + + # @planet_bp.route("", methods=["GET"]) # def list_planets(): # planet_list = [] From 6853ea8d9091d7341ddfec9c6ffcce0fa790098b Mon Sep 17 00:00:00 2001 From: francescafr Date: Wed, 2 Nov 2022 18:18:16 -0700 Subject: [PATCH 08/16] created test files --- .gitignore | 1 + app/__init__.py | 16 +++++++++----- app/models/planet.py | 1 - app/routes.py | 51 +------------------------------------------- tests/__init__.py | 0 tests/conftest.py | 32 +++++++++++++++++++++++++++ tests/test_routes.py | 34 +++++++++++++++++++++++++++++ 7 files changed, 79 insertions(+), 56 deletions(-) create mode 100644 tests/__init__.py create mode 100644 tests/conftest.py create mode 100644 tests/test_routes.py diff --git a/.gitignore b/.gitignore index 4e9b18359..577f9295e 100644 --- a/.gitignore +++ b/.gitignore @@ -89,6 +89,7 @@ ipython_config.py # For a library or package, you might want to ignore these files since the code is # intended to run in multiple environments; otherwise, check them in: # .python-version +.env # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. diff --git a/app/__init__.py b/app/__init__.py index f3a97f903..2a01a79be 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,17 +1,23 @@ from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate +from dotenv import load_dotenv +import os db = SQLAlchemy() migrate = Migrate() +load_dotenv() - -def create_app(test_config=None): +def create_app(test_config=True): app = Flask(__name__) - app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False - app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system_development' - + if not test_config: + app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("SQLALCHEMY_DATABASE_URI") + else: + app.config["TESTING"] = True + app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("SQLALCHEMY_TEST_DATABASE_URI") db.init_app(app) migrate.init_app(app, db) diff --git a/app/models/planet.py b/app/models/planet.py index e21490164..6aa161f68 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -1,6 +1,5 @@ from app import db - class Planet(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String) diff --git a/app/routes.py b/app/routes.py index 191daa2e5..171d0f014 100644 --- a/app/routes.py +++ b/app/routes.py @@ -2,19 +2,6 @@ from app import db from app.models.planet import Planet -# class Planet: -# def __init__(self, id, name, description, flag): -# self.id = id -# self.name = name -# self.description = description -# self.flag = flag - -# planets = [ -# Planet(0, "jupiter", "largest planet in solar system", False), -# Planet(1, "mercury", "smallest planet in solar system", False), -# Planet(2, "mars", "most explored planet in solar system", True) -# ] - planet_bp = Blueprint("planets", __name__, url_prefix="/planets") @planet_bp.route("", methods=["GET", "POST"]) @@ -29,11 +16,9 @@ def handle_planets(): return make_response("yay!", 201) elif request.method == "GET": planets = Planet.query.all() - planets_response = [] - planets_response.append([planet.to_dict() for planet in planets]) + planets_response = [planet.to_dict() for planet in planets] return jsonify(planets_response) - def validate_model(cls, model_id): try: model_id = int(model_id) @@ -44,42 +29,8 @@ def validate_model(cls, model_id): if not model: abort(make_response({"message": f"{model_id} not found"}, 404)) - @planet_bp.route("/", methods=["GET"]) def get_planet(id): validate_model(Planet, id) planet = Planet.query.get(id) return jsonify(planet.to_dict()) - - -# @planet_bp.route("", methods=["GET"]) -# def list_planets(): -# planet_list = [] -# for planet in planets: -# planet_list.append(dict( -# id = planet.id, -# name = planet.name, -# description = planet.description, -# flag = planet.flag -# )) -# return jsonify(planet_list) - -# @planet_bp.route("/", methods=["GET"]) -# def get_planet(id): -# planet = validate_planet(id) -# return jsonify(dict( -# id = planet.id, -# name = planet.name, -# description = planet.description, -# flag = planet.flag, -# )) - -# def validate_planet(id): -# try: -# planet_id = int(id) -# except: -# abort(make_response({"message": f"planet {id} is invalid"}, 400)) -# for planet in planets: -# if planet.id == planet_id: -# return planet -# abort(make_response({"message": f"{planet_id} not found"}, 404)) \ No newline at end of file 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..8bdf34ec1 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,32 @@ +import pytest +from app import create_app +from app import db +from flask.signals import request_finished + +@pytest.fixture +def empty_list(): + return [] + +def test_len_of_empty_list(empty_list): + assert isinstance(empty_list, list) + assert len(empty_list) == 0 + +@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() + diff --git a/tests/test_routes.py b/tests/test_routes.py new file mode 100644 index 000000000..39f106327 --- /dev/null +++ b/tests/test_routes.py @@ -0,0 +1,34 @@ +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 == [] + + +# GET /planets/1 returns response body that matches our fixture +def test_get_first_planet(client): +# act + response = client.get('/planets/1') + response_body = response.get_json() +# assert + assert response.status_code == 200 + assert response_body == { + "id": "1", + "name": "" + + } + +# GET /planets/1 with no data in test database (no fixture) returns a 404 + +# act + +# assert + +# GET /planets with JSON request body returns a 201 + +# act + +# assert \ No newline at end of file From 4fd78764cfb9799dcb6a2d75e98a2a62cd4ed527 Mon Sep 17 00:00:00 2001 From: Cristal Date: Thu, 3 Nov 2022 12:04:21 -0700 Subject: [PATCH 09/16] created tests 1-2 --- app/__init__.py | 8 +++---- app/routes.py | 2 +- tests/conftest.py | 25 +++++++++++++++++++++ tests/test_routes.py | 52 ++++++++++++++++++++++++++++++++------------ 4 files changed, 68 insertions(+), 19 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 2a01a79be..bf88da75b 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -8,15 +8,15 @@ migrate = Migrate() load_dotenv() -def create_app(test_config=True): +def create_app(test_config=None): app = Flask(__name__) - + + app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False + 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) diff --git a/app/routes.py b/app/routes.py index 171d0f014..3fcb350c4 100644 --- a/app/routes.py +++ b/app/routes.py @@ -13,7 +13,7 @@ def handle_planets(): flag=request_body["flag"]) db.session.add(new_planet) db.session.commit() - return make_response("yay!", 201) + return make_response(f"planet {new_planet.name} successfully created!", 201) elif request.method == "GET": planets = Planet.query.all() planets_response = [planet.to_dict() for planet in planets] diff --git a/tests/conftest.py b/tests/conftest.py index 8bdf34ec1..7703357ad 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -2,6 +2,7 @@ from app import create_app from app import db from flask.signals import request_finished +from app.models.planet import Planet @pytest.fixture def empty_list(): @@ -30,3 +31,27 @@ def expire_session(sender, response, **extra): def client(app): return app.test_client() +@pytest.fixture +def one_planet(app): + planet = Planet(name="venus", + description="doesn't have any moons, 2nd largest planet.", + flag=False) + + db.session.add(planet) + db.session.commit() + return planet + + +@pytest.fixture +def multi_planets(app): + planet_one = Planet(name="venus", + description="doesn't have any moons, 2nd largest planet.", + flag=False) + planet_two = Planet(name="Neptune", + description="one of two ice giant planets.", + flag=False) + planet_list = [planet_one, planet_two] + + db.session.add(planet_one, planet_two) + db.session.commit() + return planet_list \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py index 39f106327..56174b5f7 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -1,3 +1,6 @@ +from flask import jsonify +from app.models.planet import Planet + def test_get_all_planets_with_no_records(client): #act response = client.get('/planets') @@ -9,26 +12,47 @@ def test_get_all_planets_with_no_records(client): # GET /planets/1 returns response body that matches our fixture -def test_get_first_planet(client): +def test_get_first_planet(client, one_planet): # act response = client.get('/planets/1') response_body = response.get_json() # assert assert response.status_code == 200 - assert response_body == { - "id": "1", - "name": "" - - } + assert response_body["id"] == one_planet.id + assert response_body["name"] == one_planet.name + assert response_body["description"] == one_planet.description + assert response_body["flag"] == one_planet.flag # GET /planets/1 with no data in test database (no fixture) returns a 404 - +def test_get_empty_database_returns_404(client): # act - + response = client.get('/planets/1') # assert - -# GET /planets with JSON request body returns a 201 - -# act - -# assert \ No newline at end of file + assert response.status_code == 404 + +# GET /planets with JSON request body returns a 200 +# def test_planets_with_data_return_200_with_valid_data(client, multi_planets): +# # act +# response = client.get('/planets') +# response_body = response.get_json() +# # assert +# assert response.status_code == 200 +# assert response_body["id"] == multi_planets[0].id +# assert response_body["name"] == one_planet.name +# assert response_body["description"] == one_planet.description +# assert response_body["flag"] == one_planet.flag + + +# POST /planets with JSON request body returns a 201 +def test_save_planet(client): + # arrange + NEW_PLANET ={"name": "Mercury", + "description": "planet closest to the sun.", + "flag": False} + # act + response = client.post('/planets', json=NEW_PLANET) + response_body = response.get_json() + + # assert + assert response.status_code == 201 + assert response_body == f"planet {NEW_PLANET['name']} successfully created!" \ No newline at end of file From 9dc98a23caf7ed4442b58e908d616da780ba2f80 Mon Sep 17 00:00:00 2001 From: francescafr Date: Thu, 3 Nov 2022 12:36:00 -0700 Subject: [PATCH 10/16] passing all wave 6 tests --- tests/conftest.py | 4 ++-- tests/test_routes.py | 31 ++++++++++++++++++------------- 2 files changed, 20 insertions(+), 15 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index 7703357ad..df2996e12 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -52,6 +52,6 @@ def multi_planets(app): flag=False) planet_list = [planet_one, planet_two] - db.session.add(planet_one, planet_two) + db.session.add_all(planet_list) db.session.commit() - return planet_list \ No newline at end of file + \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py index 56174b5f7..5fb805af4 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -10,7 +10,6 @@ def test_get_all_planets_with_no_records(client): assert response.status_code == 200 assert response_body == [] - # GET /planets/1 returns response body that matches our fixture def test_get_first_planet(client, one_planet): # act @@ -31,17 +30,23 @@ def test_get_empty_database_returns_404(client): assert response.status_code == 404 # GET /planets with JSON request body returns a 200 -# def test_planets_with_data_return_200_with_valid_data(client, multi_planets): -# # act -# response = client.get('/planets') -# response_body = response.get_json() -# # assert -# assert response.status_code == 200 -# assert response_body["id"] == multi_planets[0].id -# assert response_body["name"] == one_planet.name -# assert response_body["description"] == one_planet.description -# assert response_body["flag"] == one_planet.flag - +def test_planets_with_data_return_200_with_valid_data(client, multi_planets): +# act + response = client.get('/planets') + response_body = response.get_json() +# assert + assert response.status_code == 200 + assert response_body == [ { + 'name': 'venus', + 'description': "doesn't have any moons, 2nd largest planet.", + 'flag': False, + 'id': 1}, + { + 'name': 'Neptune', 'description': 'one of two ice giant planets.', + 'flag': False, + 'id': 2 + } + ] # POST /planets with JSON request body returns a 201 def test_save_planet(client): @@ -51,7 +56,7 @@ def test_save_planet(client): "flag": False} # act response = client.post('/planets', json=NEW_PLANET) - response_body = response.get_json() + response_body = response.get_data(as_text=True) # assert assert response.status_code == 201 From d7d9cfa70b96d560bd407a8d94ea2a7dd3cfa013 Mon Sep 17 00:00:00 2001 From: francescafr Date: Thu, 3 Nov 2022 12:52:48 -0700 Subject: [PATCH 11/16] improved formatting --- app/models/planet.py | 6 ++++-- app/routes.py | 17 +++++++++-------- tests/conftest.py | 18 +++++------------- tests/test_routes.py | 21 +++++++++++++-------- 4 files changed, 31 insertions(+), 31 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index 6aa161f68..7c50ec5d3 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -8,9 +8,11 @@ class Planet(db.Model): @classmethod def from_dict(cls,input_data): - return cls(name=input_data["name"], + return cls( + name=input_data["name"], description=input_data["description"], - flag=input_data["flag"]) + flag=input_data["flag"] + ) def to_dict(self): return dict( diff --git a/app/routes.py b/app/routes.py index 3fcb350c4..288819af8 100644 --- a/app/routes.py +++ b/app/routes.py @@ -14,23 +14,24 @@ def handle_planets(): db.session.add(new_planet) db.session.commit() return make_response(f"planet {new_planet.name} successfully created!", 201) + elif request.method == "GET": planets = Planet.query.all() planets_response = [planet.to_dict() for planet in planets] return jsonify(planets_response) +@planet_bp.route("/", methods=["GET"]) +def get_planet(id): + validate_model(Planet, id) + planet = Planet.query.get(id) + return jsonify(planet.to_dict()) + def validate_model(cls, model_id): try: model_id = int(model_id) except: - abort(make_response({"message": f"object {model_id} is invalid"}, 400)) + abort(make_response({"message": f"object '{model_id}' is invalid"}, 400)) model = cls.query.get(model_id) if not model: - abort(make_response({"message": f"{model_id} not found"}, 404)) - -@planet_bp.route("/", methods=["GET"]) -def get_planet(id): - validate_model(Planet, id) - planet = Planet.query.get(id) - return jsonify(planet.to_dict()) + abort(make_response({"message": f"{model_id} not found"}, 404)) \ No newline at end of file diff --git a/tests/conftest.py b/tests/conftest.py index df2996e12..49c52f383 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -4,14 +4,6 @@ from flask.signals import request_finished from app.models.planet import Planet -@pytest.fixture -def empty_list(): - return [] - -def test_len_of_empty_list(empty_list): - assert isinstance(empty_list, list) - assert len(empty_list) == 0 - @pytest.fixture def app(): app = create_app({"TESTING": True}) @@ -41,15 +33,15 @@ def one_planet(app): db.session.commit() return planet - @pytest.fixture def multi_planets(app): planet_one = Planet(name="venus", - description="doesn't have any moons, 2nd largest planet.", - flag=False) + description="doesn't have any moons, 2nd largest planet.", + flag=False) planet_two = Planet(name="Neptune", - description="one of two ice giant planets.", - flag=False) + description="one of two ice giant planets.", + flag=False) + planet_list = [planet_one, planet_two] db.session.add_all(planet_list) diff --git a/tests/test_routes.py b/tests/test_routes.py index 5fb805af4..b3e0c225a 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -1,7 +1,7 @@ -from flask import jsonify from app.models.planet import Planet -def test_get_all_planets_with_no_records(client): +# GET /planets returns empty list +def test_get_all_planets_with_no_records_returns_empty(client): #act response = client.get('/planets') response_body = response.get_json() @@ -10,31 +10,35 @@ def test_get_all_planets_with_no_records(client): assert response.status_code == 200 assert response_body == [] + # GET /planets/1 returns response body that matches our fixture def test_get_first_planet(client, one_planet): -# act + # act response = client.get('/planets/1') response_body = response.get_json() -# assert + + # assert assert response.status_code == 200 assert response_body["id"] == one_planet.id assert response_body["name"] == one_planet.name assert response_body["description"] == one_planet.description assert response_body["flag"] == one_planet.flag + # GET /planets/1 with no data in test database (no fixture) returns a 404 def test_get_empty_database_returns_404(client): -# act + # act response = client.get('/planets/1') -# assert + # assert assert response.status_code == 404 + # GET /planets with JSON request body returns a 200 def test_planets_with_data_return_200_with_valid_data(client, multi_planets): -# act + # act response = client.get('/planets') response_body = response.get_json() -# assert + # assert assert response.status_code == 200 assert response_body == [ { 'name': 'venus', @@ -48,6 +52,7 @@ def test_planets_with_data_return_200_with_valid_data(client, multi_planets): } ] + # POST /planets with JSON request body returns a 201 def test_save_planet(client): # arrange From 5b74c66342b83d52d350aaa6ec085802fd9743c2 Mon Sep 17 00:00:00 2001 From: francescafr Date: Thu, 3 Nov 2022 13:06:31 -0700 Subject: [PATCH 12/16] improved formatting --- tests/test_routes.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/test_routes.py b/tests/test_routes.py index b3e0c225a..30f8985ee 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -44,9 +44,11 @@ def test_planets_with_data_return_200_with_valid_data(client, multi_planets): 'name': 'venus', 'description': "doesn't have any moons, 2nd largest planet.", 'flag': False, - 'id': 1}, + 'id': 1 + }, { - 'name': 'Neptune', 'description': 'one of two ice giant planets.', + 'name': 'Neptune', + 'description': 'one of two ice giant planets.', 'flag': False, 'id': 2 } From f291e27680576720f187314e0f273413e432de0d Mon Sep 17 00:00:00 2001 From: Cristal Date: Thu, 3 Nov 2022 16:16:53 -0700 Subject: [PATCH 13/16] added a comment for where I think we can use a query param, still unsure --- app/__init__.py | 5 +---- app/routes.py | 2 ++ tests/conftest.py | 1 - tests/test_routes.py | 7 ++----- 4 files changed, 5 insertions(+), 10 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index bf88da75b..8d62712be 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -28,7 +28,4 @@ def create_app(test_config=None): app.register_blueprint(planet_bp) - return app - - - \ No newline at end of file + return app \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 288819af8..62f97a413 100644 --- a/app/routes.py +++ b/app/routes.py @@ -20,6 +20,8 @@ def handle_planets(): planets_response = [planet.to_dict() for planet in planets] return jsonify(planets_response) +# Would we add a query param here? ^ + @planet_bp.route("/", methods=["GET"]) def get_planet(id): validate_model(Planet, id) diff --git a/tests/conftest.py b/tests/conftest.py index 49c52f383..21eeaa71d 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -46,4 +46,3 @@ def multi_planets(app): db.session.add_all(planet_list) db.session.commit() - \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py index 30f8985ee..e6ed4716b 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -1,6 +1,6 @@ from app.models.planet import Planet -# GET /planets returns empty list + def test_get_all_planets_with_no_records_returns_empty(client): #act response = client.get('/planets') @@ -11,7 +11,6 @@ def test_get_all_planets_with_no_records_returns_empty(client): assert response_body == [] -# GET /planets/1 returns response body that matches our fixture def test_get_first_planet(client, one_planet): # act response = client.get('/planets/1') @@ -25,7 +24,6 @@ def test_get_first_planet(client, one_planet): assert response_body["flag"] == one_planet.flag -# GET /planets/1 with no data in test database (no fixture) returns a 404 def test_get_empty_database_returns_404(client): # act response = client.get('/planets/1') @@ -33,7 +31,7 @@ def test_get_empty_database_returns_404(client): assert response.status_code == 404 -# GET /planets with JSON request body returns a 200 + def test_planets_with_data_return_200_with_valid_data(client, multi_planets): # act response = client.get('/planets') @@ -55,7 +53,6 @@ def test_planets_with_data_return_200_with_valid_data(client, multi_planets): ] -# POST /planets with JSON request body returns a 201 def test_save_planet(client): # arrange NEW_PLANET ={"name": "Mercury", From 501a1dfedaade90e5342da694a1335aab27050bc Mon Sep 17 00:00:00 2001 From: Cristal Date: Thu, 3 Nov 2022 19:10:31 -0700 Subject: [PATCH 14/16] added name and id search queries --- app/routes.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/routes.py b/app/routes.py index 62f97a413..ae9a43e06 100644 --- a/app/routes.py +++ b/app/routes.py @@ -16,6 +16,8 @@ def handle_planets(): return make_response(f"planet {new_planet.name} successfully created!", 201) elif request.method == "GET": + name_query = request.args.get("name") + id_query = request.args.get("id") planets = Planet.query.all() planets_response = [planet.to_dict() for planet in planets] return jsonify(planets_response) From 3daa29df9d53e7f9a80ed6ce6ba138c3b349794e Mon Sep 17 00:00:00 2001 From: Cristal Date: Thu, 3 Nov 2022 20:27:57 -0700 Subject: [PATCH 15/16] working on name and id queries --- app/routes.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index ae9a43e06..589a12b9d 100644 --- a/app/routes.py +++ b/app/routes.py @@ -18,11 +18,18 @@ def handle_planets(): elif request.method == "GET": name_query = request.args.get("name") id_query = request.args.get("id") + + planet_query = Planet.query + + if name_query: + planet_query = planet_query.filter_by(name=name_query) + if id_query: + planet_query = planet_query.filter_by(id=id_query) + planets = Planet.query.all() planets_response = [planet.to_dict() for planet in planets] return jsonify(planets_response) -# Would we add a query param here? ^ @planet_bp.route("/", methods=["GET"]) def get_planet(id): From 4d5e3180e4f29ee7b8368620464ba4c169484a2c Mon Sep 17 00:00:00 2001 From: francescafr Date: Fri, 4 Nov 2022 07:18:36 -0700 Subject: [PATCH 16/16] added queries for flag and name --- app/routes.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/app/routes.py b/app/routes.py index 589a12b9d..66260a362 100644 --- a/app/routes.py +++ b/app/routes.py @@ -17,16 +17,16 @@ def handle_planets(): elif request.method == "GET": name_query = request.args.get("name") - id_query = request.args.get("id") + flag_query = request.args.get("flag") planet_query = Planet.query if name_query: planet_query = planet_query.filter_by(name=name_query) - if id_query: - planet_query = planet_query.filter_by(id=id_query) + if flag_query: + planet_query = planet_query.filter_by(flag=flag_query) - planets = Planet.query.all() + planets = planet_query.all() planets_response = [planet.to_dict() for planet in planets] return jsonify(planets_response)