From 50c6395d3b264b51917b09b559b24f686269c5ae Mon Sep 17 00:00:00 2001 From: kindra greenawalt Date: Fri, 21 Oct 2022 13:55:53 -0400 Subject: [PATCH 01/13] defined planet class and started a hard code list of of planets. --- app/routes.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..97bc2bf5f 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,12 @@ from flask import Blueprint +class Planet: + def __init__(self,id,name,description,temperature): + self.id = id + self.name = name + self.description = description + self.temperature = temperature + +planets = [ + Planet(1,"Jupiter",) +] \ No newline at end of file From 49724d588718abed5ef36e0fb9d6beb7963ba924 Mon Sep 17 00:00:00 2001 From: Selam Chaka Date: Mon, 24 Oct 2022 14:42:52 -0400 Subject: [PATCH 02/13] wave1 and wave2 --- app/__init__.py | 3 +++ app/routes.py | 61 ++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 63 insertions(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..b386c5938 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -3,5 +3,8 @@ def create_app(test_config=None): app = Flask(__name__) + + from .routes import planet_bp + app.register_blueprint(planet_bp) return app diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..1cc683986 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,61 @@ -from flask import Blueprint +from crypt import methods +from flask import Blueprint , jsonify, abort, make_response +class Planet: + def __init__(self,id,name,description,diameter): + self.id = id + self.name = name + self.description = description + self.diameter = diameter + +# https://space-facts.com/planets/ +# https://solarsystem.nasa.gov/planets/neptune/overview/ + +PLANETS = [ + Planet(1, "Mercury", "The smallest planet in our solar system and closest to the Sun", "4,879 km"), + Planet(2, "Venus", "Spins slowly in the opposite direction from most planets", "12,104 km"), + Planet(3, "Earth", "The only place we know of so far that’s inhabited by living things", "12,742 km"), + Planet(4, "Mars", " It is a dusty, cold, desert world with a very thin atmosphere", "6,779 km"), + Planet(5, "Jupiter", "It's more than twice as massive than the other planets of our solar system combined", "139,822 km"), + Planet(6, "Saturn", "Adorned with a dazzling, complex system of icy rings, Saturn is unique in our solar system", "116,464 km"), + Planet(7, "Uranus", "The Sun—rotates at a nearly 90-degree angle from the plane of its orbit", "50,724 km"), + Planet(8, "Neptune", "The Sun—is dark, cold and whipped by supersonic winds", "49,244 km") + ] + +planet_bp = Blueprint("planets", __name__,url_prefix="/planets") + + +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"book {planet_id} not found"}, 404)) + +@planet_bp.route("", methods = ["GET"]) +def get_all_planets(): + result = [] + for planet in PLANETS: + result.append({ + "id": planet.id, + "name":planet.name, + "description":planet.description, + "diameter":planet.diameter + }) + + return jsonify(result) + +@planet_bp.route("/", methods = ["GET"]) +def get_one_planet(planet_id): + planet = validate_planet(planet_id) + return jsonify({ + "id": planet.id, + "name":planet.name, + "description":planet.description, + "diameter":planet.diameter + }) From a39a94dc0f5d5c0d981233c3f402bfa7721f4a18 Mon Sep 17 00:00:00 2001 From: Selam Chaka Date: Fri, 28 Oct 2022 15:04:40 -0400 Subject: [PATCH 03/13] Wave 3 Create planet --- app/__init__.py | 12 ++ app/models/__init__.py | 0 app/models/planet.py | 7 + app/routes.py | 131 +++++++++++------- migrations/README | 1 + migrations/alembic.ini | 50 +++++++ migrations/env.py | 91 ++++++++++++ migrations/script.py.mako | 24 ++++ .../c23eebf6a6b7_adds_planet_model.py | 34 +++++ 9 files changed, 298 insertions(+), 52 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/c23eebf6a6b7_adds_planet_model.py diff --git a/app/__init__.py b/app/__init__.py index b386c5938..e91d88484 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,9 +1,21 @@ from flask import Flask +from flask_sqlalchemy import SQLAlchemy +from flask_migrate import Migrate + +db = SQLAlchemy() +migrate = Migrate() def create_app(test_config=None): app = Flask(__name__) + app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False + app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system_development' + + db.init_app(app) + migrate.init_app(app, db) + + from. models.planet import Planet from .routes import planet_bp app.register_blueprint(planet_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..09b916f3c --- /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) + diameter = db.Column(db.String) \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 1cc683986..9390e38f2 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,61 +1,88 @@ +from app import db +from app.models.planet import Planet + from crypt import methods -from flask import Blueprint , jsonify, abort, make_response - -class Planet: - def __init__(self,id,name,description,diameter): - self.id = id - self.name = name - self.description = description - self.diameter = diameter +from flask import Blueprint , jsonify, abort, make_response, request + + +planet_bp = Blueprint("planets", __name__,url_prefix="/planets") + +@planet_bp.route("", methods=["POST"]) +def create_planet(): + request_body = request.get_json() + new_planet = Planet(name=request_body["name"], + description=request_body["description"], + diameter = request_body["diameter"]) + + db.session.add(new_planet) + db.session.commit() + + return f"Planet {new_planet.name} successfully created", 201 + + + + + + + + + +# class Planet: +# def __init__(self,id,name,description,diameter): +# self.id = id +# self.name = name +# self.description = description +# self.diameter = diameter + # https://space-facts.com/planets/ # https://solarsystem.nasa.gov/planets/neptune/overview/ -PLANETS = [ - Planet(1, "Mercury", "The smallest planet in our solar system and closest to the Sun", "4,879 km"), - Planet(2, "Venus", "Spins slowly in the opposite direction from most planets", "12,104 km"), - Planet(3, "Earth", "The only place we know of so far that’s inhabited by living things", "12,742 km"), - Planet(4, "Mars", " It is a dusty, cold, desert world with a very thin atmosphere", "6,779 km"), - Planet(5, "Jupiter", "It's more than twice as massive than the other planets of our solar system combined", "139,822 km"), - Planet(6, "Saturn", "Adorned with a dazzling, complex system of icy rings, Saturn is unique in our solar system", "116,464 km"), - Planet(7, "Uranus", "The Sun—rotates at a nearly 90-degree angle from the plane of its orbit", "50,724 km"), - Planet(8, "Neptune", "The Sun—is dark, cold and whipped by supersonic winds", "49,244 km") - ] +# PLANETS = [ +# Planet(1, "Mercury", "The smallest planet in our solar system and closest to the Sun", "4,879 km"), +# Planet(2, "Venus", "Spins slowly in the opposite direction from most planets", "12,104 km"), +# Planet(3, "Earth", "The only place we know of so far that’s inhabited by living things", "12,742 km"), +# Planet(4, "Mars", " It is a dusty, cold, desert world with a very thin atmosphere", "6,779 km"), +# Planet(5, "Jupiter", "It's more than twice as massive than the other planets of our solar system combined", "139,822 km"), +# Planet(6, "Saturn", "Adorned with a dazzling, complex system of icy rings, Saturn is unique in our solar system", "116,464 km"), +# Planet(7, "Uranus", "The Sun—rotates at a nearly 90-degree angle from the plane of its orbit", "50,724 km"), +# Planet(8, "Neptune", "The Sun—is dark, cold and whipped by supersonic winds", "49,244 km") +# ] -planet_bp = Blueprint("planets", __name__,url_prefix="/planets") -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"book {planet_id} not found"}, 404)) - -@planet_bp.route("", methods = ["GET"]) -def get_all_planets(): - result = [] - for planet in PLANETS: - result.append({ - "id": planet.id, - "name":planet.name, - "description":planet.description, - "diameter":planet.diameter - }) + +# 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"book {planet_id} not found"}, 404)) + +# @planet_bp.route("", methods = ["GET"]) +# def get_all_planets(): +# result = [] +# for planet in PLANETS: +# result.append({ +# "id": planet.id, +# "name":planet.name, +# "description":planet.description, +# "diameter":planet.diameter +# }) - return jsonify(result) - -@planet_bp.route("/", methods = ["GET"]) -def get_one_planet(planet_id): - planet = validate_planet(planet_id) - return jsonify({ - "id": planet.id, - "name":planet.name, - "description":planet.description, - "diameter":planet.diameter - }) +# return jsonify(result) + +# @planet_bp.route("/", methods = ["GET"]) +# def get_one_planet(planet_id): +# planet = validate_planet(planet_id) +# return jsonify({ +# "id": planet.id, +# "name":planet.name, +# "description":planet.description, +# "diameter":planet.diameter +# }) diff --git a/migrations/README b/migrations/README new file mode 100644 index 000000000..0e0484415 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Single-database configuration for Flask. diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 000000000..ec9d45c26 --- /dev/null +++ b/migrations/alembic.ini @@ -0,0 +1,50 @@ +# 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,flask_migrate + +[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 + +[logger_flask_migrate] +level = INFO +handlers = +qualname = flask_migrate + +[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..68feded2a --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,91 @@ +from __future__ import with_statement + +import logging +from logging.config import fileConfig + +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.get_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 = current_app.extensions['migrate'].db.get_engine() + + 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/c23eebf6a6b7_adds_planet_model.py b/migrations/versions/c23eebf6a6b7_adds_planet_model.py new file mode 100644 index 000000000..a69040259 --- /dev/null +++ b/migrations/versions/c23eebf6a6b7_adds_planet_model.py @@ -0,0 +1,34 @@ +"""adds Planet Model + +Revision ID: c23eebf6a6b7 +Revises: +Create Date: 2022-10-28 14:58:24.929016 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'c23eebf6a6b7' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('planet', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('name', sa.String(), nullable=True), + sa.Column('description', sa.String(), nullable=True), + sa.Column('diameter', 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 91ec0bbefb01948066b984bceba9ef8effb1e4d6 Mon Sep 17 00:00:00 2001 From: Kindra Date: Tue, 1 Nov 2022 14:06:09 -0400 Subject: [PATCH 04/13] created get all planets function --- app/routes.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/app/routes.py b/app/routes.py index 9390e38f2..16cb3cf2c 100644 --- a/app/routes.py +++ b/app/routes.py @@ -19,6 +19,20 @@ def create_planet(): return f"Planet {new_planet.name} successfully created", 201 +@planet_bp.route("", methods=["GET"]) +def read_all_planets(): + planets_response = [] + planets = Planet.query.all() + for planet in planets: + planets_response.append( + { + "id": planet.id, + "name": planet.name, + "description": planet.description + } + ) + return jsonify(planets_response) + From 612a5ffd19d92fce7e99ac7d7ead9971a725a302 Mon Sep 17 00:00:00 2001 From: Kindra Date: Tue, 1 Nov 2022 15:03:04 -0400 Subject: [PATCH 05/13] created get one planet, update one planet, and delete one planet. Bugs in later two --- app/routes.py | 50 +++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index 16cb3cf2c..54f330eb5 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,3 +1,4 @@ +from attr import validate from app import db from app.models.planet import Planet @@ -7,6 +8,19 @@ planet_bp = Blueprint("planets", __name__,url_prefix="/planets") +def validate_planet(planet_id): + try: + planet_id = int(planet_id) + except: + abort(make_response({"message":f"planet {planet_id} invalid"}, 400)) + + planet = Planet.query.get(planet_id) + + if not planet: + abort(make_response({"message":f"planet {planet_id} not found"}, 404)) + + return planet + @planet_bp.route("", methods=["POST"]) def create_planet(): request_body = request.get_json() @@ -28,11 +42,45 @@ def read_all_planets(): { "id": planet.id, "name": planet.name, - "description": planet.description + "description": planet.description, + "diameter": planet.diameter } ) return jsonify(planets_response) + + +@planet_bp.route("/", methods=["GET"]) +def read_one_planet(planet_id): + planet = validate_planet(planet_id) + return { + "id": planet.id, + "name": planet.name, + "description": planet.description, + "diameter": planet.diameter + } + +@planet_bp.route("/", methods=["DELETE"]) +def delete_planet(planet_id): + planet = validate_planet(planet_id) + + db.session.delete(planet) + db.session.commit + + return make_response(jsonify(f"Planet #{planet.id} successfully deleted!")) + +@planet_bp.route("/", methods["PUT"]) +def update_planet(planet_id): + planet = validate_planet(planet_id) + + request_body = request.get_json() + + planet.name = request_body["name"] + planet.description = request_body["description"] + planet.diameter = request_body["diameter"] + + db.session.commit() + return make_response(jsonify(f"Planet #{planet_id} successfully updated! ")) From b046204972b8105f6b8ad068f1cf9ceaeddc133a Mon Sep 17 00:00:00 2001 From: Selam Chaka Date: Tue, 1 Nov 2022 15:22:31 -0400 Subject: [PATCH 06/13] fixed bug's for update and delete --- app/routes.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/app/routes.py b/app/routes.py index 54f330eb5..6b5e525f4 100644 --- a/app/routes.py +++ b/app/routes.py @@ -64,11 +64,11 @@ def delete_planet(planet_id): planet = validate_planet(planet_id) db.session.delete(planet) - db.session.commit + db.session.commit() - return make_response(jsonify(f"Planet #{planet.id} successfully deleted!")) + return make_response(f"Planet #{planet.id} successfully deleted") -@planet_bp.route("/", methods["PUT"]) +@planet_bp.route("/", methods=["PUT"]) def update_planet(planet_id): planet = validate_planet(planet_id) @@ -80,9 +80,7 @@ def update_planet(planet_id): db.session.commit() - return make_response(jsonify(f"Planet #{planet_id} successfully updated! ")) - - + return make_response(f"Planet #{planet.id} successfully updated") From c7dbd0d7b3918ecd4bec641a5d02f54fe291c8ba Mon Sep 17 00:00:00 2001 From: Kindra Date: Wed, 2 Nov 2022 14:33:21 -0400 Subject: [PATCH 07/13] refactored to add query params --- app/models/planet.py | 11 ++++++++++- app/routes.py | 31 +++++++++++++------------------ 2 files changed, 23 insertions(+), 19 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index 09b916f3c..9ad4601f8 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -4,4 +4,13 @@ class Planet(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String) description = db.Column(db.String) - diameter = db.Column(db.String) \ No newline at end of file + diameter = db.Column(db.String) + + + def to_dict(self): + planet_dict = {} + planet_dict["id"] = self.id + planet_dict["name"] = self.name + planet_dict["description"] = self.description + planet_dict["diameter"] = self.diameter + return planet_dict \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 6b5e525f4..e854c673d 100644 --- a/app/routes.py +++ b/app/routes.py @@ -35,38 +35,31 @@ def create_planet(): @planet_bp.route("", methods=["GET"]) def read_all_planets(): + planet_query = request.args.get("name") + if planet_query: + planets = Planet.query.filter_by(name=planet_query) + else: + planets = Planet.query.all() + planets_response = [] - planets = Planet.query.all() for planet in planets: - planets_response.append( - { - "id": planet.id, - "name": planet.name, - "description": planet.description, - "diameter": planet.diameter - } - ) + planets_response.append(planet.to_dict()) return jsonify(planets_response) @planet_bp.route("/", methods=["GET"]) def read_one_planet(planet_id): planet = validate_planet(planet_id) - return { - "id": planet.id, - "name": planet.name, - "description": planet.description, - "diameter": planet.diameter - } + return planet.to_dict() @planet_bp.route("/", methods=["DELETE"]) def delete_planet(planet_id): planet = validate_planet(planet_id) db.session.delete(planet) - db.session.commit() + db.session.commit - return make_response(f"Planet #{planet.id} successfully deleted") + return make_response(jsonify(f"Planet #{planet.id} successfully deleted!")) @planet_bp.route("/", methods=["PUT"]) def update_planet(planet_id): @@ -80,7 +73,9 @@ def update_planet(planet_id): db.session.commit() - return make_response(f"Planet #{planet.id} successfully updated") + return make_response(jsonify(f"Planet #{planet_id} successfully updated! ")) + + From d0280cde812b66b3c3ebb6b1965f43acd0bda1de Mon Sep 17 00:00:00 2001 From: Selam Chaka Date: Thu, 3 Nov 2022 15:25:02 -0400 Subject: [PATCH 08/13] fixed delete bug and refactoring using cls --- app/models/planet.py | 10 +++++++++- app/routes.py | 18 +++++++++--------- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index 9ad4601f8..6f9fd424d 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -13,4 +13,12 @@ def to_dict(self): planet_dict["name"] = self.name planet_dict["description"] = self.description planet_dict["diameter"] = self.diameter - return planet_dict \ No newline at end of file + return planet_dict + + @classmethod + def from_dict(cls, planet_data): + new_planet = Planet(name=planet_data["name"], + description=planet_data["description"], + diameter=planet_data["diameter"] + ) + return new_planet \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index e854c673d..16962251c 100644 --- a/app/routes.py +++ b/app/routes.py @@ -8,16 +8,16 @@ planet_bp = Blueprint("planets", __name__,url_prefix="/planets") -def validate_planet(planet_id): +def validate_planet(cls, planet_id): try: planet_id = int(planet_id) except: - abort(make_response({"message":f"planet {planet_id} invalid"}, 400)) + abort(make_response({"message":f"{cls.__name__} {planet_id} invalid"}, 400)) - planet = Planet.query.get(planet_id) + planet = cls.query.get(planet_id) if not planet: - abort(make_response({"message":f"planet {planet_id} not found"}, 404)) + abort(make_response({"message":f"{cls.__name__} {planet_id} not found"}, 404)) return planet @@ -31,7 +31,7 @@ def create_planet(): db.session.add(new_planet) db.session.commit() - return f"Planet {new_planet.name} successfully created", 201 + return make_response(jsonify(f"Planet {new_planet.name} successfully created", 201)) @planet_bp.route("", methods=["GET"]) def read_all_planets(): @@ -49,21 +49,21 @@ def read_all_planets(): @planet_bp.route("/", methods=["GET"]) def read_one_planet(planet_id): - planet = validate_planet(planet_id) + planet = validate_planet(Planet,planet_id) return planet.to_dict() @planet_bp.route("/", methods=["DELETE"]) def delete_planet(planet_id): - planet = validate_planet(planet_id) + planet = validate_planet(Planet, planet_id) db.session.delete(planet) - db.session.commit + db.session.commit() return make_response(jsonify(f"Planet #{planet.id} successfully deleted!")) @planet_bp.route("/", methods=["PUT"]) def update_planet(planet_id): - planet = validate_planet(planet_id) + planet = validate_planet(Planet, planet_id) request_body = request.get_json() From c70bfd7891d076079bf4fa7b31a36dd801f495d3 Mon Sep 17 00:00:00 2001 From: Kindra Date: Thu, 3 Nov 2022 18:17:57 -0400 Subject: [PATCH 09/13] test files and a few pytests created --- tests/__init__.py | 0 tests/conftest.py | 39 +++++++++++++++++++++++++++++++++++++++ tests/test_routes.py | 40 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 79 insertions(+) create mode 100644 tests/__init__.py create mode 100644 tests/conftest.py create mode 100644 tests/test_routes.py 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..3f98401a5 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,39 @@ +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 two_saved_planets(app): + # Arrange + venus_planet = Planet(name="Venus", + description="a fun planet to be on", + diameter = "2,374 km") + mars_planet = Planet(name="Mars", + description="home of the martians", + diameter="3,456 km") + + db.session.add_all([venus_planet, mars_planet]) + db.session.commit() + +@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..03f1f6b24 --- /dev/null +++ b/tests/test_routes.py @@ -0,0 +1,40 @@ +import pytest +from app.models.planet import Planet + +def test_get_all_planets_with_no_records(client): + # Act + response = client.get("/planets") + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert response_body == [] + + +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": "Venus", + "description": "a fun planet to be on", + "diameter":"2,374 km", + } + +def test_create_one_planet(client): + # Act + response = client.post("/planets", json={ + "name": "Saturn", + "description": "rings of gold shine bright", + "diameter": "5,467 km" + }) + response_body = response.get_json() + + + # Assert + assert response.status_code == 200 + assert response_body == "Planet Saturn successfully created, 201" \ No newline at end of file From 11373c000df5da7d1e436114dfd8c69a8b926eba Mon Sep 17 00:00:00 2001 From: Kindra Date: Thu, 3 Nov 2022 18:36:24 -0400 Subject: [PATCH 10/13] fixed test bug that was returning 200 instead of 201 --- tests/test_routes.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_routes.py b/tests/test_routes.py index 03f1f6b24..4bf0681b0 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -36,5 +36,5 @@ def test_create_one_planet(client): # Assert - assert response.status_code == 200 - assert response_body == "Planet Saturn successfully created, 201" \ No newline at end of file + assert response.status_code == 201 + assert response_body == "Planet Saturn successfully created" \ No newline at end of file From cc387056170d69a22eed1e2ea8d6beda5283b1d3 Mon Sep 17 00:00:00 2001 From: Kindra Date: Thu, 3 Nov 2022 18:41:42 -0400 Subject: [PATCH 11/13] fixed create planet route and pytest for creating planet --- app/__init__.py | 16 ++++++++++++---- app/routes.py | 9 +++++---- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index e91d88484..9825ecd0b 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,16 +1,24 @@ 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) diff --git a/app/routes.py b/app/routes.py index 16962251c..f24005358 100644 --- a/app/routes.py +++ b/app/routes.py @@ -24,14 +24,15 @@ def validate_planet(cls, planet_id): @planet_bp.route("", methods=["POST"]) def create_planet(): request_body = request.get_json() - new_planet = Planet(name=request_body["name"], - description=request_body["description"], - diameter = request_body["diameter"]) + new_planet = Planet.from_dict(request_body) + # name=request_body["name"], + # description=request_body["description"], + # diameter = request_body["diameter"]) db.session.add(new_planet) db.session.commit() - return make_response(jsonify(f"Planet {new_planet.name} successfully created", 201)) + return make_response(jsonify(f"Planet {new_planet.name} successfully created"), 201) @planet_bp.route("", methods=["GET"]) def read_all_planets(): From 78573829abd460f257583a438e8c7f24656732de Mon Sep 17 00:00:00 2001 From: Selam Chaka Date: Thu, 3 Nov 2022 22:51:04 -0400 Subject: [PATCH 12/13] adding five tests passing --- app/__init__.py | 7 +++---- tests/test_routes.py | 32 +++++++++++++++++++++++++++++++- 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 9825ecd0b..16713db38 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -12,14 +12,13 @@ def create_app(test_config=None): app = Flask(__name__) if not test_config: app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False - app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get( - "SQLALCHEMY_DATABASE_URI") + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("SQLALCHEMY_DATABASE_URI") else: app.config["TESTING"] = True app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False - app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( - "SQLALCHEMY_TEST_DATABASE_URI") + app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("SQLALCHEMY_TEST_DATABASE_URI") + db.init_app(app) migrate.init_app(app, db) diff --git a/tests/test_routes.py b/tests/test_routes.py index 4bf0681b0..b8b46b6fb 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -10,7 +10,6 @@ def test_get_all_planets_with_no_records(client): assert response.status_code == 200 assert response_body == [] - def test_get_one_planet(client, two_saved_planets): # Act response = client.get("/planets/1") @@ -25,6 +24,37 @@ def test_get_one_planet(client, two_saved_planets): "diameter":"2,374 km", } +def test_get_one_planet_with_no_records(client): + # Act + response = client.get("/planets/1") + response_body = response.get_json() + + # Assert + assert response.status_code == 404 + assert response_body == { "message": "Planet 1 not found"} + +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": "Venus", + "description": "a fun planet to be on", + "diameter":"2,374 km" + }, + { + "id": 2, + "name": "Mars", + "description": "home of the martians", + "diameter":"3,456 km" + } + ] + def test_create_one_planet(client): # Act response = client.post("/planets", json={ From b595eb42f2b981c5b00c1b03d96147dd2b16b83d Mon Sep 17 00:00:00 2001 From: Selam Chaka Date: Thu, 3 Nov 2022 22:54:41 -0400 Subject: [PATCH 13/13] some cleaning --- app/routes.py | 70 ----------------------------------------------- tests/conftest.py | 8 +++--- 2 files changed, 4 insertions(+), 74 deletions(-) diff --git a/app/routes.py b/app/routes.py index f24005358..3940f69c4 100644 --- a/app/routes.py +++ b/app/routes.py @@ -25,9 +25,6 @@ def validate_planet(cls, planet_id): def create_planet(): request_body = request.get_json() new_planet = Planet.from_dict(request_body) - # name=request_body["name"], - # description=request_body["description"], - # diameter = request_body["diameter"]) db.session.add(new_planet) db.session.commit() @@ -75,70 +72,3 @@ def update_planet(planet_id): db.session.commit() return make_response(jsonify(f"Planet #{planet_id} successfully updated! ")) - - - - - - - - -# class Planet: -# def __init__(self,id,name,description,diameter): -# self.id = id -# self.name = name -# self.description = description -# self.diameter = diameter - - -# https://space-facts.com/planets/ -# https://solarsystem.nasa.gov/planets/neptune/overview/ - -# PLANETS = [ -# Planet(1, "Mercury", "The smallest planet in our solar system and closest to the Sun", "4,879 km"), -# Planet(2, "Venus", "Spins slowly in the opposite direction from most planets", "12,104 km"), -# Planet(3, "Earth", "The only place we know of so far that’s inhabited by living things", "12,742 km"), -# Planet(4, "Mars", " It is a dusty, cold, desert world with a very thin atmosphere", "6,779 km"), -# Planet(5, "Jupiter", "It's more than twice as massive than the other planets of our solar system combined", "139,822 km"), -# Planet(6, "Saturn", "Adorned with a dazzling, complex system of icy rings, Saturn is unique in our solar system", "116,464 km"), -# Planet(7, "Uranus", "The Sun—rotates at a nearly 90-degree angle from the plane of its orbit", "50,724 km"), -# Planet(8, "Neptune", "The Sun—is dark, cold and whipped by supersonic winds", "49,244 km") -# ] - - - - -# 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"book {planet_id} not found"}, 404)) - -# @planet_bp.route("", methods = ["GET"]) -# def get_all_planets(): -# result = [] -# for planet in PLANETS: -# result.append({ -# "id": planet.id, -# "name":planet.name, -# "description":planet.description, -# "diameter":planet.diameter -# }) - -# return jsonify(result) - -# @planet_bp.route("/", methods = ["GET"]) -# def get_one_planet(planet_id): -# planet = validate_planet(planet_id) -# return jsonify({ -# "id": planet.id, -# "name":planet.name, -# "description":planet.description, -# "diameter":planet.diameter -# }) diff --git a/tests/conftest.py b/tests/conftest.py index 3f98401a5..d324cf104 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -25,11 +25,11 @@ def expire_session(sender, response, **extra): def two_saved_planets(app): # Arrange venus_planet = Planet(name="Venus", - description="a fun planet to be on", - diameter = "2,374 km") + description="a fun planet to be on", + diameter = "2,374 km") mars_planet = Planet(name="Mars", - description="home of the martians", - diameter="3,456 km") + description="home of the martians", + diameter="3,456 km") db.session.add_all([venus_planet, mars_planet]) db.session.commit()