From 5f09c26822945fd1f9f596654c49ae9a3dd0c4a7 Mon Sep 17 00:00:00 2001 From: Melinda Date: Mon, 18 Oct 2021 14:23:13 -0700 Subject: [PATCH 01/22] created planet class and a list of planet instances --- app/routes.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..86375f4bd 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,16 @@ -from flask import Blueprint +from flask import Blueprint, jasonify + +class Planet: + def __init__(self, id , name , description , moons): + self.id = id + self.name = name + self.description = description + self.moons = moons + +planets = [ + Planet(1,"earth","our world",["Moon"]), + Planet(2,"mars","The red planet",["Phobos","Deimos"]), + Planet(3,"jupiter", "The biggest one",["Lo","Europa","Callisto","Gayemede"]) + +] From db2cfa9b1a584d3ca8e8df5f41675d388c3d6c1f Mon Sep 17 00:00:00 2001 From: Mac Date: Mon, 18 Oct 2021 14:44:57 -0700 Subject: [PATCH 02/22] Created an end point to read all planets --- app/__init__.py | 3 +++ app/routes.py | 16 ++++++++++++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..ab9eee40e 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -4,4 +4,7 @@ def create_app(test_config=None): app = Flask(__name__) + from .routes import planets_bp + app.register_blueprint(planets_bp) + return app diff --git a/app/routes.py b/app/routes.py index 86375f4bd..19c6ebd52 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,4 +1,4 @@ -from flask import Blueprint, jasonify +from flask import Blueprint, jsonify class Planet: def __init__(self, id , name , description , moons): @@ -11,6 +11,18 @@ def __init__(self, id , name , description , moons): Planet(1,"earth","our world",["Moon"]), Planet(2,"mars","The red planet",["Phobos","Deimos"]), Planet(3,"jupiter", "The biggest one",["Lo","Europa","Callisto","Gayemede"]) - ] +planets_bp = Blueprint("planet", __name__, url_prefix="/planets") + +@planets_bp.route("", methods=["GET"]) +def get_all_planets(): + planets_response = [] + for planet in planets: + planets_response.append({ + "id": planet.id, + "name": planet.name, + "description": planet.description, + "moons": planet.moons + }) + return jsonify(planets_response) \ No newline at end of file From 74e422c50bf293246d64a592fed310fdf9bd4fcb Mon Sep 17 00:00:00 2001 From: Mac Date: Mon, 18 Oct 2021 14:54:04 -0700 Subject: [PATCH 03/22] refactored code with vars() and list comprehension --- app/routes.py | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/app/routes.py b/app/routes.py index 19c6ebd52..42223c014 100644 --- a/app/routes.py +++ b/app/routes.py @@ -17,12 +17,6 @@ def __init__(self, id , name , description , moons): @planets_bp.route("", methods=["GET"]) def get_all_planets(): - planets_response = [] - for planet in planets: - planets_response.append({ - "id": planet.id, - "name": planet.name, - "description": planet.description, - "moons": planet.moons - }) + planets_response = [vars(planet) for planet in planets] + return jsonify(planets_response) \ No newline at end of file From 3f8e5e72202780c51b728eaa5d8899d60f926146 Mon Sep 17 00:00:00 2001 From: Melinda Date: Mon, 18 Oct 2021 15:09:42 -0700 Subject: [PATCH 04/22] created endpoint for one planet request --- app/routes.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index 42223c014..b3409c5f0 100644 --- a/app/routes.py +++ b/app/routes.py @@ -19,4 +19,11 @@ def __init__(self, id , name , description , moons): def get_all_planets(): planets_response = [vars(planet) for planet in planets] - return jsonify(planets_response) \ No newline at end of file + return jsonify(planets_response) + +@planets_bp.route("/", methods=["GET"]) +def get_one_planet(planet_id): + planet_id = int(planet_id) + for planet in planets: + if planet.id == planet_id: + return vars(planet) \ No newline at end of file From 5d43de4c8eefb870a94f7642b74276588c9290db Mon Sep 17 00:00:00 2001 From: Mac Date: Mon, 25 Oct 2021 13:58:41 -0700 Subject: [PATCH 05/22] Adds Planet model and connects to psql database through flask --- app/__init__.py | 13 +++ app/models/__init__.py | 0 app/models/planet.py | 8 ++ migrations/README | 1 + migrations/alembic.ini | 45 +++++++++ migrations/env.py | 96 +++++++++++++++++++ migrations/script.py.mako | 24 +++++ .../0ad3b52109c1_adds_planet_model.py | 34 +++++++ 8 files changed, 221 insertions(+) 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/0ad3b52109c1_adds_planet_model.py diff --git a/app/__init__.py b/app/__init__.py index ab9eee40e..60fbcce3b 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,10 +1,23 @@ from flask import Flask +from flask_sqlalchemy import SQLAlchemy +from flask_migrate import Migrate +db = SQLAlchemy() +migrate = Migrate() def create_app(test_config=None): app = Flask(__name__) + app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False + app.config['SQLALCHEMY_DATABASE_URI'] = \ + 'postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system_development' + + db.init_app(app) + migrate.init_app(app, db) + from .routes import planets_bp app.register_blueprint(planets_bp) + from app.models.planet import Planet + return app diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/app/models/planet.py b/app/models/planet.py new file mode 100644 index 000000000..7fc36c2cc --- /dev/null +++ b/app/models/planet.py @@ -0,0 +1,8 @@ +from app import db + +class Planet(db.Model): + __name__ = 'planets' + id = db.Column(db.Integer, primary_key = True, autoincrement=True) + name = db.Column(db.String) + description = db.Column(db.String) + moons = db.Column(db.String) \ No newline at end of file diff --git a/migrations/README b/migrations/README new file mode 100644 index 000000000..98e4f9c44 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 000000000..f8ed4801f --- /dev/null +++ b/migrations/alembic.ini @@ -0,0 +1,45 @@ +# A generic, single database configuration. + +[alembic] +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 000000000..8b3fb3353 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,96 @@ +from __future__ import with_statement + +import logging +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool +from flask import current_app + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) +logger = logging.getLogger('alembic.env') + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +config.set_main_option( + 'sqlalchemy.url', + str(current_app.extensions['migrate'].db.engine.url).replace('%', '%%')) +target_metadata = current_app.extensions['migrate'].db.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, target_metadata=target_metadata, literal_binds=True + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + # this callback is used to prevent an auto-migration from being generated + # when there are no changes to the schema + # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html + def process_revision_directives(context, revision, directives): + if getattr(config.cmd_opts, 'autogenerate', False): + script = directives[0] + if script.upgrade_ops.is_empty(): + directives[:] = [] + logger.info('No changes in schema detected.') + + connectable = engine_from_config( + config.get_section(config.config_ini_section), + prefix='sqlalchemy.', + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=target_metadata, + process_revision_directives=process_revision_directives, + **current_app.extensions['migrate'].configure_args + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 000000000..2c0156303 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,24 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} diff --git a/migrations/versions/0ad3b52109c1_adds_planet_model.py b/migrations/versions/0ad3b52109c1_adds_planet_model.py new file mode 100644 index 000000000..5822e3ee4 --- /dev/null +++ b/migrations/versions/0ad3b52109c1_adds_planet_model.py @@ -0,0 +1,34 @@ +"""adds Planet model + +Revision ID: 0ad3b52109c1 +Revises: +Create Date: 2021-10-25 13:54:32.121690 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '0ad3b52109c1' +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('moons', 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 72e08e86085b7ff34c3829bd6fc5a68173be76c7 Mon Sep 17 00:00:00 2001 From: Mac Date: Mon, 25 Oct 2021 14:15:09 -0700 Subject: [PATCH 06/22] adds route for planet post request --- app/routes.py | 30 ++++++++++++------------------ 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/app/routes.py b/app/routes.py index b3409c5f0..ed34ff010 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,25 +1,19 @@ -from flask import Blueprint, jsonify - -class Planet: - def __init__(self, id , name , description , moons): - self.id = id - self.name = name - self.description = description - self.moons = moons - -planets = [ - Planet(1,"earth","our world",["Moon"]), - Planet(2,"mars","The red planet",["Phobos","Deimos"]), - Planet(3,"jupiter", "The biggest one",["Lo","Europa","Callisto","Gayemede"]) -] +from app import db +from app.models.planet import Planet +from flask import Blueprint, jsonify, make_response, request planets_bp = Blueprint("planet", __name__, url_prefix="/planets") -@planets_bp.route("", methods=["GET"]) -def get_all_planets(): - planets_response = [vars(planet) for planet in planets] +@planets_bp.route("", methods=["POST"]) +def create_planet(): + request_body = request.get_json() + new_planet = Planet(name=request_body["name"], + description=request_body["description"]) + + db.session.add(new_planet) + db.session.commit() - return jsonify(planets_response) + return make_response(f"Planet {new_planet.name} successfully created", 201) @planets_bp.route("/", methods=["GET"]) def get_one_planet(planet_id): From 00da8f95a39642d09ea7eae36997888df650803d Mon Sep 17 00:00:00 2001 From: Mac Date: Mon, 25 Oct 2021 14:25:26 -0700 Subject: [PATCH 07/22] Adds end point that returns a list of all the planets with their info for get request --- app/routes.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/app/routes.py b/app/routes.py index ed34ff010..aff18de82 100644 --- a/app/routes.py +++ b/app/routes.py @@ -15,6 +15,19 @@ def create_planet(): return make_response(f"Planet {new_planet.name} successfully created", 201) +@planets_bp.route("", methods=["GET"]) +def get_planets(): + planets = Planet.query.all() + planets_response = [] + for planet in planets: + planets_response.append({ + "id": planet.id, + "name": planet.name, + "description": planet.description, + "moons": planet.moons + }) + return jsonify(planets_response) + @planets_bp.route("/", methods=["GET"]) def get_one_planet(planet_id): planet_id = int(planet_id) From fcc5ec2b25339dea1142d945b5cc6059ce692059 Mon Sep 17 00:00:00 2001 From: Mac Date: Mon, 25 Oct 2021 14:29:49 -0700 Subject: [PATCH 08/22] Adds endpoint that returns info of one planet that matches requested id --- app/routes.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index aff18de82..e07938672 100644 --- a/app/routes.py +++ b/app/routes.py @@ -31,6 +31,12 @@ def get_planets(): @planets_bp.route("/", methods=["GET"]) def get_one_planet(planet_id): planet_id = int(planet_id) + planets = Planet.query.all() for planet in planets: if planet.id == planet_id: - return vars(planet) \ No newline at end of file + return { + "id": planet.id, + "name": planet.name, + "description": planet.description, + "moons": planet.moons + } \ No newline at end of file From 83579b4e07356f0f9fca6b2f3ceccca6390af341 Mon Sep 17 00:00:00 2001 From: Mac Date: Mon, 25 Oct 2021 14:48:42 -0700 Subject: [PATCH 09/22] refactors get_one_planet to use get(planet_id) and removes for loop --- app/models/planet.py | 2 +- app/routes.py | 18 +++++++++--------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index 7fc36c2cc..659cb5d29 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -2,7 +2,7 @@ class Planet(db.Model): __name__ = 'planets' - id = db.Column(db.Integer, primary_key = True, autoincrement=True) + id = db.Column(db.Integer, primary_key = True, autoincrement = True) name = db.Column(db.String) description = db.Column(db.String) moons = db.Column(db.String) \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index e07938672..3a2adaf4b 100644 --- a/app/routes.py +++ b/app/routes.py @@ -8,7 +8,8 @@ def create_planet(): request_body = request.get_json() new_planet = Planet(name=request_body["name"], - description=request_body["description"]) + description=request_body["description"], + moons=request_body["moons"]) db.session.add(new_planet) db.session.commit() @@ -31,12 +32,11 @@ def get_planets(): @planets_bp.route("/", methods=["GET"]) def get_one_planet(planet_id): planet_id = int(planet_id) - planets = Planet.query.all() - for planet in planets: - if planet.id == planet_id: - return { - "id": planet.id, - "name": planet.name, - "description": planet.description, - "moons": planet.moons + planet = Planet.query.get(planet_id) + + return { + "id": planet.id, + "name": planet.name, + "description": planet.description, + "moons": planet.moons } \ No newline at end of file From 2ce8e0f1229b268f12fb3306fd892a1293e8f2b1 Mon Sep 17 00:00:00 2001 From: Mac Date: Mon, 25 Oct 2021 14:52:49 -0700 Subject: [PATCH 10/22] Returns 404 not found if planet with no id in table is input --- app/routes.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index 3a2adaf4b..b1c20ed2c 100644 --- a/app/routes.py +++ b/app/routes.py @@ -32,7 +32,7 @@ def get_planets(): @planets_bp.route("/", methods=["GET"]) def get_one_planet(planet_id): planet_id = int(planet_id) - planet = Planet.query.get(planet_id) + planet = Planet.query.get_or_404(planet_id) return { "id": planet.id, From 0eebaabe487f4a5fcd9c8d69d61608e4f1d1627a Mon Sep 17 00:00:00 2001 From: Mac Date: Mon, 25 Oct 2021 21:25:23 -0700 Subject: [PATCH 11/22] Creates end point for put request and updates a planet's info --- app/routes.py | 62 ++++++++++++++++++++++++++++++--------------------- 1 file changed, 37 insertions(+), 25 deletions(-) diff --git a/app/routes.py b/app/routes.py index b1c20ed2c..e3c647ca9 100644 --- a/app/routes.py +++ b/app/routes.py @@ -4,39 +4,51 @@ planets_bp = Blueprint("planet", __name__, url_prefix="/planets") -@planets_bp.route("", methods=["POST"]) -def create_planet(): - request_body = request.get_json() - new_planet = Planet(name=request_body["name"], +@planets_bp.route("", methods=["POST", "GET"]) +def handle_planet(): + if request.method == "POST": + request_body = request.get_json() + new_planet = Planet(name=request_body["name"], description=request_body["description"], moons=request_body["moons"]) - db.session.add(new_planet) - db.session.commit() + db.session.add(new_planet) + db.session.commit() - return make_response(f"Planet {new_planet.name} successfully created", 201) + return make_response(f"Planet {new_planet.name} successfully created", 201) -@planets_bp.route("", methods=["GET"]) -def get_planets(): - planets = Planet.query.all() - planets_response = [] - for planet in planets: - planets_response.append({ + elif request.method == "GET": + planets = Planet.query.all() + planets_response = [] + for planet in planets: + planets_response.append({ + "id": planet.id, + "name": planet.name, + "description": planet.description, + "moons": planet.moons + }) + return jsonify(planets_response) + +@planets_bp.route("/", methods=["GET", "PUT", "DELETE"]) +def handle_one_planet(planet_id): + planet_id = int(planet_id) + planet = Planet.query.get_or_404(planet_id) + + if request.method == "GET": + return { "id": planet.id, "name": planet.name, "description": planet.description, "moons": planet.moons - }) - return jsonify(planets_response) + } + + elif request.method == "PUT": + form_data = request.get_json() -@planets_bp.route("/", methods=["GET"]) -def get_one_planet(planet_id): - planet_id = int(planet_id) - planet = Planet.query.get_or_404(planet_id) + planet.name = form_data["name"] + planet.description = form_data["description"] + planet.moons = form_data["moons"] + + db.session.commit() - return { - "id": planet.id, - "name": planet.name, - "description": planet.description, - "moons": planet.moons - } \ No newline at end of file + return make_response(f"Planet {planet.name} successfully updated") \ No newline at end of file From 1aa1922d4c0ea0c2075e8eed96ad89309d5e020c Mon Sep 17 00:00:00 2001 From: Mac Date: Mon, 25 Oct 2021 21:28:02 -0700 Subject: [PATCH 12/22] Adds endpoint for deleting a planet and deletes the planet --- app/routes.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index e3c647ca9..89a3b1bcf 100644 --- a/app/routes.py +++ b/app/routes.py @@ -51,4 +51,9 @@ def handle_one_planet(planet_id): db.session.commit() - return make_response(f"Planet {planet.name} successfully updated") \ No newline at end of file + return make_response(f"Planet {planet.name} successfully updated") + + elif request.method == "DELETE": + db.session.delete(planet) + db.session.commit() + return make_response(f"Planet {planet.name} successfully deleted") \ No newline at end of file From d927b675a8f060ae600a97f345e0807937c2f2cf Mon Sep 17 00:00:00 2001 From: Mac Date: Tue, 26 Oct 2021 16:20:57 -0700 Subject: [PATCH 13/22] Adds function to_dict in planet model that converts planet data into a python dictionary --- app/models/planet.py | 14 ++++++++++++-- app/routes.py | 16 +++------------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index 659cb5d29..5f8316d92 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -1,8 +1,18 @@ from app import db class Planet(db.Model): - __name__ = 'planets' id = db.Column(db.Integer, primary_key = True, autoincrement = True) name = db.Column(db.String) description = db.Column(db.String) - moons = db.Column(db.String) \ No newline at end of file + moons = db.Column(db.String) + + def to_dict(self): + """Returns planet id, name, description, and moons \ + formatted into a python dictionary""" + + return({ + "id": self.id, + "name": self.name, + "description": self.description, + "moons": self.moons + }) \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 89a3b1bcf..9087fccd1 100644 --- a/app/routes.py +++ b/app/routes.py @@ -5,7 +5,7 @@ planets_bp = Blueprint("planet", __name__, url_prefix="/planets") @planets_bp.route("", methods=["POST", "GET"]) -def handle_planet(): +def handle_planets(): if request.method == "POST": request_body = request.get_json() new_planet = Planet(name=request_body["name"], @@ -21,12 +21,7 @@ def handle_planet(): planets = Planet.query.all() planets_response = [] for planet in planets: - planets_response.append({ - "id": planet.id, - "name": planet.name, - "description": planet.description, - "moons": planet.moons - }) + planets_response.append(planet.to_dict()) return jsonify(planets_response) @planets_bp.route("/", methods=["GET", "PUT", "DELETE"]) @@ -35,12 +30,7 @@ def handle_one_planet(planet_id): planet = Planet.query.get_or_404(planet_id) if request.method == "GET": - return { - "id": planet.id, - "name": planet.name, - "description": planet.description, - "moons": planet.moons - } + return jsonify(planet.to_dict()), 200 elif request.method == "PUT": form_data = request.get_json() From 043312cc340a03bde54880799d9e614a4a2941a0 Mon Sep 17 00:00:00 2001 From: Mac Date: Tue, 26 Oct 2021 16:27:54 -0700 Subject: [PATCH 14/22] Adds code that returns 400 error if name, description, or moons are not input in a post request. --- app/routes.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/app/routes.py b/app/routes.py index 9087fccd1..4521d7218 100644 --- a/app/routes.py +++ b/app/routes.py @@ -6,8 +6,14 @@ @planets_bp.route("", methods=["POST", "GET"]) def handle_planets(): + """dfssdfsdd """ if request.method == "POST": request_body = request.get_json() + + if "name" not in request_body or "description" not in request_body \ + or "moons" not in request_body: + return jsonify({"message": "Missing data"}), 400 + new_planet = Planet(name=request_body["name"], description=request_body["description"], moons=request_body["moons"]) From b23f7c2005d69c7d79309dd2ac25e57e9d812b35 Mon Sep 17 00:00:00 2001 From: Mac Date: Tue, 26 Oct 2021 16:37:50 -0700 Subject: [PATCH 15/22] Adds doc strings to handle_planets and handle_one_planet --- app/routes.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/app/routes.py b/app/routes.py index 4521d7218..13dedd397 100644 --- a/app/routes.py +++ b/app/routes.py @@ -6,7 +6,10 @@ @planets_bp.route("", methods=["POST", "GET"]) def handle_planets(): - """dfssdfsdd """ + """Handles POST and GET requests for /planets. + Returns success message if planet successfully created with POST request. + Returns data on all planets in JSON with GET request.""" + if request.method == "POST": request_body = request.get_json() @@ -28,10 +31,15 @@ def handle_planets(): planets_response = [] for planet in planets: planets_response.append(planet.to_dict()) - return jsonify(planets_response) + return jsonify(planets_response), 200 @planets_bp.route("/", methods=["GET", "PUT", "DELETE"]) def handle_one_planet(planet_id): + """Handles GET, PUT, and DELETE requests for one planet entry. + Reads and returns planet info for GET request with valid ID input or 404 for invalid ID input. + Updates planet entry and returns success message for PUT request. + Deletes specified planet entry and return success message for DELETE request.""" + planet_id = int(planet_id) planet = Planet.query.get_or_404(planet_id) @@ -52,4 +60,5 @@ def handle_one_planet(planet_id): elif request.method == "DELETE": db.session.delete(planet) db.session.commit() + return make_response(f"Planet {planet.name} successfully deleted") \ No newline at end of file From 1bbabe462600005c3a7e7ddaa78e7222d2643f65 Mon Sep 17 00:00:00 2001 From: Melinda Date: Thu, 28 Oct 2021 11:36:52 -0700 Subject: [PATCH 16/22] add test database and connects to create app --- app/__init__.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 60fbcce3b..02517d7f2 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,17 +1,26 @@ 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'] = \ + 'postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system_development' + 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) From 6f07d4ec7ec895c852c2eac50926bb76c8b34e16 Mon Sep 17 00:00:00 2001 From: Melinda Date: Thu, 28 Oct 2021 11:52:13 -0700 Subject: [PATCH 17/22] add conftest.py file with necessary code --- requirements.txt | 7 +++++++ tests/__init__.py | 0 tests/conftest.py | 20 ++++++++++++++++++++ tests/test_routes.py | 0 4 files changed, 27 insertions(+) create mode 100644 tests/__init__.py create mode 100644 tests/conftest.py create mode 100644 tests/test_routes.py diff --git a/requirements.txt b/requirements.txt index fd90fffa8..dcbd7413b 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,5 @@ alembic==1.5.4 +attrs==21.2.0 autopep8==1.5.5 certifi==2020.12.5 chardet==4.0.0 @@ -7,12 +8,18 @@ Flask==1.1.2 Flask-Migrate==2.6.0 Flask-SQLAlchemy==2.4.4 idna==2.10 +iniconfig==1.1.1 itsdangerous==1.1.0 Jinja2==2.11.3 Mako==1.1.4 MarkupSafe==1.1.1 +packaging==21.0 +pluggy==1.0.0 psycopg2-binary==2.8.6 +py==1.10.0 pycodestyle==2.6.0 +pyparsing==3.0.3 +pytest==6.2.5 python-dateutil==2.8.1 python-dotenv==0.15.0 python-editor==1.0.4 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..7c293ef65 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,20 @@ +import pytest +from app import create_app +from app import db + + +@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..e69de29bb From 221a4e3a4c019c0538e3d3c8fb79b29a7d31ff04 Mon Sep 17 00:00:00 2001 From: Melinda Date: Thu, 28 Oct 2021 12:22:22 -0700 Subject: [PATCH 18/22] create tetst for handle planets and passes --- tests/test_routes.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/test_routes.py b/tests/test_routes.py index e69de29bb..926fb4e69 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -0,0 +1,6 @@ +def test_handle_planets_returns_200_and_empty_array(client): + response = client.get("/planets") + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == [] \ No newline at end of file From 82124d877465cdd7e14bd43620224472876fdfba Mon Sep 17 00:00:00 2001 From: Mac Date: Fri, 29 Oct 2021 12:48:33 -0700 Subject: [PATCH 19/22] Refactors code to make consistent throughout --- app/__init__.py | 1 + app/models/planet.py | 2 +- app/routes.py | 14 +++++++------- tests/test_routes.py | 2 +- 4 files changed, 10 insertions(+), 9 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 02517d7f2..911fa7557 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -21,6 +21,7 @@ def create_app(test_config=None): 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/models/planet.py b/app/models/planet.py index 5f8316d92..ff396d7ae 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -12,7 +12,7 @@ def to_dict(self): return({ "id": self.id, - "name": self.name, + "name": self.name, "description": self.description, "moons": self.moons }) \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 13dedd397..0eb9bd254 100644 --- a/app/routes.py +++ b/app/routes.py @@ -15,7 +15,7 @@ def handle_planets(): if "name" not in request_body or "description" not in request_body \ or "moons" not in request_body: - return jsonify({"message": "Missing data"}), 400 + return make_response("Missing data", 400) new_planet = Planet(name=request_body["name"], description=request_body["description"], @@ -28,10 +28,10 @@ def handle_planets(): elif request.method == "GET": planets = Planet.query.all() - planets_response = [] + planets_response = {} for planet in planets: - planets_response.append(planet.to_dict()) - return jsonify(planets_response), 200 + planets_response[planet.name] = planet.to_dict() + return make_response(planets_response, 200) @planets_bp.route("/", methods=["GET", "PUT", "DELETE"]) def handle_one_planet(planet_id): @@ -44,7 +44,7 @@ def handle_one_planet(planet_id): planet = Planet.query.get_or_404(planet_id) if request.method == "GET": - return jsonify(planet.to_dict()), 200 + return make_response(planet.to_dict(), 200) elif request.method == "PUT": form_data = request.get_json() @@ -55,10 +55,10 @@ def handle_one_planet(planet_id): db.session.commit() - return make_response(f"Planet {planet.name} successfully updated") + return make_response(f"Planet {planet.name} successfully updated", 200) elif request.method == "DELETE": db.session.delete(planet) db.session.commit() - return make_response(f"Planet {planet.name} successfully deleted") \ No newline at end of file + return make_response(f"Planet {planet.name} successfully deleted", 200) \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py index 926fb4e69..e098f2011 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -3,4 +3,4 @@ def test_handle_planets_returns_200_and_empty_array(client): response_body = response.get_json() assert response.status_code == 200 - assert response_body == [] \ No newline at end of file + assert response_body == {} \ No newline at end of file From 3a0809c916b9179ba87c9111c7f21e7fdcd91a60 Mon Sep 17 00:00:00 2001 From: Melinda Date: Wed, 3 Nov 2021 11:13:01 -0700 Subject: [PATCH 20/22] added gunicorn --- requirements.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/requirements.txt b/requirements.txt index dcbd7413b..e3a0c228c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,6 +7,7 @@ click==7.1.2 Flask==1.1.2 Flask-Migrate==2.6.0 Flask-SQLAlchemy==2.4.4 +gunicorn==20.1.0 idna==2.10 iniconfig==1.1.1 itsdangerous==1.1.0 From e62b46a3e345fa8dc7ce6dd602ea4fe60179a26c Mon Sep 17 00:00:00 2001 From: Melinda Date: Wed, 3 Nov 2021 11:15:06 -0700 Subject: [PATCH 21/22] made Procfile --- Procfile | 1 + 1 file changed, 1 insertion(+) create mode 100644 Procfile diff --git a/Procfile b/Procfile new file mode 100644 index 000000000..62e430aca --- /dev/null +++ b/Procfile @@ -0,0 +1 @@ +web: gunicorn 'app:create_app()' \ No newline at end of file From 11b0a5bc68adc30563e76810b870d84de1a1f301 Mon Sep 17 00:00:00 2001 From: Melinda Date: Wed, 3 Nov 2021 11:57:24 -0700 Subject: [PATCH 22/22] updated database link --- app/__init__.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 911fa7557..5522a2a76 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -14,8 +14,7 @@ def create_app(test_config=None): if not test_config: app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False - app.config['SQLALCHEMY_DATABASE_URI'] = \ - 'postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system_development' + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("SQLALCHEMY_DATABASE_URI") else: app.config["TESTING"] = True app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False