From 31dbb71dac9bd7cbd71ede628caacdf96bb5168c Mon Sep 17 00:00:00 2001 From: sarahstandish Date: Mon, 18 Oct 2021 14:52:01 -0700 Subject: [PATCH 01/22] create notes doc --- notes.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 notes.md diff --git a/notes.md b/notes.md new file mode 100644 index 000000000..69a68e632 --- /dev/null +++ b/notes.md @@ -0,0 +1,3 @@ +# Notes +Follow the directions in Learn - Building an API part 1 activity +This will be very similar to the 'books' API \ No newline at end of file From 814cbbbc319187e877340ebecea88e5c42896ad2 Mon Sep 17 00:00:00 2001 From: goblinbrooke Date: Tue, 19 Oct 2021 11:06:28 -0700 Subject: [PATCH 02/22] Class Planet defined + Class method defined --- app/planets.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 app/planets.py diff --git a/app/planets.py b/app/planets.py new file mode 100644 index 000000000..fe24852c2 --- /dev/null +++ b/app/planets.py @@ -0,0 +1,19 @@ +# Define the class +# Create an init +# Class variable that is number of planets (ID) +# Parameters of init = self, name, description, has_moons = boolean +# Inside init: set variables, call update number of planets, set id = number of planets +# Class method: update number of planets + +class Planet: + number_of_planets = 0 + def __init__(self, name, description, has_moons=True): + self.name = name + self.description = description + self.has_moons = has_moons + self.id = Planet.number_of_planets + Planet.increase_number_of_planets() + + @classmethod + def increase_number_of_planets(Planet): + Planet.number_of_planets += 1 \ No newline at end of file From 154ed688a11655037b2d15219012acc08afe1005 Mon Sep 17 00:00:00 2001 From: sarahstandish Date: Tue, 19 Oct 2021 11:30:56 -0700 Subject: [PATCH 03/22] add dictionary method --- app/planets.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/app/planets.py b/app/planets.py index fe24852c2..806b6caca 100644 --- a/app/planets.py +++ b/app/planets.py @@ -16,4 +16,13 @@ def __init__(self, name, description, has_moons=True): @classmethod def increase_number_of_planets(Planet): - Planet.number_of_planets += 1 \ No newline at end of file + Planet.number_of_planets += 1 + + # add some way to turn it into a dictionary easily + def create_planet_dictionary(self): + return { + "id": self.id, + "name": self.name, + "description": self.description, + "has moons": self.has_moons + } \ No newline at end of file From 01764a7ec78455a4594760e5db2cd9a7c98e4bd6 Mon Sep 17 00:00:00 2001 From: sarahstandish Date: Tue, 19 Oct 2021 11:31:29 -0700 Subject: [PATCH 04/22] add psuedocode --- app/routes.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..6ca4f0bd8 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,10 @@ from flask import Blueprint +# create blueprint which is the decorator of the routes +# it will have a url prefix of /planets +# endpoint will have a prefix of an empty strings +# methods will be get +# create the function for handle planets +# empty list +# loop through planets and add to list +# return the list in json \ No newline at end of file From b62155949d32e95553aa99fd2cd9121bde5b0f15 Mon Sep 17 00:00:00 2001 From: sarahstandish Date: Tue, 19 Oct 2021 11:31:50 -0700 Subject: [PATCH 05/22] list of planet instances --- app/list_of_planets.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 app/list_of_planets.py diff --git a/app/list_of_planets.py b/app/list_of_planets.py new file mode 100644 index 000000000..283d4c120 --- /dev/null +++ b/app/list_of_planets.py @@ -0,0 +1,18 @@ +# create a list of planets array +# fill out name, description, has moons boolean +from planets import Planet + +planets = [ + Planet("Mercury", "Closest to the sun, hot.", False), + Planet("Venus", "Spins the opposite direction of other planets.", False), + Planet("Earth", "You are here."), + Planet("Mars", "Red planet."), + Planet("Jupiter", "Gas Giant."), + Planet("Saturn", "Has rings."), + Planet("Uranus", "Controversy over pronunciation"), + Planet("Neptune", "Smallest gas giant, with faint rings."), + Planet("Pluto", "Brooke still believes!") +] + +for planet in planets: + print(planet.create_planet_dictionary()) \ No newline at end of file From 98ed786a325e4be4958d2b49bf5068aac2e3360b Mon Sep 17 00:00:00 2001 From: sarahstandish Date: Tue, 19 Oct 2021 11:43:28 -0700 Subject: [PATCH 06/22] Add planets blueprint and handle_planets endpoint --- app/__init__.py | 2 ++ app/list_of_planets.py | 2 +- app/routes.py | 16 ++++++++++++++-- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..3675c9309 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -4,4 +4,6 @@ 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/list_of_planets.py b/app/list_of_planets.py index 283d4c120..804848d3f 100644 --- a/app/list_of_planets.py +++ b/app/list_of_planets.py @@ -1,6 +1,6 @@ # create a list of planets array # fill out name, description, has moons boolean -from planets import Planet +from .planets import Planet planets = [ Planet("Mercury", "Closest to the sun, hot.", False), diff --git a/app/routes.py b/app/routes.py index 6ca4f0bd8..3f0768283 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,4 +1,5 @@ -from flask import Blueprint +from flask import Blueprint, json, jsonify +from .list_of_planets import planets # create blueprint which is the decorator of the routes # it will have a url prefix of /planets @@ -7,4 +8,15 @@ # create the function for handle planets # empty list # loop through planets and add to list -# return the list in json \ No newline at end of file +# return the list in json + +planets_bp = Blueprint("planets", __name__, url_prefix="/planets") + +@planets_bp.route("", methods=["GET"]) +def handle_planets(): + + list_of_planets = [] + for planet in planets: + list_of_planets.append(planet.create_planet_dictionary()), 200 + + return jsonify(list_of_planets) From 18c4af5bc835f0d9a09ecad4a8e048b0d9893811 Mon Sep 17 00:00:00 2001 From: goblinbrooke Date: Tue, 19 Oct 2021 12:01:03 -0700 Subject: [PATCH 07/22] Part 1 Final :) --- app/__init__.py | 3 ++- app/list_of_planets.py | 9 ++------- app/planets.py | 8 -------- app/routes.py | 17 +++++++---------- 4 files changed, 11 insertions(+), 26 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 3675c9309..0985cabdf 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -6,4 +6,5 @@ def create_app(test_config=None): from .routes import planets_bp app.register_blueprint(planets_bp) - return app + + return app \ No newline at end of file diff --git a/app/list_of_planets.py b/app/list_of_planets.py index 804848d3f..8287b7e10 100644 --- a/app/list_of_planets.py +++ b/app/list_of_planets.py @@ -1,5 +1,3 @@ -# create a list of planets array -# fill out name, description, has moons boolean from .planets import Planet planets = [ @@ -9,10 +7,7 @@ Planet("Mars", "Red planet."), Planet("Jupiter", "Gas Giant."), Planet("Saturn", "Has rings."), - Planet("Uranus", "Controversy over pronunciation"), + Planet("Uranus", "Controversy over pronunciation."), Planet("Neptune", "Smallest gas giant, with faint rings."), Planet("Pluto", "Brooke still believes!") -] - -for planet in planets: - print(planet.create_planet_dictionary()) \ No newline at end of file +] \ No newline at end of file diff --git a/app/planets.py b/app/planets.py index 806b6caca..ba35e47c9 100644 --- a/app/planets.py +++ b/app/planets.py @@ -1,10 +1,3 @@ -# Define the class -# Create an init -# Class variable that is number of planets (ID) -# Parameters of init = self, name, description, has_moons = boolean -# Inside init: set variables, call update number of planets, set id = number of planets -# Class method: update number of planets - class Planet: number_of_planets = 0 def __init__(self, name, description, has_moons=True): @@ -18,7 +11,6 @@ def __init__(self, name, description, has_moons=True): def increase_number_of_planets(Planet): Planet.number_of_planets += 1 - # add some way to turn it into a dictionary easily def create_planet_dictionary(self): return { "id": self.id, diff --git a/app/routes.py b/app/routes.py index 3f0768283..5c9034c3c 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,15 +1,6 @@ -from flask import Blueprint, json, jsonify +from flask import Blueprint, jsonify from .list_of_planets import planets -# create blueprint which is the decorator of the routes -# it will have a url prefix of /planets -# endpoint will have a prefix of an empty strings -# methods will be get -# create the function for handle planets -# empty list -# loop through planets and add to list -# return the list in json - planets_bp = Blueprint("planets", __name__, url_prefix="/planets") @planets_bp.route("", methods=["GET"]) @@ -20,3 +11,9 @@ def handle_planets(): list_of_planets.append(planet.create_planet_dictionary()), 200 return jsonify(list_of_planets) + +@planets_bp.route("/", methods=["GET"]) +def handle_planet(planet_id): + for planet in planets: + if int(planet_id) == planet.id: + return jsonify(planet.create_planet_dictionary()) \ No newline at end of file From a3557bf233c38bb2323e2a0fa23ece4793634070 Mon Sep 17 00:00:00 2001 From: goblinbrooke Date: Mon, 25 Oct 2021 13:34:02 -0700 Subject: [PATCH 08/22] Set Up + Initialize SQLA/Migrate --- app/__init__.py | 20 ++++++++++++++++++++ app/models/__init__.py | 0 app/models/planet.py | 0 app/planets.py | 3 ++- app/routes.py | 2 ++ 5 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 app/models/__init__.py create mode 100644 app/models/planet.py diff --git a/app/__init__.py b/app/__init__.py index 0985cabdf..004368d63 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,9 +1,29 @@ from flask import Flask +from flask_sqlalchemy import SQLAlchemy +from flask_migrate import Migrate + +# initialize sqlalchemy +db = SQLAlchemy() +migrate = Migrate() + +# set the database connection string +DATABASE_CONNECTION_STRING = 'postgresql+psycopg2://postgres:postgres@localhost:5432/our_universe' def create_app(test_config=None): app = Flask(__name__) + # configure sql alchemy + app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False + app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_CONNECTION_STRING + + # import models + from app.models.planet import Planet + + # hook up flask and sql alchemy + db.init_app(app) + migrate.init_app(app, db) + from .routes import planets_bp app.register_blueprint(planets_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..e69de29bb diff --git a/app/planets.py b/app/planets.py index ba35e47c9..4f258acbf 100644 --- a/app/planets.py +++ b/app/planets.py @@ -17,4 +17,5 @@ def create_planet_dictionary(self): "name": self.name, "description": self.description, "has moons": self.has_moons - } \ No newline at end of file + } + diff --git a/app/routes.py b/app/routes.py index 5c9034c3c..e03312989 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,5 +1,7 @@ from flask import Blueprint, jsonify from .list_of_planets import planets +from app.models.planet import Planet +from app import db planets_bp = Blueprint("planets", __name__, url_prefix="/planets") From 44d2a28e13288cf4563092f4c61e36694a994a86 Mon Sep 17 00:00:00 2001 From: goblinbrooke Date: Mon, 25 Oct 2021 13:52:43 -0700 Subject: [PATCH 09/22] Created new Planet Class --- app/models/planet.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/app/models/planet.py b/app/models/planet.py index e69de29bb..14ffcc87c 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -0,0 +1,17 @@ +from app import db + +class Planet(db.Model): + + __tablename__ = "planets" + id = db.Column(db.Integer, primary_key = True, autoincrement = True) + name = db.Column(db.String(50)) + description = db.Column(db.String(200)) + has_moons = db.Column(db.Boolean) + + def create_planet_dictionary(self): + return { + "id": self.id, + "name": self.name, + "description": self.description, + "has moons": self.has_moons + } \ No newline at end of file From d3187ca3b5c5cf6da7058feeb738c781e5ad11e2 Mon Sep 17 00:00:00 2001 From: goblinbrooke Date: Mon, 25 Oct 2021 14:26:43 -0700 Subject: [PATCH 10/22] GET and POST --- app/routes.py | 42 ++++++-- migrations/README | 1 + migrations/alembic.ini | 45 +++++++++ migrations/env.py | 96 +++++++++++++++++++ migrations/script.py.mako | 24 +++++ .../83d4f23ae332_added_a_planet_model.py | 34 +++++++ 6 files changed, 235 insertions(+), 7 deletions(-) create mode 100644 migrations/README create mode 100644 migrations/alembic.ini create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/83d4f23ae332_added_a_planet_model.py diff --git a/app/routes.py b/app/routes.py index e03312989..ed4eb3fef 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,18 +1,46 @@ -from flask import Blueprint, jsonify -from .list_of_planets import planets +from flask import Blueprint, jsonify, request +# from .list_of_planets import planets from app.models.planet import Planet from app import db planets_bp = Blueprint("planets", __name__, url_prefix="/planets") -@planets_bp.route("", methods=["GET"]) +@planets_bp.route("", methods=["GET", "POST"]) def handle_planets(): + if request.method == "POST": + request_body = request.get_json() + if "name" not in request_body or "description" not in request_body or "has_moons" not in request_body: + return jsonify({"message": "Missing information - you need name, description, and if the planet has moons."}), 400 - list_of_planets = [] - for planet in planets: - list_of_planets.append(planet.create_planet_dictionary()), 200 + new_planet = Planet(name = request_body["name"], description = request_body["description"], has_moons = request_body["has_moons"]) + + db.session.add(new_planet) + db.session.commit() + + return f"New Planet {new_planet.name} Added!", 201 + elif request.method == "GET": + planets = Planet.query.all() + planet_list = [] + for planet in planets: + planet_list.append(planet.create_planet_dictionary) + + return jsonify(planet_list), 200 +# Able to take both Get and Post requests +# If POST: set up a variable to hold request body +# Use variable to create new planet instance +# Add to .db session +# Comit db session +# Return a response with a 201 status code +# If GET: Query database, get all planets +# Create planets as dictionaries, put in a list +# Return jsonify list + + + # list_of_planets = [] + # for planet in planets: + # list_of_planets.append(planet.create_planet_dictionary()), 200 - return jsonify(list_of_planets) + # return jsonify(list_of_planets) @planets_bp.route("/", methods=["GET"]) def handle_planet(planet_id): 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/83d4f23ae332_added_a_planet_model.py b/migrations/versions/83d4f23ae332_added_a_planet_model.py new file mode 100644 index 000000000..3af8c4e58 --- /dev/null +++ b/migrations/versions/83d4f23ae332_added_a_planet_model.py @@ -0,0 +1,34 @@ +"""Added a Planet Model + +Revision ID: 83d4f23ae332 +Revises: +Create Date: 2021-10-25 14:05:53.661140 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '83d4f23ae332' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('planets', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('name', sa.String(length=50), nullable=True), + sa.Column('description', sa.String(length=200), nullable=True), + sa.Column('has_moons', sa.Boolean(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('planets') + # ### end Alembic commands ### From a1b83683541accf5370ef158366bc6232b5b7808 Mon Sep 17 00:00:00 2001 From: goblinbrooke Date: Mon, 25 Oct 2021 15:22:21 -0700 Subject: [PATCH 11/22] "Fixed Bugs" --- app/routes.py | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/app/routes.py b/app/routes.py index ed4eb3fef..1817ae2bf 100644 --- a/app/routes.py +++ b/app/routes.py @@ -9,20 +9,28 @@ def handle_planets(): if request.method == "POST": request_body = request.get_json() - if "name" not in request_body or "description" not in request_body or "has_moons" not in request_body: - return jsonify({"message": "Missing information - you need name, description, and if the planet has moons."}), 400 - new_planet = Planet(name = request_body["name"], description = request_body["description"], has_moons = request_body["has_moons"]) + if type(request_body) == list: + for planet in request_body: + new_planet = Planet(name = planet["name"], description = planet["description"], has_moons = planet["has_moons"]) - db.session.add(new_planet) - db.session.commit() + db.session.add(new_planet) + db.session.commit() + else: + new_planet = Planet(name = request_body["name"], description = request_body["description"], has_moons = request_body["has_moons"]) + if "name" not in request_body or "description" not in request_body or "has_moons" not in request_body: + return jsonify({"message": "Missing information - you need name, description, and if the planet has moons."}), 400 + + db.session.add(new_planet) + db.session.commit() + + return f"New Planets Added!", 201 - return f"New Planet {new_planet.name} Added!", 201 elif request.method == "GET": planets = Planet.query.all() planet_list = [] for planet in planets: - planet_list.append(planet.create_planet_dictionary) + planet_list.append(planet.create_planet_dictionary()) return jsonify(planet_list), 200 # Able to take both Get and Post requests @@ -44,6 +52,8 @@ def handle_planets(): @planets_bp.route("/", methods=["GET"]) def handle_planet(planet_id): + print(planet_id) + for planet in planets: if int(planet_id) == planet.id: return jsonify(planet.create_planet_dictionary()) \ No newline at end of file From 4e2dd6d029f93c8cdec32656a48a957726e8539e Mon Sep 17 00:00:00 2001 From: sarahstandish Date: Mon, 25 Oct 2021 15:23:17 -0700 Subject: [PATCH 12/22] various bug fixes --- app/routes.py | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/app/routes.py b/app/routes.py index ed4eb3fef..42bd7aab6 100644 --- a/app/routes.py +++ b/app/routes.py @@ -9,20 +9,26 @@ def handle_planets(): if request.method == "POST": request_body = request.get_json() - if "name" not in request_body or "description" not in request_body or "has_moons" not in request_body: - return jsonify({"message": "Missing information - you need name, description, and if the planet has moons."}), 400 - new_planet = Planet(name = request_body["name"], description = request_body["description"], has_moons = request_body["has_moons"]) + if type(request_body) == list: + for planet in request_body: + new_planet = Planet(name = planet["name"], description = planet["description"], has_moons = planet["has_moons"]) + db.session.add(new_planet) + db.session.commit() + else: + new_planet = Planet(name = request_body["name"], description = request_body["description"], has_moons = request_body["has_moons"]) + if "name" not in request_body or "description" not in request_body or "has_moons" not in request_body: + return jsonify({"message": "Missing information - you need name, description, and if the planet has moons."}), 400 - db.session.add(new_planet) - db.session.commit() + db.session.add(new_planet) + db.session.commit() return f"New Planet {new_planet.name} Added!", 201 elif request.method == "GET": planets = Planet.query.all() planet_list = [] for planet in planets: - planet_list.append(planet.create_planet_dictionary) + planet_list.append(planet.create_planet_dictionary()) return jsonify(planet_list), 200 # Able to take both Get and Post requests @@ -35,15 +41,15 @@ def handle_planets(): # Create planets as dictionaries, put in a list # Return jsonify list +# list_of_planets = [] +# for planet in planets: +# list_of_planets.append(planet.create_planet_dictionary()), 200 - # list_of_planets = [] - # for planet in planets: - # list_of_planets.append(planet.create_planet_dictionary()), 200 - - # return jsonify(list_of_planets) +# return jsonify(list_of_planets) @planets_bp.route("/", methods=["GET"]) def handle_planet(planet_id): - for planet in planets: - if int(planet_id) == planet.id: - return jsonify(planet.create_planet_dictionary()) \ No newline at end of file + pass + # for planet in planets: + # if int(planet_id) == planet.id: + # return jsonify(planet.create_planet_dictionary()) \ No newline at end of file From f598d140d57c58f8de4d3e5095b343a466a62ea6 Mon Sep 17 00:00:00 2001 From: goblinbrooke Date: Mon, 25 Oct 2021 15:32:11 -0700 Subject: [PATCH 13/22] "GET 1 Planet" --- app/routes.py | 27 +++++++-------------------- 1 file changed, 7 insertions(+), 20 deletions(-) diff --git a/app/routes.py b/app/routes.py index 1817ae2bf..be5049f41 100644 --- a/app/routes.py +++ b/app/routes.py @@ -33,27 +33,14 @@ def handle_planets(): planet_list.append(planet.create_planet_dictionary()) return jsonify(planet_list), 200 -# Able to take both Get and Post requests -# If POST: set up a variable to hold request body -# Use variable to create new planet instance -# Add to .db session -# Comit db session -# Return a response with a 201 status code -# If GET: Query database, get all planets -# Create planets as dictionaries, put in a list -# Return jsonify list - - - # list_of_planets = [] - # for planet in planets: - # list_of_planets.append(planet.create_planet_dictionary()), 200 - - # return jsonify(list_of_planets) @planets_bp.route("/", methods=["GET"]) def handle_planet(planet_id): - print(planet_id) - for planet in planets: - if int(planet_id) == planet.id: - return jsonify(planet.create_planet_dictionary()) \ No newline at end of file + planet_id = int(planet_id) + planet = Planet.query.get(planet_id) + + if planet: + return jsonify(planet.create_planet_dictionary()) + + return { "Error" : f"Planet {planet_id} was not found."}, 404 \ No newline at end of file From 731a9940a9db7d0543782cc56719f79269b08787 Mon Sep 17 00:00:00 2001 From: sarahstandish Date: Mon, 25 Oct 2021 15:34:45 -0700 Subject: [PATCH 14/22] not sure what these changes are --- app/__init__.py | 1 - 1 file changed, 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index 004368d63..68fecff56 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -9,7 +9,6 @@ # set the database connection string DATABASE_CONNECTION_STRING = 'postgresql+psycopg2://postgres:postgres@localhost:5432/our_universe' - def create_app(test_config=None): app = Flask(__name__) From b0b623577b7aa83955b7dc35e342bbb97ad6b44e Mon Sep 17 00:00:00 2001 From: sarahstandish Date: Tue, 26 Oct 2021 10:54:00 -0700 Subject: [PATCH 15/22] resolving changes --- app/routes.py | 37 ------------------------------------- 1 file changed, 37 deletions(-) diff --git a/app/routes.py b/app/routes.py index 9300d03ea..755d2c866 100644 --- a/app/routes.py +++ b/app/routes.py @@ -13,17 +13,6 @@ def handle_planets(): if type(request_body) == list: for planet in request_body: new_planet = Planet(name = planet["name"], description = planet["description"], has_moons = planet["has_moons"]) -<<<<<<< HEAD - db.session.add(new_planet) - db.session.commit() - else: - new_planet = Planet(name = request_body["name"], description = request_body["description"], has_moons = request_body["has_moons"]) - if "name" not in request_body or "description" not in request_body or "has_moons" not in request_body: - return jsonify({"message": "Missing information - you need name, description, and if the planet has moons."}), 400 - - db.session.add(new_planet) - db.session.commit() -======= db.session.add(new_planet) db.session.commit() @@ -36,7 +25,6 @@ def handle_planets(): db.session.commit() return f"New Planets Added!", 201 ->>>>>>> f598d140d57c58f8de4d3e5095b343a466a62ea6 elif request.method == "GET": planets = Planet.query.all() @@ -45,30 +33,6 @@ def handle_planets(): planet_list.append(planet.create_planet_dictionary()) return jsonify(planet_list), 200 -<<<<<<< HEAD -# Able to take both Get and Post requests -# If POST: set up a variable to hold request body -# Use variable to create new planet instance -# Add to .db session -# Comit db session -# Return a response with a 201 status code -# If GET: Query database, get all planets -# Create planets as dictionaries, put in a list -# Return jsonify list - -# list_of_planets = [] -# for planet in planets: -# list_of_planets.append(planet.create_planet_dictionary()), 200 - -# return jsonify(list_of_planets) - -@planets_bp.route("/", methods=["GET"]) -def handle_planet(planet_id): - pass - # for planet in planets: - # if int(planet_id) == planet.id: - # return jsonify(planet.create_planet_dictionary()) -======= @planets_bp.route("/", methods=["GET"]) def handle_planet(planet_id): @@ -80,4 +44,3 @@ def handle_planet(planet_id): return jsonify(planet.create_planet_dictionary()) return { "Error" : f"Planet {planet_id} was not found."}, 404 ->>>>>>> f598d140d57c58f8de4d3e5095b343a466a62ea6 From d4a4e7de3ab2354bae309b45cdc679b687adb4d4 Mon Sep 17 00:00:00 2001 From: sarahstandish Date: Tue, 26 Oct 2021 10:54:35 -0700 Subject: [PATCH 16/22] resolve merge conflicts --- app/routes.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index 755d2c866..e7c9fbbb7 100644 --- a/app/routes.py +++ b/app/routes.py @@ -5,7 +5,7 @@ planets_bp = Blueprint("planets", __name__, url_prefix="/planets") -@planets_bp.route("", methods=["GET", "POST"]) +@planets_bp.giroute("", methods=["GET", "POST"]) def handle_planets(): if request.method == "POST": request_body = request.get_json() From 4c217a93130f0c1d65079e19a2f167b91fbc87d1 Mon Sep 17 00:00:00 2001 From: goblinbrooke Date: Tue, 26 Oct 2021 11:19:56 -0700 Subject: [PATCH 17/22] DESTROYED PLANET --- app/routes.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/app/routes.py b/app/routes.py index be5049f41..a031b692f 100644 --- a/app/routes.py +++ b/app/routes.py @@ -34,13 +34,18 @@ def handle_planets(): return jsonify(planet_list), 200 -@planets_bp.route("/", methods=["GET"]) +@planets_bp.route("/", methods=["GET", "DELETE"]) def handle_planet(planet_id): planet_id = int(planet_id) planet = Planet.query.get(planet_id) - if planet: + if not planet: + return { "Error" : f"Planet {planet_id} was not found."}, 404 + if request.method == "GET": return jsonify(planet.create_planet_dictionary()) - - return { "Error" : f"Planet {planet_id} was not found."}, 404 \ No newline at end of file + elif request.method == "DELETE": + Planet.query.delete(planet) + db.session.commit() + return jsonify({"Message": f"Success! Planet with {planet_id} was destroyed!"}) + \ No newline at end of file From 6f9fc100c362b610d837c7adc13cd7790ac49047 Mon Sep 17 00:00:00 2001 From: sarahstandish Date: Tue, 26 Oct 2021 11:20:49 -0700 Subject: [PATCH 18/22] resolve merge conflict --- app/routes.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index e7c9fbbb7..5307b0796 100644 --- a/app/routes.py +++ b/app/routes.py @@ -5,7 +5,7 @@ planets_bp = Blueprint("planets", __name__, url_prefix="/planets") -@planets_bp.giroute("", methods=["GET", "POST"]) +@planets_bp.route("", methods=["GET", "POST"]) def handle_planets(): if request.method == "POST": request_body = request.get_json() @@ -44,3 +44,4 @@ def handle_planet(planet_id): return jsonify(planet.create_planet_dictionary()) return { "Error" : f"Planet {planet_id} was not found."}, 404 + From 532261e255981f184f0752a125b043a4109bf798 Mon Sep 17 00:00:00 2001 From: sarahstandish Date: Tue, 26 Oct 2021 11:25:34 -0700 Subject: [PATCH 19/22] add PUT route --- app/routes.py | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/app/routes.py b/app/routes.py index 4d20022ba..766319d2c 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,4 +1,4 @@ -from flask import Blueprint, jsonify, request +from flask import Blueprint, json, jsonify, request # from .list_of_planets import planets from app.models.planet import Planet from app import db @@ -34,7 +34,7 @@ def handle_planets(): return jsonify(planet_list), 200 -@planets_bp.route("/", methods=["GET", "DELETE"]) +@planets_bp.route("/", methods=["GET", "DELETE", "PUT"]) def handle_planet(planet_id): planet_id = int(planet_id) @@ -42,10 +42,22 @@ def handle_planet(planet_id): if not planet: return { "Error" : f"Planet {planet_id} was not found."}, 404 + if request.method == "GET": return jsonify(planet.create_planet_dictionary()) + elif request.method == "DELETE": Planet.query.delete(planet) db.session.commit() return jsonify({"Message": f"Success! Planet with {planet_id} was destroyed!"}) + + elif request.method == "PUT": + input_data = request.get_json() + planet.name = input_data["name"] + planet.description = input_data["description"] + planet.has_moons = input_data["has_moons"] + + db.session.commit() + + return jsonify(planet.create_planet_dictionary()), 200 From ebfb222b97ee3822a50e31661bb9d7d6167cefe1 Mon Sep 17 00:00:00 2001 From: sarahstandish Date: Tue, 26 Oct 2021 11:29:10 -0700 Subject: [PATCH 20/22] fix error in delete endpoint --- app/routes.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/routes.py b/app/routes.py index 766319d2c..0751fc5ef 100644 --- a/app/routes.py +++ b/app/routes.py @@ -47,9 +47,9 @@ def handle_planet(planet_id): return jsonify(planet.create_planet_dictionary()) elif request.method == "DELETE": - Planet.query.delete(planet) + db.session.delete(planet) db.session.commit() - return jsonify({"Message": f"Success! Planet with {planet_id} was destroyed!"}) + return jsonify({"Message": f"Success! Planet with id {planet_id} was destroyed!"}) elif request.method == "PUT": input_data = request.get_json() From 97e50063ff3d9ad71dd4e5994343ea859f877b45 Mon Sep 17 00:00:00 2001 From: goblinbrooke Date: Thu, 28 Oct 2021 11:31:51 -0700 Subject: [PATCH 21/22] "Test Config + First Test" Co-authored-by: sarahstandish --- .gitignore | 1 + app/__init__.py | 16 +++++++++++----- app/routes.py | 3 +-- tests/__init__.py | 0 tests/conftest.py | 21 +++++++++++++++++++++ tests/test_routes.py | 8 ++++++++ 6 files changed, 42 insertions(+), 7 deletions(-) create mode 100644 tests/__init__.py create mode 100644 tests/conftest.py create mode 100644 tests/test_routes.py diff --git a/.gitignore b/.gitignore index 4e9b18359..1bfc66fc1 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ __pycache__/ *.py[cod] *$py.class +.env # C extensions *.so diff --git a/app/__init__.py b/app/__init__.py index 68fecff56..f933dec03 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,20 +1,26 @@ from flask import Flask from flask_sqlalchemy import SQLAlchemy -from flask_migrate import Migrate +from flask_migrate import Migrate +from dotenv import load_dotenv +import os # initialize sqlalchemy db = SQLAlchemy() migrate = Migrate() +load_dotenv() -# set the database connection string -DATABASE_CONNECTION_STRING = 'postgresql+psycopg2://postgres:postgres@localhost:5432/our_universe' def create_app(test_config=None): app = Flask(__name__) # configure sql alchemy - app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False - app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_CONNECTION_STRING + if not test_config: + app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_CONNECTION_STRING') + else: + app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('TEST_DATABASE_CONNECTION_STRING') + app.config['TESTING'] = True # import models from app.models.planet import Planet diff --git a/app/routes.py b/app/routes.py index 0751fc5ef..6915ccd39 100644 --- a/app/routes.py +++ b/app/routes.py @@ -59,5 +59,4 @@ def handle_planet(planet_id): db.session.commit() - return jsonify(planet.create_planet_dictionary()), 200 - + return jsonify(planet.create_planet_dictionary()), 200 \ No newline at end of file diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 000000000..3dcde1d36 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,21 @@ +import pytest +from app import create_app +from app import db +from app.models.planet import Planet + + +@pytest.fixture +def app(): + app = create_app({"TESTING": True}) + + with app.app_context(): + db.create_all() + yield app + + with app.app_context(): + db.drop_all() + + +@pytest.fixture +def client(app): + return app.test_client() \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py new file mode 100644 index 000000000..4cf3d118d --- /dev/null +++ b/tests/test_routes.py @@ -0,0 +1,8 @@ +def test_get_planets(client): + # Act + response = client.get("/planets") + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert response_body == [] \ No newline at end of file From d4c67755a9722a3b60fbeb0493376348e0118f30 Mon Sep 17 00:00:00 2001 From: goblinbrooke Date: Thu, 28 Oct 2021 12:02:10 -0700 Subject: [PATCH 22/22] All Tests Passed!! Final --- tests/conftest.py | 15 ++++++++++++- tests/test_routes.py | 53 +++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 66 insertions(+), 2 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index 3dcde1d36..7608bd6c5 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -18,4 +18,17 @@ def app(): @pytest.fixture def client(app): - return app.test_client() \ No newline at end of file + return app.test_client() + +@pytest.fixture +def one_planet(app): + planet1 = Planet(name="Mercury", description="Closest to the sun, hot.", has_moons=0) + db.session.add(planet1) + db.session.commit() + +@pytest.fixture +def two_planets(app): + planet1 = Planet(name="Mercury", description="Closest to the sun, hot.", has_moons=0) + planet2 = Planet(name="Venus", description="Spins the opposite direction of other planets.", has_moons=0) + db.session.add_all([planet1, planet2]) + db.session.commit() \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py index 4cf3d118d..283175304 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -5,4 +5,55 @@ def test_get_planets(client): # Assert assert response.status_code == 200 - assert response_body == [] \ No newline at end of file + assert response_body == [] + +def test_get_all_planets_with_one_record(client, one_planet): + # Act + response = client.get("/planets/1") + response_body = response.get_json() + + #Assert + assert response.status_code == 200 + assert len(response_body) == 4 + assert response_body == { + "name" : "Mercury", + "description" : "Closest to the sun, hot.", + "has moons" : False, + "id" : 1 + } + +def test_get_all_planets_with_one_record_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_returns_array(client, two_planets): + # Act + response = client.get("/planets") + response_body = response.get_json() + + #Assert + assert response.status_code == 200 + assert len(response_body) == 2 + assert response_body == [{ + "name" : "Mercury", + "description" : "Closest to the sun, hot.", + "has moons" : False, + "id" : 1 + }, { + "name" : "Venus", + "description" : "Spins the opposite direction of other planets.", + "has moons" : False, + "id" : 2 + }] + +def test_post_all_planets_returns_201(client): + # Act + response = client.post("/planets", json = {"name": "Venus", "description": "Spins the opposite direction of other planets", "has_moons": 0}) + response_body = response.get_json() + + #Assert + assert response.status_code == 201 \ No newline at end of file