From 5a1644cdaee612f20cbe5c96279870cb84b71077 Mon Sep 17 00:00:00 2001 From: Tyrah Date: Fri, 22 Apr 2022 11:09:25 -0700 Subject: [PATCH 01/15] "completed wave 1 with thu and hillary and tyrah" --- app/__init__.py | 3 +++ app/routes.py | 36 +++++++++++++++++++++++++++++++++++- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..1123a559e 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -4,4 +4,7 @@ def create_app(test_config=None): app = Flask(__name__) + from .routes import bp + app.register_blueprint(bp) + return app diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..a6bc2856f 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,36 @@ -from flask import Blueprint +from flask import Blueprint, jsonify +class Planet: + def __init__(self, id, name, description, has_moon=None): + self.id = id + self.name = name + self.description = description + self.has_moon = has_moon + +planets = [ + Planet(1, "Mercury", "terrestrial", False), + Planet(2, "Jupiter", "gaseous", True), + Planet(3, "Earth", "terrestrial", True) +] + +#instantiate blueprint object +bp = Blueprint("planets_bp",__name__, url_prefix="/planets") + +#design endpoint with blueprint tag +"""..to get all existing planets, so that I can see a list of planets, +with their id, name, description, and other data of the planet.""" + +@bp.route("", methods=["GET"]) +def list_planets(): + list_of_planets = [dict( + id = planet.id, + name = planet.name, + description = planet.description, + has_moon = planet.has_moon, + ) for planet in planets] + + return jsonify(list_of_planets) + +# FLASK_ENV=developer flask run + + From 0c6f9f1e201f1e547e93a810ff2624b95b439c80 Mon Sep 17 00:00:00 2001 From: Thu Vuong Date: Fri, 22 Apr 2022 11:22:47 -0700 Subject: [PATCH 02/15] removed comments --- app/__init__.py | 1 - app/routes.py | 9 --------- 2 files changed, 10 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 1123a559e..fadc19d57 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,6 +1,5 @@ from flask import Flask - def create_app(test_config=None): app = Flask(__name__) diff --git a/app/routes.py b/app/routes.py index a6bc2856f..4ad294b4a 100644 --- a/app/routes.py +++ b/app/routes.py @@ -13,13 +13,8 @@ def __init__(self, id, name, description, has_moon=None): Planet(3, "Earth", "terrestrial", True) ] -#instantiate blueprint object bp = Blueprint("planets_bp",__name__, url_prefix="/planets") -#design endpoint with blueprint tag -"""..to get all existing planets, so that I can see a list of planets, -with their id, name, description, and other data of the planet.""" - @bp.route("", methods=["GET"]) def list_planets(): list_of_planets = [dict( @@ -30,7 +25,3 @@ def list_planets(): ) for planet in planets] return jsonify(list_of_planets) - -# FLASK_ENV=developer flask run - - From 43cd3389cde892ea311e07643a33ef698effef7f Mon Sep 17 00:00:00 2001 From: Shannon Bellemore Date: Mon, 25 Apr 2022 15:25:04 -0500 Subject: [PATCH 03/15] get one planet --- app/routes.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/app/routes.py b/app/routes.py index 4ad294b4a..16bf70f75 100644 --- a/app/routes.py +++ b/app/routes.py @@ -25,3 +25,19 @@ def list_planets(): ) for planet in planets] return jsonify(list_of_planets) + +@bp.route("/", methods=["GET"]) +def get_planet(id): + try: + id = int(id) + except ValueError: + return jsonify({"message":f"planet {id} invalid"}), 400 + + for planet in planets: + if planet.id == id: + return jsonify(dict( + id = planet.id, + name = planet.name, + description = planet.description, + has_moon = planet.has_moon)) + return jsonify({"message":f"planet {id} not found"}), 404 From 94e65be55d029867135e744c444e9a4ae88d439f Mon Sep 17 00:00:00 2001 From: Shannon Bellemore Date: Mon, 25 Apr 2022 17:35:17 -0500 Subject: [PATCH 04/15] modified get_planet --- app/routes.py | 36 +++++++++++++++++++----------------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/app/routes.py b/app/routes.py index 16bf70f75..6308d13a5 100644 --- a/app/routes.py +++ b/app/routes.py @@ -7,6 +7,14 @@ def __init__(self, id, name, description, has_moon=None): self.description = description self.has_moon = has_moon + def make_dict(self): + return dict( + id = self.id, + name = self.name, + description = self.description, + has_moon = self.has_moon, + ) + planets = [ Planet(1, "Mercury", "terrestrial", False), Planet(2, "Jupiter", "gaseous", True), @@ -15,29 +23,23 @@ def __init__(self, id, name, description, has_moon=None): bp = Blueprint("planets_bp",__name__, url_prefix="/planets") +# GET /planets @bp.route("", methods=["GET"]) def list_planets(): - list_of_planets = [dict( - id = planet.id, - name = planet.name, - description = planet.description, - has_moon = planet.has_moon, - ) for planet in planets] + list_of_planets = [planet.make_dict() for planet in planets] return jsonify(list_of_planets) +# GET planets/id @bp.route("/", methods=["GET"]) def get_planet(id): - try: - id = int(id) - except ValueError: - return jsonify({"message":f"planet {id} invalid"}), 400 - + id = int(id) for planet in planets: if planet.id == id: - return jsonify(dict( - id = planet.id, - name = planet.name, - description = planet.description, - has_moon = planet.has_moon)) - return jsonify({"message":f"planet {id} not found"}), 404 + return jsonify(planet.make_dict()) + # try: + # id = int(id) + # except ValueError: + # return jsonify({"message":f"planet {id} invalid"}), 400 + + # return jsonify({"message":f"planet {id} not found"}), 404 From 815fa1a7afbce9cd5809afab9fda3ba639966f14 Mon Sep 17 00:00:00 2001 From: Shannon Bellemore Date: Mon, 25 Apr 2022 17:48:50 -0500 Subject: [PATCH 05/15] handled errors --- app/routes.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/app/routes.py b/app/routes.py index 6308d13a5..0a3f0b6d9 100644 --- a/app/routes.py +++ b/app/routes.py @@ -33,13 +33,13 @@ def list_planets(): # GET planets/id @bp.route("/", methods=["GET"]) def get_planet(id): - id = int(id) + try: + id = int(id) + except ValueError: + return jsonify(dict(message=f"planet {id} is invalid")), 400 + for planet in planets: if planet.id == id: return jsonify(planet.make_dict()) - # try: - # id = int(id) - # except ValueError: - # return jsonify({"message":f"planet {id} invalid"}), 400 - # return jsonify({"message":f"planet {id} not found"}), 404 + return jsonify(dict(message=f"planet {id} not found")), 404 From 98d3d0fa4e957bde7443f15931afb43b00285434 Mon Sep 17 00:00:00 2001 From: Shannon Bellemore Date: Mon, 25 Apr 2022 18:12:02 -0500 Subject: [PATCH 06/15] added abort and validate_planet --- app/__init__.py | 4 ++-- app/routes/__init__.py | 0 app/{routes.py => routes/planet_routes.py} | 18 +++++++++++------- 3 files changed, 13 insertions(+), 9 deletions(-) create mode 100644 app/routes/__init__.py rename app/{routes.py => routes/planet_routes.py} (73%) diff --git a/app/__init__.py b/app/__init__.py index fadc19d57..79517b3b0 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -3,7 +3,7 @@ def create_app(test_config=None): app = Flask(__name__) - from .routes import bp - app.register_blueprint(bp) + from .routes import planet_routes + app.register_blueprint(planet_routes.bp) return app diff --git a/app/routes/__init__.py b/app/routes/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/app/routes.py b/app/routes/planet_routes.py similarity index 73% rename from app/routes.py rename to app/routes/planet_routes.py index 0a3f0b6d9..1e505bbc1 100644 --- a/app/routes.py +++ b/app/routes/planet_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, has_moon=None): @@ -30,16 +30,20 @@ def list_planets(): return jsonify(list_of_planets) -# GET planets/id -@bp.route("/", methods=["GET"]) -def get_planet(id): +def validate_planet(id): try: id = int(id) except ValueError: - return jsonify(dict(message=f"planet {id} is invalid")), 400 + abort(make_response(jsonify(dict(message=f"planet {id} is invalid")), 400)) for planet in planets: if planet.id == id: - return jsonify(planet.make_dict()) + return planet + + abort(make_response(jsonify(dict(message=f"planet {id} not found")), 404)) - return jsonify(dict(message=f"planet {id} not found")), 404 +# GET planets/id +@bp.route("/", methods=["GET"]) +def get_planet(id): + planet = validate_planet(id) + return jsonify(planet.make_dict()) \ No newline at end of file From f979e6d372100079c21365a7babaa484df2c91c6 Mon Sep 17 00:00:00 2001 From: Hillary Smith Date: Fri, 29 Apr 2022 11:34:21 -0700 Subject: [PATCH 07/15] worked on wave 3 --- app/__init__.py | 11 +++++++++++ app/models/__init__.py | 0 app/models/planet.py | 15 +++++++++++++++ app/routes/planet_routes.py | 28 ++++++++++++++-------------- 4 files changed, 40 insertions(+), 14 deletions(-) create mode 100644 app/models/__init__.py create mode 100644 app/models/planet.py diff --git a/app/__init__.py b/app/__init__.py index 79517b3b0..247401996 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,8 +1,19 @@ 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 planet_routes app.register_blueprint(planet_routes.bp) diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/app/models/planet.py b/app/models/planet.py new file mode 100644 index 000000000..18919ae92 --- /dev/null +++ b/app/models/planet.py @@ -0,0 +1,15 @@ +from app import db + +class Planet(db.Model): + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + name = db.Column(db.String, nullable=False) + description = db.Column(db.String, nullable=False) + has_moon = db.Column(db.Boolean, nullable=False) + + def make_dict(self): + return dict( + id = self.id, + name = self.name, + description = self.description, + has_moon = self.has_moon, + ) diff --git a/app/routes/planet_routes.py b/app/routes/planet_routes.py index 1e505bbc1..fc665fb68 100644 --- a/app/routes/planet_routes.py +++ b/app/routes/planet_routes.py @@ -1,19 +1,19 @@ from flask import Blueprint, jsonify, abort, make_response -class Planet: - def __init__(self, id, name, description, has_moon=None): - self.id = id - self.name = name - self.description = description - self.has_moon = has_moon - - def make_dict(self): - return dict( - id = self.id, - name = self.name, - description = self.description, - has_moon = self.has_moon, - ) +# class Planet: +# def __init__(self, id, name, description, has_moon=None): +# self.id = id +# self.name = name +# self.description = description +# self.has_moon = has_moon + +# def make_dict(self): +# return dict( +# id = self.id, +# name = self.name, +# description = self.description, +# has_moon = self.has_moon, +# ) planets = [ Planet(1, "Mercury", "terrestrial", False), From 3e6d1d3d6de5700203961bd9ded3bc6e9276dbc3 Mon Sep 17 00:00:00 2001 From: Hillary Smith Date: Fri, 29 Apr 2022 11:36:41 -0700 Subject: [PATCH 08/15] worked on wave 3 --- app/routes/planet_routes.py | 54 +++++++++++++++++++++++-------------- 1 file changed, 34 insertions(+), 20 deletions(-) diff --git a/app/routes/planet_routes.py b/app/routes/planet_routes.py index fc665fb68..59b7736ba 100644 --- a/app/routes/planet_routes.py +++ b/app/routes/planet_routes.py @@ -1,4 +1,5 @@ -from flask import Blueprint, jsonify, abort, make_response +from flask import Blueprint, jsonify, abort, make_response, request +from app.models.planet import Planet # class Planet: # def __init__(self, id, name, description, has_moon=None): @@ -15,14 +16,27 @@ # has_moon = self.has_moon, # ) -planets = [ - Planet(1, "Mercury", "terrestrial", False), - Planet(2, "Jupiter", "gaseous", True), - Planet(3, "Earth", "terrestrial", True) -] +# planets = [ +# Planet(1, "Mercury", "terrestrial", False), +# Planet(2, "Jupiter", "gaseous", True), +# Planet(3, "Earth", "terrestrial", True) +# ] bp = Blueprint("planets_bp",__name__, url_prefix="/planets") +@bp.routes("", methods=["POST"]) +def create_planet(): + request_body = request.get_json() + planet = Planet( + name = request_body["name"], + description = request_body["description"], + has_moon = request_body["has_moon"] + ) + db.session.add(planet) + db.session.commit() + + return jsonify(planet.make_dict()), 201 + # GET /planets @bp.route("", methods=["GET"]) def list_planets(): @@ -30,20 +44,20 @@ def list_planets(): return jsonify(list_of_planets) -def validate_planet(id): - try: - id = int(id) - except ValueError: - abort(make_response(jsonify(dict(message=f"planet {id} is invalid")), 400)) +# def validate_planet(id): +# try: +# id = int(id) +# except ValueError: +# abort(make_response(jsonify(dict(message=f"planet {id} is invalid")), 400)) - for planet in planets: - if planet.id == id: - return planet +# for planet in planets: +# if planet.id == id: +# return planet - abort(make_response(jsonify(dict(message=f"planet {id} not found")), 404)) +# abort(make_response(jsonify(dict(message=f"planet {id} not found")), 404)) -# GET planets/id -@bp.route("/", methods=["GET"]) -def get_planet(id): - planet = validate_planet(id) - return jsonify(planet.make_dict()) \ No newline at end of file +# # GET planets/id +# @bp.route("/", methods=["GET"]) +# def get_planet(id): +# planet = validate_planet(id) +# return jsonify(planet.make_dict()) \ No newline at end of file From 95ecda0a21bca1afd7892739e3201bfd4594a0d5 Mon Sep 17 00:00:00 2001 From: Shannon Bellemore Date: Sat, 30 Apr 2022 23:09:57 -0500 Subject: [PATCH 09/15] wave 3 --- app/__init__.py | 3 +- app/models/planet.py | 8 +- app/routes/planet_routes.py | 11 ++- migrations/README | 1 + migrations/alembic.ini | 45 +++++++++ migrations/env.py | 96 +++++++++++++++++++ migrations/script.py.mako | 24 +++++ .../versions/0909b759653b_add_planet_model.py | 34 +++++++ 8 files changed, 213 insertions(+), 9 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 create mode 100644 migrations/versions/0909b759653b_add_planet_model.py diff --git a/app/__init__.py b/app/__init__.py index 247401996..e6dec1231 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -13,7 +13,8 @@ def create_app(test_config=None): db.init_app(app) migrate.init_app(app, db) - + + # Register Blueprints from .routes import planet_routes app.register_blueprint(planet_routes.bp) diff --git a/app/models/planet.py b/app/models/planet.py index 18919ae92..b40729251 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -8,8 +8,8 @@ class Planet(db.Model): def make_dict(self): return dict( - id = self.id, - name = self.name, - description = self.description, - has_moon = self.has_moon, + id=self.id, + name=self.name, + description=self.description, + has_moon=self.has_moon, ) diff --git a/app/routes/planet_routes.py b/app/routes/planet_routes.py index 59b7736ba..e053abc88 100644 --- a/app/routes/planet_routes.py +++ b/app/routes/planet_routes.py @@ -1,5 +1,6 @@ from flask import Blueprint, jsonify, abort, make_response, request from app.models.planet import Planet +from app import db # class Planet: # def __init__(self, id, name, description, has_moon=None): @@ -17,14 +18,15 @@ # ) # planets = [ -# Planet(1, "Mercury", "terrestrial", False), -# Planet(2, "Jupiter", "gaseous", True), -# Planet(3, "Earth", "terrestrial", True) +# Planet(1, "Mercury", description="terrestrial", has_moon=False), +# Planet(2, "Jupiter", description="gaseous", has_moon=True), +# Planet(3, "Earth", description="terrestrial", has_moon=True) # ] bp = Blueprint("planets_bp",__name__, url_prefix="/planets") -@bp.routes("", methods=["POST"]) +# POST /planets +@bp.route("", methods=["POST"]) def create_planet(): request_body = request.get_json() planet = Planet( @@ -40,6 +42,7 @@ def create_planet(): # GET /planets @bp.route("", methods=["GET"]) def list_planets(): + planets = Planet.query.all() list_of_planets = [planet.make_dict() for planet in planets] return jsonify(list_of_planets) 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/0909b759653b_add_planet_model.py b/migrations/versions/0909b759653b_add_planet_model.py new file mode 100644 index 000000000..d856186a3 --- /dev/null +++ b/migrations/versions/0909b759653b_add_planet_model.py @@ -0,0 +1,34 @@ +"""add planet model + +Revision ID: 0909b759653b +Revises: +Create Date: 2022-04-30 22:05:20.168921 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '0909b759653b' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('planet', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('description', sa.String(), nullable=False), + sa.Column('has_moon', sa.Boolean(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('planet') + # ### end Alembic commands ### From 4f41dfd9ae77f766de6bd214b49d1897c13d122b Mon Sep 17 00:00:00 2001 From: Hillary Smith Date: Tue, 3 May 2022 11:10:10 -0700 Subject: [PATCH 10/15] finished wave 4 --- app/routes/planet_routes.py | 67 +++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/app/routes/planet_routes.py b/app/routes/planet_routes.py index e053abc88..c4d682f26 100644 --- a/app/routes/planet_routes.py +++ b/app/routes/planet_routes.py @@ -1,3 +1,4 @@ +import re from flask import Blueprint, jsonify, abort, make_response, request from app.models.planet import Planet from app import db @@ -47,6 +48,72 @@ def list_planets(): return jsonify(list_of_planets) + +# GET /planets/ + +@bp.route("/", methods=["GET"]) +def get_planet_by_id(planet_id): + planet = get_planet_record_by_id(planet_id) + return jsonify(planet.make_dict()) + +# PUT /planets/ +@bp.route("/", methods=["PUT"]) +def replace_planet_by_id(planet_id): + request_body = request.get_json() + planet = get_planet_record_by_id(planet_id) + + planet.name = request_body["name"] + planet.description = request_body["description"] + planet.has_moon = request_body["has_moon"] + + db.session.commit() + + return jsonify(planet.make_dict()) + +# DELETE /planets/ +@bp.route("/", methods=["DELETE"]) +def delete_planet_by_id(planet_id): + planet = get_planet_record_by_id(planet_id) + + db.session.delete(planet) + db.session.commit() + + return make_response(f"Planet with id {planet_id} successfully deleted") + +# PATCH /planets/ +@bp.route("/", methods=["PATCH"]) +def update_planet_by_id(planet_id): + request_body = request.get_json() + planet = get_planet_record_by_id(planet_id) + planet_keys = request_body.keys() + + if "name" in planet_keys: + planet.name = request_body["name"] + if "description" in planet_keys: + planet.description = request_body["description"] + if "has_moon" in planet_keys: + planet.has_moon = request_body["has_moon"] + + db.session.commit() + return jsonify(planet.make_dict()) + +# helper function +def get_planet_record_by_id(id): + try: + id = int(id) + except ValueError: + abort(make_response(jsonify(dict(details=f"Invalid planet id {id}")), 400)) + + planet = Planet.query.get(id) + + if planet: + return planet + + abort(make_response(jsonify(dict(details=f"No planet with id {id} found")), 404)) + + + + # def validate_planet(id): # try: # id = int(id) From 4c525f26bc497494ed19c36b87166a99a22ed25a Mon Sep 17 00:00:00 2001 From: Shannon Bellemore Date: Wed, 4 May 2022 22:20:15 -0500 Subject: [PATCH 11/15] refactor, added class method, error function --- app/models/planet.py | 9 +++++++++ app/routes/planet_routes.py | 26 ++++++++++++++++++-------- 2 files changed, 27 insertions(+), 8 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index b40729251..f661ba305 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -13,3 +13,12 @@ def make_dict(self): description=self.description, has_moon=self.has_moon, ) + + # ************************* + @classmethod + def from_dict(cls, data_dict): + return cls( + name = data_dict["name"], + description = data_dict["description"], + has_moon = data_dict["has_moon"] + ) diff --git a/app/routes/planet_routes.py b/app/routes/planet_routes.py index c4d682f26..c324e726b 100644 --- a/app/routes/planet_routes.py +++ b/app/routes/planet_routes.py @@ -26,15 +26,19 @@ bp = Blueprint("planets_bp",__name__, url_prefix="/planets") +def error_message(message, status_code): + abort(make_response(jsonify(dict(details=message)), status_code)) + # POST /planets @bp.route("", methods=["POST"]) def create_planet(): request_body = request.get_json() - planet = Planet( - name = request_body["name"], - description = request_body["description"], - has_moon = request_body["has_moon"] - ) + + try: + planet = Planet.from_dict(request_body) + except KeyError as error: + error_message(f"Missing key: {error}", 400) + db.session.add(planet) db.session.commit() @@ -43,7 +47,13 @@ def create_planet(): # GET /planets @bp.route("", methods=["GET"]) def list_planets(): - planets = Planet.query.all() + description_param = request.args.get("description") + + if description_param: + planets = Planet.query.filter_by(description=description_param) + else: + planets = Planet.query.all() + list_of_planets = [planet.make_dict() for planet in planets] return jsonify(list_of_planets) @@ -102,14 +112,14 @@ def get_planet_record_by_id(id): try: id = int(id) except ValueError: - abort(make_response(jsonify(dict(details=f"Invalid planet id {id}")), 400)) + error_message(f"Invalid planet id {id}", 400) planet = Planet.query.get(id) if planet: return planet - abort(make_response(jsonify(dict(details=f"No planet with id {id} found")), 404)) + error_message(f"No planet with id {id} found", 404) From 9b70983825222be71ae8db70e1c87f034b237e52 Mon Sep 17 00:00:00 2001 From: Hillary Smith Date: Thu, 5 May 2022 08:27:51 -0700 Subject: [PATCH 12/15] refactoring --- app/models/planet.py | 15 +++++++++++++++ app/routes/planet_routes.py | 31 ++++++++++++++----------------- 2 files changed, 29 insertions(+), 17 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index f661ba305..dbe59bbe3 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -13,7 +13,22 @@ def make_dict(self): description=self.description, has_moon=self.has_moon, ) + + def replace_all_details(self, data_dict): + self.name = data_dict["name"] + self.description = data_dict["description"] + self.has_moon = data_dict["has_moon"] + def replace_some_details(self, data_dict): + planet_keys = data_dict.keys() + + if "name" in planet_keys: + self.name = data_dict["name"] + if "description" in planet_keys: + self.description = data_dict["description"] + if "has_moon" in planet_keys: + self.has_moon = data_dict["has_moon"] + # ************************* @classmethod def from_dict(cls, data_dict): diff --git a/app/routes/planet_routes.py b/app/routes/planet_routes.py index c324e726b..672a7efdf 100644 --- a/app/routes/planet_routes.py +++ b/app/routes/planet_routes.py @@ -1,4 +1,3 @@ -import re from flask import Blueprint, jsonify, abort, make_response, request from app.models.planet import Planet from app import db @@ -48,9 +47,15 @@ def create_planet(): @bp.route("", methods=["GET"]) def list_planets(): description_param = request.args.get("description") - + name_param = request.args.get("name") + has_moon_param = request.args.get("has_moon") + if description_param: planets = Planet.query.filter_by(description=description_param) + elif name_param: + planets = Planet.query.filter_by(name=name_param) + elif has_moon_param: + planets = Planet.query.filter_by(has_moon=has_moon_param) else: planets = Planet.query.all() @@ -60,7 +65,6 @@ def list_planets(): # GET /planets/ - @bp.route("/", methods=["GET"]) def get_planet_by_id(planet_id): planet = get_planet_record_by_id(planet_id) @@ -71,11 +75,12 @@ def get_planet_by_id(planet_id): def replace_planet_by_id(planet_id): request_body = request.get_json() planet = get_planet_record_by_id(planet_id) - - planet.name = request_body["name"] - planet.description = request_body["description"] - planet.has_moon = request_body["has_moon"] - + + try: + planet.replace_all_details(request_body) + except KeyError as error: + error_message(f"Missing key: {error}", 400) + db.session.commit() return jsonify(planet.make_dict()) @@ -95,15 +100,7 @@ def delete_planet_by_id(planet_id): def update_planet_by_id(planet_id): request_body = request.get_json() planet = get_planet_record_by_id(planet_id) - planet_keys = request_body.keys() - - if "name" in planet_keys: - planet.name = request_body["name"] - if "description" in planet_keys: - planet.description = request_body["description"] - if "has_moon" in planet_keys: - planet.has_moon = request_body["has_moon"] - + planet.replace_some_details(request_body) db.session.commit() return jsonify(planet.make_dict()) From f8682b76297185e46c8425cda63cf5f7f6a645f4 Mon Sep 17 00:00:00 2001 From: Hillary Smith Date: Thu, 5 May 2022 11:11:21 -0700 Subject: [PATCH 13/15] set up for testing completed --- app/__init__.py | 16 ++++++++++++---- tests/__init__.py | 0 tests/conftest.py | 25 +++++++++++++++++++++++++ tests/test_routes.py | 0 4 files changed, 37 insertions(+), 4 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 e6dec1231..dcb7c8d2a 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,21 +1,29 @@ from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate +from dotenv import load_dotenv +import os db = SQLAlchemy() migrate = Migrate() +load_dotenv def create_app(test_config=None): app = Flask(__name__) - app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False - app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system_development' - + if not test_config: + app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("SQLALCHEMY_DATABASE_URI") + else: + app.config["TESTING"] = True + app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("SQLALCHEMY_TEST_DATABASE_URI") + db.init_app(app) migrate.init_app(app, db) # Register Blueprints - from .routes import planet_routes + from .routes import planet_routes #is this better or worse than following the way in Learn which separates Planet model import and bp app.register_blueprint(planet_routes.bp) return app 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..ac8a4193b --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,25 @@ +import pytest +from app import create_app +from app import db +from flask.signals import request_finished + + +@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() \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py new file mode 100644 index 000000000..e69de29bb From 2715ec702d0d9e1d7d2eac8ade7692e9711d9a0b Mon Sep 17 00:00:00 2001 From: Hillary Smith Date: Thu, 5 May 2022 13:55:34 -0700 Subject: [PATCH 14/15] wrote first two tests --- app/__init__.py | 2 +- tests/conftest.py | 12 +++++++++++- tests/test_routes.py | 22 ++++++++++++++++++++++ 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index dcb7c8d2a..2f263ea2d 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -6,7 +6,7 @@ db = SQLAlchemy() migrate = Migrate() -load_dotenv +load_dotenv() def create_app(test_config=None): app = Flask(__name__) diff --git a/tests/conftest.py b/tests/conftest.py index ac8a4193b..8c34ea1c9 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 @@ -22,4 +23,13 @@ def expire_session(sender, response, **extra): @pytest.fixture def client(app): - return app.test_client() \ No newline at end of file + return app.test_client() + +@pytest.fixture +def two_planets(app): + tatooine = Planet(id=1, name="Tatooine", description="desert", has_moon=True) + hoth = Planet(id=2, name="Hoth", description="icy tundra", has_moon=True) + + db.session.add(tatooine) + db.session.add(hoth) + db.session.commit() \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py index e69de29bb..d39d913b7 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -0,0 +1,22 @@ +import pytest + + +def test_get_all_planets_with_empty_db_return_empty_list(client): + response = client.get('/planets') + + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == [] + +def test_get_one_planet(client, two_planets): + response = client.get("planets/1") + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == { + "id": 1, + "name": "Tatooine", + "description": "desert", + "has_moon": True + } \ No newline at end of file From 32a4b6e80e359cc823c56e6fc2353f4acf558fda Mon Sep 17 00:00:00 2001 From: Hillary Smith Date: Thu, 5 May 2022 16:58:29 -0700 Subject: [PATCH 15/15] finished tests --- app/__init__.py | 2 +- app/routes/planet_routes.py | 73 +++++++++---------------------------- tests/test_routes.py | 54 ++++++++++++++++++++++++--- 3 files changed, 66 insertions(+), 63 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 2f263ea2d..56c8a1107 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -23,7 +23,7 @@ def create_app(test_config=None): migrate.init_app(app, db) # Register Blueprints - from .routes import planet_routes #is this better or worse than following the way in Learn which separates Planet model import and bp + from .routes import planet_routes app.register_blueprint(planet_routes.bp) return app diff --git a/app/routes/planet_routes.py b/app/routes/planet_routes.py index 672a7efdf..283875598 100644 --- a/app/routes/planet_routes.py +++ b/app/routes/planet_routes.py @@ -2,29 +2,22 @@ from app.models.planet import Planet from app import db -# class Planet: -# def __init__(self, id, name, description, has_moon=None): -# self.id = id -# self.name = name -# self.description = description -# self.has_moon = has_moon - -# def make_dict(self): -# return dict( -# id = self.id, -# name = self.name, -# description = self.description, -# has_moon = self.has_moon, -# ) - -# planets = [ -# Planet(1, "Mercury", description="terrestrial", has_moon=False), -# Planet(2, "Jupiter", description="gaseous", has_moon=True), -# Planet(3, "Earth", description="terrestrial", has_moon=True) -# ] - bp = Blueprint("planets_bp",__name__, url_prefix="/planets") +# helper functions +def get_planet_record_by_id(id): + try: + id = int(id) + except ValueError: + error_message(f"Invalid planet id {id}", 400) + + planet = Planet.query.get(id) + + if planet: + return planet + + error_message(f"No planet with id {id} found", 404) + def error_message(message, status_code): abort(make_response(jsonify(dict(details=message)), status_code)) @@ -68,6 +61,7 @@ def list_planets(): @bp.route("/", methods=["GET"]) def get_planet_by_id(planet_id): planet = get_planet_record_by_id(planet_id) + return jsonify(planet.make_dict()) # PUT /planets/ @@ -101,40 +95,7 @@ def update_planet_by_id(planet_id): request_body = request.get_json() planet = get_planet_record_by_id(planet_id) planet.replace_some_details(request_body) - db.session.commit() - return jsonify(planet.make_dict()) - -# helper function -def get_planet_record_by_id(id): - try: - id = int(id) - except ValueError: - error_message(f"Invalid planet id {id}", 400) - - planet = Planet.query.get(id) - if planet: - return planet + db.session.commit() - error_message(f"No planet with id {id} found", 404) - - - - -# def validate_planet(id): -# try: -# id = int(id) -# except ValueError: -# abort(make_response(jsonify(dict(message=f"planet {id} is invalid")), 400)) - -# for planet in planets: -# if planet.id == id: -# return planet - -# abort(make_response(jsonify(dict(message=f"planet {id} not found")), 404)) - -# # GET planets/id -# @bp.route("/", methods=["GET"]) -# def get_planet(id): -# planet = validate_planet(id) -# return jsonify(planet.make_dict()) \ No newline at end of file + return jsonify(planet.make_dict()) \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py index d39d913b7..95b15e096 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -1,6 +1,4 @@ -import pytest - - +# Test GET /planets def test_get_all_planets_with_empty_db_return_empty_list(client): response = client.get('/planets') @@ -9,8 +7,28 @@ def test_get_all_planets_with_empty_db_return_empty_list(client): assert response.status_code == 200 assert response_body == [] -def test_get_one_planet(client, two_planets): - response = client.get("planets/1") +# Test GET /planets +def test_get_all_planets_using_fixture(client, two_planets): + response = client.get('/planets') + + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == [{ + "id": 1, + "name": "Tatooine", + "description": "desert", + "has_moon": True}, + {"id": 2, + "name": "Hoth", + "description": "icy tundra", + "has_moon": True + }] + +# Test GET /planets/ +def test_get_one_planet_using_fixture(client, two_planets): + response = client.get("/planets/1") + response_body = response.get_json() assert response.status_code == 200 @@ -19,4 +37,28 @@ def test_get_one_planet(client, two_planets): "name": "Tatooine", "description": "desert", "has_moon": True - } \ No newline at end of file + } + +# Test GET /planets/ +def test_get_one_planet_no_db_data_return_404(client): + response = client.get("/planets/1") + + assert response.status_code == 404 + +# Test POST /planets +def test_post_one_planet(client): + response = client.post("/planets", json={ + "name": "Endor", + "description": "Blue gas giant", + "has_moon": True + }) + + response_body=response.get_json() + + assert response.status_code == 201 + assert response_body == { + "id": 1, + "name": "Endor", + "description": "Blue gas giant", + "has_moon": True + } \ No newline at end of file