From 2d33ee9296df80f9c64fe7ac697ece097cc5e4fc Mon Sep 17 00:00:00 2001 From: Carolyn Qi Date: Thu, 20 Apr 2023 11:33:41 -0700 Subject: [PATCH 01/12] Add routes for planet and moons --- app/__init__.py | 6 +++++ app/routes.py | 58 ++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 63 insertions(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..ca4ca740c 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -3,5 +3,11 @@ def create_app(test_config=None): app = Flask(__name__) + + from .routes import solar_system_planet + app.register_blueprint(solar_system_planet) + + from .routes import solar_system_moon + app.register_blueprint(solar_system_moon) return app diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..dfd7b9c0e 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,58 @@ -from flask import Blueprint +from flask import Blueprint, jsonify + + +class Planet(): + def __init__(self, id, name, radius): + self.id = id + self.name = name + self.radius = radius + +class Moon(): + def __init__(self, id, name, radius, planet): + self.id = id + self.name = name + self.radius = radius + self.planet = planet + +mercury = Planet(1, "mercury", 1516) +venus = Planet(2, "venus", 3760) +earth = Planet(3, "earth", 6371) +mars = Planet(4, "mars", 2106) + +planet_list = [mercury, venus, earth, mars] + +moon = Moon(1, "moon", 1079, earth) +phobos = Moon(2, "phobos", 11, mars) +deimos = Moon(3, "deimos", 6.2, mars) +europa = Moon(4, "europa", 1560, mars) + +moon_list = [moon, phobos, deimos, europa] + +solar_system_planet = Blueprint("solar_system_planet", __name__, url_prefix="/solar_system/planet") + + +@solar_system_planet.route("", methods=["GET"]) +def get_planets(): + return_list = [] + for planet in planet_list: + return_list.append({ + "id": planet.id, + "name": planet.name, + "radius": planet.radius + }) + return jsonify(return_list), 200 + +solar_system_moon = Blueprint("solar_system_moon", __name__, url_prefix="/solar_system/moon") + +@solar_system_moon.route("", methods=["GET"]) +def get_planets(): + return_list = [] + for moon in moon_list: + return_list.append({ + "id": moon.id, + "name": moon.name, + "radius": moon.radius, + "planet name": moon.planet.name + }) + return jsonify(return_list), 200 \ No newline at end of file From 828798646c8f37e7801a37b2803eae35af6963d7 Mon Sep 17 00:00:00 2001 From: Carolyn Qi Date: Thu, 20 Apr 2023 11:42:45 -0700 Subject: [PATCH 02/12] Add description to planets --- app/routes.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/app/routes.py b/app/routes.py index dfd7b9c0e..594e99ca1 100644 --- a/app/routes.py +++ b/app/routes.py @@ -3,10 +3,11 @@ class Planet(): - def __init__(self, id, name, radius): + def __init__(self, id, name, radius, description): self.id = id self.name = name self.radius = radius + self.description = description class Moon(): def __init__(self, id, name, radius, planet): @@ -15,10 +16,10 @@ def __init__(self, id, name, radius, planet): self.radius = radius self.planet = planet -mercury = Planet(1, "mercury", 1516) -venus = Planet(2, "venus", 3760) -earth = Planet(3, "earth", 6371) -mars = Planet(4, "mars", 2106) +mercury = Planet(1, "mercury", 1516, "I am the smallest planet in our solar system") +venus = Planet(2, "venus", 3760, "I spin in the opposite direction from Earth") +earth = Planet(3, "earth", 6371, "I am the densest planet in our solar system") +mars = Planet(4, "mars", 2106, "I am the only planet humans sent rovers on") planet_list = [mercury, venus, earth, mars] @@ -39,7 +40,8 @@ def get_planets(): return_list.append({ "id": planet.id, "name": planet.name, - "radius": planet.radius + "radius": planet.radius, + "description": planet.description }) return jsonify(return_list), 200 From 450cc97b987f4d0acdc8a059a6f8357cdfac5c4e Mon Sep 17 00:00:00 2001 From: Bella Date: Fri, 21 Apr 2023 12:44:15 -0700 Subject: [PATCH 03/12] added remaining planets --- app/routes.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/app/routes.py b/app/routes.py index 594e99ca1..eea709183 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,7 +1,5 @@ from flask import Blueprint, jsonify - - class Planet(): def __init__(self, id, name, radius, description): self.id = id @@ -20,6 +18,10 @@ def __init__(self, id, name, radius, planet): venus = Planet(2, "venus", 3760, "I spin in the opposite direction from Earth") earth = Planet(3, "earth", 6371, "I am the densest planet in our solar system") mars = Planet(4, "mars", 2106, "I am the only planet humans sent rovers on") +jupiter = Planet(5, "jupiter", 43441, "I am more than twice as massive as all the other planets combined") +saturn = Planet(6, "saturn", 36184, "I am the one with the ring") +uranus = Planet(7, "uranus", 15759, "I am the coldest planet in the solar system") +neptune = Planet(8, "neptune", 15299, "I am the only planet in our solar system not visible to the naked eye") planet_list = [mercury, venus, earth, mars] @@ -57,4 +59,5 @@ def get_planets(): "radius": moon.radius, "planet name": moon.planet.name }) - return jsonify(return_list), 200 \ No newline at end of file + return jsonify(return_list), 200 + From 42d8dc67b4510048261b33eeb9e4cd3d3795ce52 Mon Sep 17 00:00:00 2001 From: Carolyn Qi Date: Fri, 21 Apr 2023 14:19:16 -0700 Subject: [PATCH 04/12] Pull one moon and one planet --- app/routes.py | 42 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index eea709183..5d9f2c908 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, radius, description): @@ -47,6 +47,26 @@ def get_planets(): }) return jsonify(return_list), 200 +@solar_system_planet.route("/", methods=["GET"]) +def get_planet_by_id(planet_id): + planet = verify_planet_id(planet_id) + return { + "id": planet.id, + "name": planet.name, + "radius": planet.radius, + "description": planet.description + } + +def verify_planet_id(planet_id): + try: + planet_id = int(planet_id) + except ValueError: + abort(make_response({"message": f"Planet {planet_id} is invalid"}, 400)) + for planet in planet_list: + if planet.id == planet_id: + return planet + abort(make_response({"message": "Planet {planet_id} is not found"}, 404)) + solar_system_moon = Blueprint("solar_system_moon", __name__, url_prefix="/solar_system/moon") @solar_system_moon.route("", methods=["GET"]) @@ -61,3 +81,23 @@ def get_planets(): }) return jsonify(return_list), 200 +@solar_system_moon.route("/", methods=["GET"]) +def get_moon_by_id(moon_id): + moon = verify_moon_id(moon_id) + return { + "id": moon.id, + "name": moon.name, + "radius": moon.radius, + "planet name": moon.planet.name + } + +def verify_moon_id(moon_id): + try: + moon_id = int(moon_id) + except ValueError: + abort(make_response({"message": f"Moon {moon_id} is invalid"}, 400)) + for moon in moon_list: + if moon.id == moon_id: + return moon + abort(make_response({"message": f"Moon {moon_id} is not found"}, 404)) + From 9b9fd5ee831e8d866acb8ccef64bb2d0e9761c32 Mon Sep 17 00:00:00 2001 From: Carolyn Qi Date: Thu, 27 Apr 2023 14:18:16 -0700 Subject: [PATCH 05/12] Add database --- app/__init__.py | 18 +++- app/models/moon.py | 8 ++ app/models/planet.py | 8 ++ app/{ => routes}/routes.py | 77 ++++++++------- migrations/README | 1 + migrations/alembic.ini | 45 +++++++++ migrations/env.py | 96 +++++++++++++++++++ migrations/script.py.mako | 24 +++++ ...d3bd2eba81a_adds_moon_and_planet_models.py | 42 ++++++++ 9 files changed, 280 insertions(+), 39 deletions(-) create mode 100644 app/models/moon.py create mode 100644 app/models/planet.py rename app/{ => routes}/routes.py (57%) 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/4d3bd2eba81a_adds_moon_and_planet_models.py diff --git a/app/__init__.py b/app/__init__.py index ca4ca740c..1bb575580 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,13 +1,27 @@ 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__) - from .routes import solar_system_planet + app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False + app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system_database" + + from .models.moon import Moon + from .models.planet import Planet + + db.init_app(app) + migrate.init_app(app, db) + + from .routes.routes import solar_system_planet app.register_blueprint(solar_system_planet) - from .routes import solar_system_moon + from .routes.routes import solar_system_moon app.register_blueprint(solar_system_moon) return app diff --git a/app/models/moon.py b/app/models/moon.py new file mode 100644 index 000000000..93b770f79 --- /dev/null +++ b/app/models/moon.py @@ -0,0 +1,8 @@ +from app import db + +class Moon(db.Model): + id = db.Column(db.Integer, primary_key = True, autoincrement = True) + name = db.Column(db.String) + radius = db.Column(db.Integer) + planet_id = db.Column(db.Integer) + diff --git a/app/models/planet.py b/app/models/planet.py new file mode 100644 index 000000000..5928614e3 --- /dev/null +++ b/app/models/planet.py @@ -0,0 +1,8 @@ +from app import db + +class Planet(db.Model): + id = db.Column(db.Integer, primary_key = True, autoincrement = True) + name = db.Column(db.String) + radius = db.Column(db.Integer) + description = db.Column(db.Text) + diff --git a/app/routes.py b/app/routes/routes.py similarity index 57% rename from app/routes.py rename to app/routes/routes.py index 5d9f2c908..16da8a291 100644 --- a/app/routes.py +++ b/app/routes/routes.py @@ -1,44 +1,29 @@ -from flask import Blueprint, jsonify, abort, make_response - -class Planet(): - def __init__(self, id, name, radius, description): - self.id = id - self.name = name - self.radius = radius - self.description = description - -class Moon(): - def __init__(self, id, name, radius, planet): - self.id = id - self.name = name - self.radius = radius - self.planet = planet - -mercury = Planet(1, "mercury", 1516, "I am the smallest planet in our solar system") -venus = Planet(2, "venus", 3760, "I spin in the opposite direction from Earth") -earth = Planet(3, "earth", 6371, "I am the densest planet in our solar system") -mars = Planet(4, "mars", 2106, "I am the only planet humans sent rovers on") -jupiter = Planet(5, "jupiter", 43441, "I am more than twice as massive as all the other planets combined") -saturn = Planet(6, "saturn", 36184, "I am the one with the ring") -uranus = Planet(7, "uranus", 15759, "I am the coldest planet in the solar system") -neptune = Planet(8, "neptune", 15299, "I am the only planet in our solar system not visible to the naked eye") - -planet_list = [mercury, venus, earth, mars] - -moon = Moon(1, "moon", 1079, earth) -phobos = Moon(2, "phobos", 11, mars) -deimos = Moon(3, "deimos", 6.2, mars) -europa = Moon(4, "europa", 1560, mars) - -moon_list = [moon, phobos, deimos, europa] +from flask import Blueprint, jsonify, request, make_response, abort +from app import db +from app.models.moon import Moon +from app.models.planet import Planet solar_system_planet = Blueprint("solar_system_planet", __name__, url_prefix="/solar_system/planet") +@solar_system_planet.route("", methods=["POST"]) +def add_planet(): + request_body = request.get_json() + new_planet = Planet( + name = request_body["name"], + radius = request_body["radius"], + description = request_body["description"] + ) + + db.session.add(new_planet) + db.session.commit() + + return make_response({"message": f"Planet {new_planet.name} has been added, with the id: {new_planet.id}"}, 201) @solar_system_planet.route("", methods=["GET"]) def get_planets(): return_list = [] - for planet in planet_list: + all_planets = Planet.query.all() + for planet in all_planets: return_list.append({ "id": planet.id, "name": planet.name, @@ -62,17 +47,34 @@ def verify_planet_id(planet_id): planet_id = int(planet_id) except ValueError: abort(make_response({"message": f"Planet {planet_id} is invalid"}, 400)) - for planet in planet_list: + all_planets = Planet.query.all() + for planet in all_planets: if planet.id == planet_id: return planet abort(make_response({"message": "Planet {planet_id} is not found"}, 404)) solar_system_moon = Blueprint("solar_system_moon", __name__, url_prefix="/solar_system/moon") +@solar_system_moon.route("", methods=["POST"]) +def add_moon(): + request_body = request.get_json() + new_moon = Moon( + name = request_body["name"], + radius = request_body["radius"], + description = request_body["description"], + planet_id = request_body["planet_id"] + ) + + db.session.add(new_moon) + db.session.commit() + + return make_response({"message": f"Planet {new_moon.name} has been added, with the id: {new_moon.id}"}, 201) + @solar_system_moon.route("", methods=["GET"]) def get_planets(): return_list = [] - for moon in moon_list: + all_moons = Moon.query.all() + for moon in all_moons: return_list.append({ "id": moon.id, "name": moon.name, @@ -96,7 +98,8 @@ def verify_moon_id(moon_id): moon_id = int(moon_id) except ValueError: abort(make_response({"message": f"Moon {moon_id} is invalid"}, 400)) - for moon in moon_list: + all_moons = Moon.query.all() + for moon in all_moons: if moon.id == moon_id: return moon abort(make_response({"message": f"Moon {moon_id} is not found"}, 404)) 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/4d3bd2eba81a_adds_moon_and_planet_models.py b/migrations/versions/4d3bd2eba81a_adds_moon_and_planet_models.py new file mode 100644 index 000000000..69c805216 --- /dev/null +++ b/migrations/versions/4d3bd2eba81a_adds_moon_and_planet_models.py @@ -0,0 +1,42 @@ +"""adds Moon and Planet models + +Revision ID: 4d3bd2eba81a +Revises: +Create Date: 2023-04-27 14:13:06.328129 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '4d3bd2eba81a' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('moon', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('name', sa.String(), nullable=True), + sa.Column('radius', sa.Integer(), nullable=True), + sa.Column('planet_id', sa.Integer(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('planet', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('name', sa.String(), nullable=True), + sa.Column('radius', sa.Integer(), nullable=True), + sa.Column('description', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('planet') + op.drop_table('moon') + # ### end Alembic commands ### From ca4752edf9088eeed275570f2c73cfb86b202908 Mon Sep 17 00:00:00 2001 From: Carolyn Qi Date: Mon, 1 May 2023 12:19:47 -0700 Subject: [PATCH 06/12] Added Delete and Put Methods --- app/routes/routes.py | 53 +++++++++++++++++++++++++++++++++++++++----- 1 file changed, 48 insertions(+), 5 deletions(-) diff --git a/app/routes/routes.py b/app/routes/routes.py index 16da8a291..eef003702 100644 --- a/app/routes/routes.py +++ b/app/routes/routes.py @@ -42,6 +42,28 @@ def get_planet_by_id(planet_id): "description": planet.description } +@solar_system_planet.route("/", methods=["DELETE"]) +def delete_planet(planet_id): + planet = verify_planet_id(planet_id) + + db.session.delete(planet) + db.session.commit() + + return make_response({"message": f"Planet {planet.id} has been deleted"}, 200) + +@solar_system_planet.route("/", methods=["PUT"]) +def update(planet_id): + planet = verify_planet_id(planet_id) + request_body = request.get_json() + + planet.name = request_body["name"] + planet.radius = request_body["radius"] + planet.description = request_body["description"] + + db.session.commit() + + return make_response({"message": f"Planet {planet.id} has been updated"}, 200) + def verify_planet_id(planet_id): try: planet_id = int(planet_id) @@ -61,17 +83,16 @@ def add_moon(): new_moon = Moon( name = request_body["name"], radius = request_body["radius"], - description = request_body["description"], planet_id = request_body["planet_id"] ) db.session.add(new_moon) db.session.commit() - return make_response({"message": f"Planet {new_moon.name} has been added, with the id: {new_moon.id}"}, 201) + return make_response({"message": f"Moon {new_moon.name} has been added, with the id: {new_moon.id}"}, 201) @solar_system_moon.route("", methods=["GET"]) -def get_planets(): +def get_moons(): return_list = [] all_moons = Moon.query.all() for moon in all_moons: @@ -79,7 +100,7 @@ def get_planets(): "id": moon.id, "name": moon.name, "radius": moon.radius, - "planet name": moon.planet.name + "planet name": moon.planet_id }) return jsonify(return_list), 200 @@ -90,9 +111,31 @@ def get_moon_by_id(moon_id): "id": moon.id, "name": moon.name, "radius": moon.radius, - "planet name": moon.planet.name + "planet name": moon.planet_id } +@solar_system_moon.route("/", methods=["DELETE"]) +def delete_planet(moon_id): + moon = verify_moon_id(moon_id) + + db.session.delete(moon) + db.session.commit() + + return make_response({"message": f"Moon {moon.id} has been deleted"}, 200) + +@solar_system_moon.route("/", methods=["PUT"]) +def update(moon_id): + moon = verify_moon_id(moon_id) + request_body = request.get_json() + + moon.name = request_body["name"] + moon.radius = request_body["radius"] + moon.planet_id = request_body["planet_id"] + + db.session.commit() + + return make_response({"message": f"Moon {moon.id} has been updated"}, 200) + def verify_moon_id(moon_id): try: moon_id = int(moon_id) From f181cdcf131192a021bd0c5fd348465f4234c808 Mon Sep 17 00:00:00 2001 From: Carolyn Qi Date: Tue, 2 May 2023 10:49:36 -0700 Subject: [PATCH 07/12] Add testing environment and added query param --- app/__init__.py | 9 ++++++++- app/routes/routes.py | 12 ++++++++++-- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 1bb575580..13dddf446 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,16 +1,23 @@ from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate +import os +from dotenv import load_dotenv 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_database" + if not test_config: + app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("SQLALCHEMY_DATABASE_URI") + else: + app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("SQLALCHEMY_TEST_DATABASE_URI") from .models.moon import Moon from .models.planet import Planet diff --git a/app/routes/routes.py b/app/routes/routes.py index eef003702..735323803 100644 --- a/app/routes/routes.py +++ b/app/routes/routes.py @@ -22,7 +22,11 @@ def add_planet(): @solar_system_planet.route("", methods=["GET"]) def get_planets(): return_list = [] - all_planets = Planet.query.all() + name_query = request.args.get("name") + if name_query is None: + all_planets = Planet.query.all() + else: + all_planets = Planet.query.filter_by(name=name_query) for planet in all_planets: return_list.append({ "id": planet.id, @@ -94,7 +98,11 @@ def add_moon(): @solar_system_moon.route("", methods=["GET"]) def get_moons(): return_list = [] - all_moons = Moon.query.all() + name_query = request.args.get("name") + if name_query is None: + all_moons = Moon.query.all() + else: + all_moons = Moon.query.filterby(name=name_query) for moon in all_moons: return_list.append({ "id": moon.id, From d64a830f11b09341f44f3322815af6c316ed94de Mon Sep 17 00:00:00 2001 From: Carolyn Qi Date: Tue, 2 May 2023 11:03:39 -0700 Subject: [PATCH 08/12] Add multiple params: now adding radius min --- app/routes/routes.py | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/app/routes/routes.py b/app/routes/routes.py index 735323803..478312fde 100644 --- a/app/routes/routes.py +++ b/app/routes/routes.py @@ -23,10 +23,15 @@ def add_planet(): def get_planets(): return_list = [] name_query = request.args.get("name") - if name_query is None: + radius_query = request.args.get("radius_min") + if not name_query and not radius_query: all_planets = Planet.query.all() - else: - all_planets = Planet.query.filter_by(name=name_query) + elif name_query and radius_query: + all_planets = Planet.query.filter(Planet.name==name_query, Planet.radius>=radius_query) + elif radius_query: + all_planets = Planet.query.filter(Planet.radius>=radius_query) + elif name_query: + all_planets = Planet.query.filter(Planet.name==name_query) for planet in all_planets: return_list.append({ "id": planet.id, @@ -99,10 +104,15 @@ def add_moon(): def get_moons(): return_list = [] name_query = request.args.get("name") - if name_query is None: + radius_query = request.args.get("radius_min") + if not name_query and not radius_query: all_moons = Moon.query.all() - else: - all_moons = Moon.query.filterby(name=name_query) + elif name_query and radius_query: + all_moons = Moon.query.filter(Moon.name==name_query, Moon.radius>=radius_query) + elif radius_query: + all_moons = Moon.query.filter(Moon.radius>=radius_query) + elif name_query: + all_moons = Moon.query.filter(Moon.name==name_query) for moon in all_moons: return_list.append({ "id": moon.id, From 8258aec59f893aea3c8cbaa52e0eda4b15c66a37 Mon Sep 17 00:00:00 2001 From: Carolyn Qi Date: Wed, 3 May 2023 15:37:11 -0700 Subject: [PATCH 09/12] added tests for planets --- app/__init__.py | 4 ++-- tests/__init__.py | 0 tests/conftest.py | 33 +++++++++++++++++++++++++++++++++ tests/test_route.py | 35 +++++++++++++++++++++++++++++++++++ 4 files changed, 70 insertions(+), 2 deletions(-) create mode 100644 tests/__init__.py create mode 100644 tests/conftest.py create mode 100644 tests/test_route.py diff --git a/app/__init__.py b/app/__init__.py index 13dddf446..d73e76895 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -10,11 +10,11 @@ load_dotenv() -def create_app(test_config=None): +def create_app(testing=None): app = Flask(__name__) app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False - if not test_config: + if not testing: app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("SQLALCHEMY_DATABASE_URI") else: app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("SQLALCHEMY_TEST_DATABASE_URI") 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..993358e33 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,33 @@ +import pytest +from app import create_app, db +from flask.signals import request_finished +from app.models.moon import Moon +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_planets(app): + mercury = Planet(name="mercury", radius=1516, description="I am the smallest planet in our solar system") + venus = Planet(name="venus", radius=3760, description="I spin in the opposite direction from Earth") + + db.session.add_all([mercury, venus]) + db.session.commit() + diff --git a/tests/test_route.py b/tests/test_route.py new file mode 100644 index 000000000..51d6e69d3 --- /dev/null +++ b/tests/test_route.py @@ -0,0 +1,35 @@ +import pytest + +def test_get_all_planets(client, two_planets): + response = client.get("/solar_system/planet") + + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == [ + {"id": 1, "name": "mercury", "radius": 1516, "description": "I am the smallest planet in our solar system"}, + {"id": 2, "name": "venus", "radius": 3760, "description": "I spin in the opposite direction from Earth"}] + +def test_post_creates_planet(client): + response = client.post("/solar_system/planet", json = {"name": "mercury", "radius": 1516, "description": "I am the smallest planet in our solar system"}) + + response_body = response.get_json() + + assert response.status_code == 201 + assert "Planet mercury has been added, with the id: 1" in response_body["message"] + +def test_get_one_planet(client, two_planets): + response = client.get("/solar_system/planet/1") + + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == {"id": 1, "name": "mercury", "radius": 1516, "description": "I am the smallest planet in our solar system"} + +def test_delete_one_planet(client, two_planets): + response = client.delete("/solar_system/planet/1") + + response_body = response.get_json() + + assert response.status_code == 200 + assert "Planet 1 has been deleted" in response_body["message"] \ No newline at end of file From 69fe4459245a231c32fe442ae08a09182a9b48fa Mon Sep 17 00:00:00 2001 From: Carolyn Qi Date: Fri, 5 May 2023 11:11:12 -0700 Subject: [PATCH 10/12] Refactor --- app/models/moon.py | 16 ++++++++++++++ app/models/planet.py | 16 ++++++++++++++ app/routes/routes.py | 51 ++++++++++++++------------------------------ 3 files changed, 48 insertions(+), 35 deletions(-) diff --git a/app/models/moon.py b/app/models/moon.py index 93b770f79..83398b65a 100644 --- a/app/models/moon.py +++ b/app/models/moon.py @@ -6,3 +6,19 @@ class Moon(db.Model): radius = db.Column(db.Integer) planet_id = db.Column(db.Integer) + def to_dict(self): + return { + "id": self.id, + "name": self.name, + "radius": self.radius, + "planet_id": self.planet_id + } + + @classmethod + def from_dict(cls, moon_data): + return cls( + name = moon_data["name"], + radius = moon_data["radius"], + planet_id = moon_data["planet_id"], + ) + diff --git a/app/models/planet.py b/app/models/planet.py index 5928614e3..389fa8576 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -6,3 +6,19 @@ class Planet(db.Model): radius = db.Column(db.Integer) description = db.Column(db.Text) + def to_dict(self): + return { + "id": self.id, + "name": self.name, + "radius": self.radius, + "description": self.description + } + + @classmethod + def from_dict(cls, planet_data): + return cls( + name = planet_data["name"], + radius = planet_data["radius"], + description = planet_data["description"], + ) + diff --git a/app/routes/routes.py b/app/routes/routes.py index 478312fde..bdb078e2f 100644 --- a/app/routes/routes.py +++ b/app/routes/routes.py @@ -8,11 +8,7 @@ @solar_system_planet.route("", methods=["POST"]) def add_planet(): request_body = request.get_json() - new_planet = Planet( - name = request_body["name"], - radius = request_body["radius"], - description = request_body["description"] - ) + new_planet = Planet.from_dict(request_body) db.session.add(new_planet) db.session.commit() @@ -43,7 +39,7 @@ def get_planets(): @solar_system_planet.route("/", methods=["GET"]) def get_planet_by_id(planet_id): - planet = verify_planet_id(planet_id) + planet = verify_item_id(Planet, planet_id) return { "id": planet.id, "name": planet.name, @@ -53,7 +49,7 @@ def get_planet_by_id(planet_id): @solar_system_planet.route("/", methods=["DELETE"]) def delete_planet(planet_id): - planet = verify_planet_id(planet_id) + planet = verify_item_id(Planet, planet_id) db.session.delete(planet) db.session.commit() @@ -62,7 +58,7 @@ def delete_planet(planet_id): @solar_system_planet.route("/", methods=["PUT"]) def update(planet_id): - planet = verify_planet_id(planet_id) + planet = verify_item_id(Planet, planet_id) request_body = request.get_json() planet.name = request_body["name"] @@ -73,27 +69,12 @@ def update(planet_id): return make_response({"message": f"Planet {planet.id} has been updated"}, 200) -def verify_planet_id(planet_id): - try: - planet_id = int(planet_id) - except ValueError: - abort(make_response({"message": f"Planet {planet_id} is invalid"}, 400)) - all_planets = Planet.query.all() - for planet in all_planets: - if planet.id == planet_id: - return planet - abort(make_response({"message": "Planet {planet_id} is not found"}, 404)) - solar_system_moon = Blueprint("solar_system_moon", __name__, url_prefix="/solar_system/moon") @solar_system_moon.route("", methods=["POST"]) def add_moon(): request_body = request.get_json() - new_moon = Moon( - name = request_body["name"], - radius = request_body["radius"], - planet_id = request_body["planet_id"] - ) + new_moon = Moon.from_dict(request_body) db.session.add(new_moon) db.session.commit() @@ -124,7 +105,7 @@ def get_moons(): @solar_system_moon.route("/", methods=["GET"]) def get_moon_by_id(moon_id): - moon = verify_moon_id(moon_id) + moon = verify_item_id(Moon, moon_id) return { "id": moon.id, "name": moon.name, @@ -134,7 +115,7 @@ def get_moon_by_id(moon_id): @solar_system_moon.route("/", methods=["DELETE"]) def delete_planet(moon_id): - moon = verify_moon_id(moon_id) + moon = verify_item_id(Moon, moon_id) db.session.delete(moon) db.session.commit() @@ -143,7 +124,7 @@ def delete_planet(moon_id): @solar_system_moon.route("/", methods=["PUT"]) def update(moon_id): - moon = verify_moon_id(moon_id) + moon = verify_item_id(Moon, moon_id) request_body = request.get_json() moon.name = request_body["name"] @@ -154,14 +135,14 @@ def update(moon_id): return make_response({"message": f"Moon {moon.id} has been updated"}, 200) -def verify_moon_id(moon_id): +def verify_item_id(model, item_id): try: - moon_id = int(moon_id) + item_id = int(item_id) except ValueError: - abort(make_response({"message": f"Moon {moon_id} is invalid"}, 400)) - all_moons = Moon.query.all() - for moon in all_moons: - if moon.id == moon_id: - return moon - abort(make_response({"message": f"Moon {moon_id} is not found"}, 404)) + abort(make_response({"message": f"Moon {item_id} is invalid"}, 400)) + all_items = model.query.all() + for item in all_items: + if item.id == item_id: + return item + abort(make_response({"message": f"Moon {item_id} is not found"}, 404)) From 7d55779c9eb3e7303a9b078ad43a0a395a3ac602 Mon Sep 17 00:00:00 2001 From: Carolyn Qi Date: Tue, 9 May 2023 11:26:41 -0700 Subject: [PATCH 11/12] add gunicorn --- requirements.txt | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/requirements.txt b/requirements.txt index ae59e7b55..f4ff77124 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,14 +4,20 @@ blinker==1.4 certifi==2020.12.5 chardet==4.0.0 click==7.1.2 +coverage==7.2.3 +exceptiongroup==1.1.1 Flask==1.1.2 Flask-Migrate==2.6.0 Flask-SQLAlchemy==2.4.4 +gunicorn==20.1.0 idna==2.10 +iniconfig==2.0.0 itsdangerous==1.1.0 Jinja2==2.11.3 Mako==1.1.4 MarkupSafe==1.1.1 +packaging==23.1 +pluggy==1.0.0 psycopg2-binary==2.9.5 pycodestyle==2.6.0 pytest==7.3.1 @@ -23,5 +29,6 @@ requests==2.25.1 six==1.15.0 SQLAlchemy==1.3.23 toml==0.10.2 +tomli==2.0.1 urllib3==1.26.4 Werkzeug==1.0.1 From 1929e2822724a2e3e6c660fb701f11687ec8f95d Mon Sep 17 00:00:00 2001 From: Carolyn Qi Date: Tue, 9 May 2023 11:50:49 -0700 Subject: [PATCH 12/12] Add Render Database to our init --- app/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index d73e76895..f081cb329 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -15,7 +15,7 @@ def create_app(testing=None): app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False if not testing: - app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("SQLALCHEMY_DATABASE_URI") + app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("RENDER_DATABASE_URI") else: app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("SQLALCHEMY_TEST_DATABASE_URI")