From 601d1d09a428810b3ebf1f2257e7188997de8a48 Mon Sep 17 00:00:00 2001 From: Jackie Date: Tue, 2 May 2023 14:58:37 -0400 Subject: [PATCH 1/8] Wave 1 commit. Planet class defined and list of planet instances created. Planets endpoint created. --- app/__init__.py | 3 +++ app/routes.py | 32 +++++++++++++++++++++++++++++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..ab9eee40e 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -4,4 +4,7 @@ def create_app(test_config=None): app = Flask(__name__) + from .routes import planets_bp + app.register_blueprint(planets_bp) + return app diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..0ab8d382b 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,32 @@ -from flask import Blueprint +from flask import Blueprint, jsonify + +class Planet: + def __init__(self, id, name, description): + self.id = id + self.name = name + self.description = description + +planets = [ + Planet(1, "Mercury", "Terrestrial planet closest to the sun. Smallest planet."), + Planet(2, "Venus", "Terrestrial planet second from sun. Hot surface."), + Planet(3, "Earth", "Third planet from the sun. Largest terrestrial planet."), + Planet(4, "Mars", "Terrestrial planet fourth from the sun. Red planet."), + Planet(5, "Jupiter", "First gas giant planet from the sun. Largest planet."), + Planet(6, "Saturn", "Sixth planet from the sun. Gas giant planet with rings."), + Planet(7, "Uranus", "Seventh planet from the sun. Ice giant planet."), + Planet(8, "Neptune", "Furthest planet from the sun. Cold, blue gas giant planet.") +] + +planets_bp = Blueprint("planets", __name__, url_prefix="/planets") + +@planets_bp.route("", methods=["GET"]) +def handle_planets(): + planets_response = [] + for planet in planets: + planets_response.append({ + "id": planet.id, + "name": planet.name, + "description": planet.description + }) + return jsonify(planets_response) From 8ed497fb26cd3f24afe627612345c5befe68e8fd Mon Sep 17 00:00:00 2001 From: Jackie Date: Tue, 2 May 2023 15:22:43 -0400 Subject: [PATCH 2/8] wave 2 commit. Endpoint created to read one planet. Error handling for non-integer planet id and non-existing planet addressed. --- app/routes.py | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index 0ab8d382b..9e99d25e4 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: @@ -30,3 +30,26 @@ def handle_planets(): "description": planet.description }) return jsonify(planets_response) + +def validate_planet(planet_id): + try: + planet_id = int(planet_id) + except: + abort(make_response({"message":f"planet {planet_id} invalid"}, 400)) + + for planet in planets: + if planet_id == planet.id: + return planet + + abort(make_response({"message":f"planet {planet_id} not found"}, 404)) + + +@planets_bp.route("/", methods=["GET"]) +def handle_planet(planet_id): + planet = validate_planet(planet_id) + + return { + "id": planet.id, + "name": planet.name, + "description": planet.description, + } From 230a21f3865a6a6396aab720794a077cc859a648 Mon Sep 17 00:00:00 2001 From: Jackie Date: Tue, 2 May 2023 21:22:59 -0400 Subject: [PATCH 3/8] Third wave commit. Includes Planet model, endpoint to create model record, and refactored endpoint to get all records from database table. --- app/__init__.py | 13 ++ app/models/__init__.py | 0 app/models/planet.py | 7 ++ app/routes.py | 118 +++++++++++------- migrations/README | 1 + migrations/alembic.ini | 45 +++++++ migrations/env.py | 96 ++++++++++++++ migrations/script.py.mako | 24 ++++ .../a91d71893aa5_adds_planet_model.py | 33 +++++ 9 files changed, 291 insertions(+), 46 deletions(-) create mode 100644 app/models/__init__.py create mode 100644 app/models/planet.py create mode 100644 migrations/README create mode 100644 migrations/alembic.ini create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/a91d71893aa5_adds_planet_model.py diff --git a/app/__init__.py b/app/__init__.py index ab9eee40e..3a90d4c9d 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,10 +1,23 @@ 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 planets_bp app.register_blueprint(planets_bp) + return app diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/app/models/planet.py b/app/models/planet.py new file mode 100644 index 000000000..eb74308a6 --- /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) \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 9e99d25e4..e15b89414 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,55 +1,81 @@ -from flask import Blueprint, jsonify, abort, make_response - - -class Planet: - def __init__(self, id, name, description): - self.id = id - self.name = name - self.description = description - -planets = [ - Planet(1, "Mercury", "Terrestrial planet closest to the sun. Smallest planet."), - Planet(2, "Venus", "Terrestrial planet second from sun. Hot surface."), - Planet(3, "Earth", "Third planet from the sun. Largest terrestrial planet."), - Planet(4, "Mars", "Terrestrial planet fourth from the sun. Red planet."), - Planet(5, "Jupiter", "First gas giant planet from the sun. Largest planet."), - Planet(6, "Saturn", "Sixth planet from the sun. Gas giant planet with rings."), - Planet(7, "Uranus", "Seventh planet from the sun. Ice giant planet."), - Planet(8, "Neptune", "Furthest planet from the sun. Cold, blue gas giant planet.") -] +from app import db +from app.models.planet import Planet +from flask import Blueprint, jsonify, abort, make_response, request, Response + + +# class Planet: +# def __init__(self, id, name, description): +# self.id = id +# self.name = name +# self.description = description + +# planets = [ +# Planet(1, "Mercury", "Terrestrial planet closest to the sun. Smallest planet."), +# Planet(2, "Venus", "Terrestrial planet second from sun. Hot surface."), +# Planet(3, "Earth", "Third planet from the sun. Largest terrestrial planet."), +# Planet(4, "Mars", "Terrestrial planet fourth from the sun. Red planet."), +# Planet(5, "Jupiter", "First gas giant planet from the sun. Largest planet."), +# Planet(6, "Saturn", "Sixth planet from the sun. Gas giant planet with rings."), +# Planet(7, "Uranus", "Seventh planet from the sun. Ice giant planet."), +# Planet(8, "Neptune", "Furthest planet from the sun. Cold, blue gas giant planet.") +# ] planets_bp = Blueprint("planets", __name__, url_prefix="/planets") -@planets_bp.route("", methods=["GET"]) +@planets_bp.route("", methods=["GET", "POST"]) def handle_planets(): - planets_response = [] - for planet in planets: - planets_response.append({ - "id": planet.id, - "name": planet.name, - "description": planet.description - }) - return jsonify(planets_response) - -def validate_planet(planet_id): - try: - planet_id = int(planet_id) - except: - abort(make_response({"message":f"planet {planet_id} invalid"}, 400)) + if request.method == "GET": + planets = Planet.query.all() + planets_response = [] + for planet in planets: + planets_response.append({ + "id": planet.id, + "name": planet.name, + "description": planet.description + }) + return jsonify(planets_response) - for planet in planets: - if planet_id == planet.id: - return planet + elif request.method == "POST": + request_body = request.get_json() + new_planet = Planet(name=request_body["name"], + description=request_body["description"]) + + db.session.add(new_planet) + db.session.commit() + + return make_response(f"Planet {new_planet.name} successfully created", 201) + + +# def validate_planet(planet_id): +# try: +# planet_id = int(planet_id) +# except: +# abort(make_response({"message":f"planet {planet_id} invalid"}, 400)) + +# for planet in planets: +# if planet_id == planet.id: +# return planet - abort(make_response({"message":f"planet {planet_id} not found"}, 404)) +# abort(make_response({"message":f"planet {planet_id} not found"}, 404)) -@planets_bp.route("/", methods=["GET"]) -def handle_planet(planet_id): - planet = validate_planet(planet_id) +# @planets_bp.route("/", methods=["GET"]) +# def handle_planet(planet_id): +# planet = validate_planet(planet_id) - return { - "id": planet.id, - "name": planet.name, - "description": planet.description, - } +# return { +# "id": planet.id, +# "name": planet.name, +# "description": planet.description, + # } + +# @planets_bp.route("", methods=["POST"]) +# def create_planet(): +# request_body = request.get_json() +# new_planet = Planet(name=request_body["name"], +# description=request_body["description"]) + +# db.session.add(new_planet) +# db.session.commit() + +# return make_response(f"Planet {new_planet.name} successfully created", 201) \ 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/a91d71893aa5_adds_planet_model.py b/migrations/versions/a91d71893aa5_adds_planet_model.py new file mode 100644 index 000000000..e5f295dc7 --- /dev/null +++ b/migrations/versions/a91d71893aa5_adds_planet_model.py @@ -0,0 +1,33 @@ +"""adds Planet model + +Revision ID: a91d71893aa5 +Revises: +Create Date: 2023-05-02 17:28:23.061054 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'a91d71893aa5' +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 ### From 469087a28764a12fa60c35b49648475cf2a9f5aa Mon Sep 17 00:00:00 2001 From: Jackie Date: Tue, 2 May 2023 21:57:12 -0400 Subject: [PATCH 4/8] Fourth wave commit. Endpoints added to read, delete, and update one planet. --- app/routes.py | 54 ++++++++++++++++++++++++++++++++++----------------- 1 file changed, 36 insertions(+), 18 deletions(-) diff --git a/app/routes.py b/app/routes.py index e15b89414..0696fbfd6 100644 --- a/app/routes.py +++ b/app/routes.py @@ -46,28 +46,46 @@ def handle_planets(): return make_response(f"Planet {new_planet.name} successfully created", 201) -# def validate_planet(planet_id): -# try: -# planet_id = int(planet_id) -# except: -# abort(make_response({"message":f"planet {planet_id} invalid"}, 400)) +def validate_planet(planet_id): + try: + planet_id = int(planet_id) + except: + abort(make_response({"message":f"planet {planet_id} invalid"}, 400)) -# for planet in planets: -# if planet_id == planet.id: -# return planet - -# abort(make_response({"message":f"planet {planet_id} not found"}, 404)) + planet = Planet.query.get(planet_id) + + if not planet: + abort(make_response({"message":f"planet {planet_id} not found"}, 404)) + return planet -# @planets_bp.route("/", methods=["GET"]) -# def handle_planet(planet_id): -# planet = validate_planet(planet_id) + +@planets_bp.route("/", methods=["GET", "PUT", "DELETE"]) +def handle_one_planet(planet_id): + planet = validate_planet(planet_id) -# return { -# "id": planet.id, -# "name": planet.name, -# "description": planet.description, - # } + if request.method == "GET": + return { + "id": planet.id, + "name": planet.name, + "description": planet.description, + } + + elif request.method == "PUT": + request_body = request.get_json() + + planet.name = request_body["name"] + planet.description = request_body["description"] + + db.session.commit() + + return make_response(f"Planet #{planet.id} successfully updated") + + elif request.method == "DELETE": + db.session.delete(planet) + db.session.commit() + + return make_response(f"Planet #{planet.id} successfully deleted") # @planets_bp.route("", methods=["POST"]) # def create_planet(): From eacf8d2dcb0901bb0d55ae978597f4063a4526e4 Mon Sep 17 00:00:00 2001 From: Jackie Date: Thu, 4 May 2023 06:14:46 -0400 Subject: [PATCH 5/8] Wave 06 commit. Test fixtures and tests created. --- app/__init__.py | 10 +++++++-- app/routes.py | 2 +- tests/__init__.py | 0 tests/conftest.py | 38 +++++++++++++++++++++++++++++++ tests/test_routes.py | 53 ++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 100 insertions(+), 3 deletions(-) create mode 100644 tests/__init__.py create mode 100644 tests/conftest.py create mode 100644 tests/test_routes.py diff --git a/app/__init__.py b/app/__init__.py index 3a90d4c9d..d217f8710 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,16 +1,22 @@ 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_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI') + 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/routes.py b/app/routes.py index 0696fbfd6..5a78ad95c 100644 --- a/app/routes.py +++ b/app/routes.py @@ -43,7 +43,7 @@ def handle_planets(): 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) def validate_planet(planet_id): 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..196455c5f --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,38 @@ +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 + planet_mars = Planet(name="Mars", + description="Smallest planet") + planet_jupiter = Planet(name="Jupiter", + description="Largest planet") + + db.session.add_all([planet_mars, planet_jupiter]) + + db.session.commit() \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py new file mode 100644 index 000000000..46cf8181a --- /dev/null +++ b/tests/test_routes.py @@ -0,0 +1,53 @@ +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": "Smallest planet" + } + + +def test_get_one_planet_no_data_returns_404(client): + # Act + response = client.get("/planets/1") + response_body = response.get_json() + + # Assert + 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": "Smallest planet" + }, + { + "id": 2, + "name": "Jupiter", + "description": "Largest planet" + }] + + +def test_create_one_planet(client): + # Act + response = client.post("/planets", json={ + "name": "Earth", + "description": "Water planet" + }) + response_body = response.get_json() + + # Assert + assert response.status_code == 201 + assert response_body == "Planet Earth successfully created" \ No newline at end of file From 994f9e9e5fcf3b0c8476b3e6b807ef11ff69d8f8 Mon Sep 17 00:00:00 2001 From: Jackie Date: Thu, 4 May 2023 12:35:33 -0400 Subject: [PATCH 6/8] Wave 06 updated to fix broken code in create_app method --- app/__init__.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index d217f8710..b3f67fc87 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -13,10 +13,17 @@ def create_app(test_config=None): app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False - if not test_config: - app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI') - app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_TEST_DATABASE_URI') + # if not test_config: + # app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI') + # app.config['SQLALCHEMY_TEST_DATABASE_URI'] = os.environ.get('SQLALCHEMY_TEST_DATABASE_URI') + if not test_config: + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get( + "SQLALCHEMY_DATABASE_URI") + else: + app.config["TESTING"] = True + app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( + "SQLALCHEMY_TEST_DATABASE_URI") db.init_app(app) migrate.init_app(app, db) From 5a129a6bdf3b3882ef9811788906c0bd28191ff6 Mon Sep 17 00:00:00 2001 From: Jackie Date: Thu, 4 May 2023 13:20:41 -0400 Subject: [PATCH 7/8] Wave 6 --- app/__init__.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index b3f67fc87..8e21a640b 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -13,10 +13,6 @@ def create_app(test_config=None): app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False - # if not test_config: - # app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI') - # app.config['SQLALCHEMY_TEST_DATABASE_URI'] = os.environ.get('SQLALCHEMY_TEST_DATABASE_URI') - if not test_config: app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get( "SQLALCHEMY_DATABASE_URI") From b9808d44230fce97f0672ceb90f9a6cf6b6bc997 Mon Sep 17 00:00:00 2001 From: Jackie Date: Thu, 4 May 2023 17:30:48 -0400 Subject: [PATCH 8/8] Wave 5 commit. Endpoints tested using Postman. Code refactored to use query params to get a planet by name. --- app/routes.py | 38 ++++++++------------------------------ 1 file changed, 8 insertions(+), 30 deletions(-) diff --git a/app/routes.py b/app/routes.py index 5a78ad95c..ce585641d 100644 --- a/app/routes.py +++ b/app/routes.py @@ -2,30 +2,18 @@ from app.models.planet import Planet from flask import Blueprint, jsonify, abort, make_response, request, Response - -# class Planet: -# def __init__(self, id, name, description): -# self.id = id -# self.name = name -# self.description = description - -# planets = [ -# Planet(1, "Mercury", "Terrestrial planet closest to the sun. Smallest planet."), -# Planet(2, "Venus", "Terrestrial planet second from sun. Hot surface."), -# Planet(3, "Earth", "Third planet from the sun. Largest terrestrial planet."), -# Planet(4, "Mars", "Terrestrial planet fourth from the sun. Red planet."), -# Planet(5, "Jupiter", "First gas giant planet from the sun. Largest planet."), -# Planet(6, "Saturn", "Sixth planet from the sun. Gas giant planet with rings."), -# Planet(7, "Uranus", "Seventh planet from the sun. Ice giant planet."), -# Planet(8, "Neptune", "Furthest planet from the sun. Cold, blue gas giant planet.") -# ] - planets_bp = Blueprint("planets", __name__, url_prefix="/planets") @planets_bp.route("", methods=["GET", "POST"]) def handle_planets(): if request.method == "GET": - planets = Planet.query.all() + + name_query = request.args.get("name") + if name_query: + planets = Planet.query.filter_by(name=name_query) + else: + planets = Planet.query.all() + planets_response = [] for planet in planets: planets_response.append({ @@ -86,14 +74,4 @@ def handle_one_planet(planet_id): db.session.commit() return make_response(f"Planet #{planet.id} successfully deleted") - -# @planets_bp.route("", methods=["POST"]) -# def create_planet(): -# request_body = request.get_json() -# new_planet = Planet(name=request_body["name"], -# description=request_body["description"]) - -# db.session.add(new_planet) -# db.session.commit() - -# return make_response(f"Planet {new_planet.name} successfully created", 201) \ No newline at end of file + \ No newline at end of file