From 17490c1a67d93bd0ec4214fa66390ff341bef9a7 Mon Sep 17 00:00:00 2001 From: kaitlyngore Date: Fri, 15 Oct 2021 14:09:33 -0400 Subject: [PATCH 01/20] added planet class and planet list --- app/planet.py | 0 app/routes.py | 22 +++++++++++++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 app/planet.py diff --git a/app/planet.py b/app/planet.py new file mode 100644 index 000000000..e69de29bb diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..74ad6ac71 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,22 @@ -from flask import Blueprint +from flask import Blueprint, jsonify +from planet import Planet +planets = [ + Planet(1, "Mercury", "Mercury is the smallest planet in the Solar System and the closest to the Sun", "terrestrial"), + Planet(2, "Venus", "Venus is the second planet from the Sun.", "terrestrial") +] + +planet_list_bp = Blueprint("planet_list_bp", __name__, url_prefix="/planets") + +@planet_list_bp.route("", methods=["GET"]) +def handle_planets(): + planet_response = [] + for planet in planets: + planet_response.append( + {"id:" planet.id, + "name": planet.name, + "description": planet.description}, + "type": planet.type + }) + + return jsonify(planet_response) \ No newline at end of file From 02a0bb22f4b096973daa2f027e307a880c15e8f6 Mon Sep 17 00:00:00 2001 From: kaitlyngore Date: Mon, 18 Oct 2021 16:14:47 -0400 Subject: [PATCH 02/20] added get planets --- app/routes.py | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/app/routes.py b/app/routes.py index 74ad6ac71..9f32dacc2 100644 --- a/app/routes.py +++ b/app/routes.py @@ -10,13 +10,15 @@ @planet_list_bp.route("", methods=["GET"]) def handle_planets(): - planet_response = [] + planets_response = [] for planet in planets: - planet_response.append( - {"id:" planet.id, - "name": planet.name, - "description": planet.description}, - "type": planet.type - }) - - return jsonify(planet_response) \ No newline at end of file + planets_response.append( + { + "id": planet.id, + "name": planet.name, + "description": planet.description, + "type": planet.type, + } + ) + return jsonify(planets_response) + \ No newline at end of file From 57e9761b2eb4055bf3e32d765088f7a1d0bf7fef Mon Sep 17 00:00:00 2001 From: kaitlyngore Date: Mon, 18 Oct 2021 16:30:09 -0400 Subject: [PATCH 03/20] made /planets work --- app/__init__.py | 3 ++- app/planet.py | 6 ++++++ app/routes.py | 2 +- 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..969dff8ef 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -3,5 +3,6 @@ def create_app(test_config=None): app = Flask(__name__) - + from .routes import planet_list_bp + app.register_blueprint(planet_list_bp) return app diff --git a/app/planet.py b/app/planet.py index e69de29bb..70302d187 100644 --- a/app/planet.py +++ b/app/planet.py @@ -0,0 +1,6 @@ +class Planet: + def __init__(self, id, name, description, type): + self.id = id + self.name = name + self.description = description + self.type = type diff --git a/app/routes.py b/app/routes.py index 9f32dacc2..76b5a655c 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,5 +1,5 @@ from flask import Blueprint, jsonify -from planet import Planet +from .planet import Planet planets = [ Planet(1, "Mercury", "Mercury is the smallest planet in the Solar System and the closest to the Sun", "terrestrial"), From 015dae67057bcdce53bd8a6af4ecbe64ad37c4f1 Mon Sep 17 00:00:00 2001 From: Nourhan Alenany Date: Mon, 18 Oct 2021 13:56:22 -0700 Subject: [PATCH 04/20] added one planet --- app/__init__.py | 5 +++-- app/routes.py | 16 +++++++++++++--- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 969dff8ef..773d64837 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -3,6 +3,7 @@ def create_app(test_config=None): app = Flask(__name__) - from .routes import planet_list_bp - app.register_blueprint(planet_list_bp) + from .routes import planet_bp + app.register_blueprint(planet_bp) + return app diff --git a/app/routes.py b/app/routes.py index 76b5a655c..1cab8f219 100644 --- a/app/routes.py +++ b/app/routes.py @@ -6,9 +6,9 @@ Planet(2, "Venus", "Venus is the second planet from the Sun.", "terrestrial") ] -planet_list_bp = Blueprint("planet_list_bp", __name__, url_prefix="/planets") +planet_bp = Blueprint("planet_bp", __name__, url_prefix="/planets") -@planet_list_bp.route("", methods=["GET"]) +@planet_bp.route("", methods=["GET"]) def handle_planets(): planets_response = [] for planet in planets: @@ -21,4 +21,14 @@ def handle_planets(): } ) return jsonify(planets_response) - \ No newline at end of file + +@planet_bp.route("/", methods=["GET"]) +def planet(planet_id): + planet_id = int(planet_id) + for planet in planets: + if planet.id == planet_id: + return { + "id": planet.id, + "title": planet.name, + "description": planet.description + } \ No newline at end of file From beb0962e82a25761396b59991fa45e142ecac071 Mon Sep 17 00:00:00 2001 From: kaitlyngore Date: Mon, 18 Oct 2021 17:36:46 -0400 Subject: [PATCH 05/20] updated get planet return data --- app/routes.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/app/routes.py b/app/routes.py index 1cab8f219..0c5f25192 100644 --- a/app/routes.py +++ b/app/routes.py @@ -29,6 +29,7 @@ def planet(planet_id): if planet.id == planet_id: return { "id": planet.id, - "title": planet.name, - "description": planet.description + "name": planet.name, + "description": planet.description, + "type": planet.type, } \ No newline at end of file From 188d08e048756ab891b43b9ae18ce5b27699a10f Mon Sep 17 00:00:00 2001 From: kaitlyngore Date: Fri, 22 Oct 2021 14:08:54 -0400 Subject: [PATCH 06/20] added Planet model and POST method --- app/__init__.py | 13 +++ app/models/__init__.py | 0 app/models/planet.py | 7 ++ app/planet.py | 6 -- app/routes.py | 25 +++-- migrations/README | 1 + migrations/alembic.ini | 45 +++++++++ migrations/env.py | 96 +++++++++++++++++++ migrations/script.py.mako | 24 +++++ .../cef964a71fc1_adds_planet_model.py | 34 +++++++ 10 files changed, 238 insertions(+), 13 deletions(-) create mode 100644 app/models/__init__.py create mode 100644 app/models/planet.py delete mode 100644 app/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/cef964a71fc1_adds_planet_model.py diff --git a/app/__init__.py b/app/__init__.py index 773d64837..4122feb70 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,8 +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 app.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..c0e0ce9b0 --- /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) + type = db.Column(db.String) \ No newline at end of file diff --git a/app/planet.py b/app/planet.py deleted file mode 100644 index 70302d187..000000000 --- a/app/planet.py +++ /dev/null @@ -1,6 +0,0 @@ -class Planet: - def __init__(self, id, name, description, type): - self.id = id - self.name = name - self.description = description - self.type = type diff --git a/app/routes.py b/app/routes.py index 0c5f25192..be0657ada 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,10 +1,7 @@ -from flask import Blueprint, jsonify -from .planet import Planet +from flask import Blueprint, jsonify, make_response, request +from app.models.planet import Planet +from app import db -planets = [ - Planet(1, "Mercury", "Mercury is the smallest planet in the Solar System and the closest to the Sun", "terrestrial"), - Planet(2, "Venus", "Venus is the second planet from the Sun.", "terrestrial") -] planet_bp = Blueprint("planet_bp", __name__, url_prefix="/planets") @@ -32,4 +29,18 @@ def planet(planet_id): "name": planet.name, "description": planet.description, "type": planet.type, - } \ No newline at end of file + } + +@planet_bp.route("", methods=["POST"]) +def create_planet(): + request_body = request.get_json() + new_planet = Planet(name=request_body["name"], + description=request_body["description"], + type = request_body["type"], + ) + + + db.session.add(new_planet) + db.session.commit() + + return make_response(f"Planet {new_planet.name} successfully created", 201) \ No newline at end of file diff --git a/migrations/README b/migrations/README new file mode 100644 index 000000000..98e4f9c44 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 000000000..f8ed4801f --- /dev/null +++ b/migrations/alembic.ini @@ -0,0 +1,45 @@ +# A generic, single database configuration. + +[alembic] +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 000000000..8b3fb3353 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,96 @@ +from __future__ import with_statement + +import logging +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool +from flask import current_app + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) +logger = logging.getLogger('alembic.env') + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +config.set_main_option( + 'sqlalchemy.url', + str(current_app.extensions['migrate'].db.engine.url).replace('%', '%%')) +target_metadata = current_app.extensions['migrate'].db.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, target_metadata=target_metadata, literal_binds=True + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + # this callback is used to prevent an auto-migration from being generated + # when there are no changes to the schema + # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html + def process_revision_directives(context, revision, directives): + if getattr(config.cmd_opts, 'autogenerate', False): + script = directives[0] + if script.upgrade_ops.is_empty(): + directives[:] = [] + logger.info('No changes in schema detected.') + + connectable = engine_from_config( + config.get_section(config.config_ini_section), + prefix='sqlalchemy.', + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=target_metadata, + process_revision_directives=process_revision_directives, + **current_app.extensions['migrate'].configure_args + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 000000000..2c0156303 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,24 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} diff --git a/migrations/versions/cef964a71fc1_adds_planet_model.py b/migrations/versions/cef964a71fc1_adds_planet_model.py new file mode 100644 index 000000000..593eeb0dc --- /dev/null +++ b/migrations/versions/cef964a71fc1_adds_planet_model.py @@ -0,0 +1,34 @@ +"""adds Planet model + +Revision ID: cef964a71fc1 +Revises: +Create Date: 2021-10-22 13:31:15.944043 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'cef964a71fc1' +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('title', sa.String(), nullable=True), + sa.Column('description', sa.String(), nullable=True), + sa.Column('type', 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 556870410384cdd758feb174ba8a3a8eef44f2d8 Mon Sep 17 00:00:00 2001 From: kaitlyngore Date: Fri, 22 Oct 2021 14:29:41 -0400 Subject: [PATCH 07/20] added GET all and GET methods --- app/routes.py | 74 ++++++++++++++++++++++++++++++--------------------- 1 file changed, 43 insertions(+), 31 deletions(-) diff --git a/app/routes.py b/app/routes.py index be0657ada..177c42833 100644 --- a/app/routes.py +++ b/app/routes.py @@ -5,42 +5,54 @@ planet_bp = Blueprint("planet_bp", __name__, url_prefix="/planets") -@planet_bp.route("", methods=["GET"]) +@planet_bp.route("", methods=["GET", "POST"]) def handle_planets(): - planets_response = [] - for planet in planets: - planets_response.append( - { - "id": planet.id, - "name": planet.name, - "description": planet.description, - "type": planet.type, - } - ) - return jsonify(planets_response) - -@planet_bp.route("/", methods=["GET"]) -def planet(planet_id): - planet_id = int(planet_id) - for planet in planets: - if planet.id == planet_id: - return { - "id": planet.id, - "name": planet.name, - "description": planet.description, - "type": planet.type, - } + if request.method == "GET": + planets = Planet.query.all() + planets_response = [] + for planet in planets: + planets_response.append( + { + "id": planet.id, + "name": planet.name, + "description": planet.description, + "type": planet.type, + } + ) + return jsonify(planets_response) -@planet_bp.route("", methods=["POST"]) -def create_planet(): - request_body = request.get_json() - new_planet = Planet(name=request_body["name"], + elif request.method == "POST": + request_body = request.get_json() + new_planet = Planet(name=request_body["name"], description=request_body["description"], type = request_body["type"], ) + db.session.add(new_planet) + db.session.commit() + + return make_response(f"Planet {new_planet.name} successfully created", 201) + +@planet_bp.route("/", methods=["GET"]) +def planet(planet_id): + planet = Planet.query.get(planet_id) + + return { + "id": planet.id, + "name": planet.name, + "description": planet.description, + "type": planet.type, + } + +# @planet_bp.route("", methods=["POST"]) +# def create_planet(): +# request_body = request.get_json() +# new_planet = Planet(name=request_body["name"], +# description=request_body["description"], +# type = request_body["type"], +# ) - 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) \ No newline at end of file +# return make_response(f"Planet {new_planet.name} successfully created", 201) \ No newline at end of file From fa4229bc9f1a18d6ba46df692d14e3c1137591d6 Mon Sep 17 00:00:00 2001 From: kaitlyngore Date: Fri, 22 Oct 2021 14:30:28 -0400 Subject: [PATCH 08/20] remove comments --- app/routes.py | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/app/routes.py b/app/routes.py index 177c42833..c279c4573 100644 --- a/app/routes.py +++ b/app/routes.py @@ -42,17 +42,3 @@ def planet(planet_id): "description": planet.description, "type": planet.type, } - -# @planet_bp.route("", methods=["POST"]) -# def create_planet(): -# request_body = request.get_json() -# new_planet = Planet(name=request_body["name"], -# description=request_body["description"], -# type = request_body["type"], -# ) - - -# db.session.add(new_planet) -# db.session.commit() - -# return make_response(f"Planet {new_planet.name} successfully created", 201) \ No newline at end of file From 91323f13dc0ac39bdb066a7431999770e4c12aca Mon Sep 17 00:00:00 2001 From: Nourhan Alenany Date: Sun, 24 Oct 2021 22:38:03 -0700 Subject: [PATCH 09/20] Add PUT and DELETE requests --- app/models/planet.py | 2 +- app/routes.py | 43 ++++++++++++++++++++++++++++++------------- 2 files changed, 31 insertions(+), 14 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index c0e0ce9b0..91f02e63f 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -2,6 +2,6 @@ class Planet(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) - name = db.Column(db.String) + title = db.Column(db.String) description = db.Column(db.String) type = db.Column(db.String) \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index c279c4573..06b76266b 100644 --- a/app/routes.py +++ b/app/routes.py @@ -5,6 +5,7 @@ planet_bp = Blueprint("planet_bp", __name__, url_prefix="/planets") + @planet_bp.route("", methods=["GET", "POST"]) def handle_planets(): if request.method == "GET": @@ -14,7 +15,7 @@ def handle_planets(): planets_response.append( { "id": planet.id, - "name": planet.name, + "title": planet.title, "description": planet.description, "type": planet.type, } @@ -23,22 +24,38 @@ def handle_planets(): elif request.method == "POST": request_body = request.get_json() - new_planet = Planet(name=request_body["name"], - description=request_body["description"], - type = request_body["type"], - ) + new_planet = Planet(title=request_body["title"], + description=request_body["description"], + type=request_body["type"], + ) 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.title} successfully created", 201) + -@planet_bp.route("/", methods=["GET"]) +@planet_bp.route("/", methods=["GET", "PUT", "DELETE"]) def planet(planet_id): planet = Planet.query.get(planet_id) - return { - "id": planet.id, - "name": planet.name, - "description": planet.description, - "type": planet.type, - } + if request.method == "GET": + return { + "id": planet.id, + "title": planet.title, + "description": planet.description, + "type": planet.type, + } + elif request.method == "PUT": + form_data = request.get_json() + + planet.title = form_data["title"] + planet.description = form_data["description"] + planet.type = form_data["type"] + + db.session.commit() + return make_response(f"Planet #{planet.id} successfully updated") + + elif request.method == "DELETE": + db.session.delete(planet) + db.session.commit() + return make_response(f"Planet #{planet.id} successfully deleted") From 3b25c3efdc5e23c5051cfb4821c654089ef8fce1 Mon Sep 17 00:00:00 2001 From: kaitlyngore Date: Mon, 25 Oct 2021 17:17:07 -0400 Subject: [PATCH 10/20] added PATCH method --- app/models/planet.py | 2 +- app/routes.py | 28 ++++++++++++++++++++++------ 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index 91f02e63f..c0e0ce9b0 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -2,6 +2,6 @@ class Planet(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) - title = db.Column(db.String) + name = db.Column(db.String) description = db.Column(db.String) type = db.Column(db.String) \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 06b76266b..0ab640a1e 100644 --- a/app/routes.py +++ b/app/routes.py @@ -15,7 +15,7 @@ def handle_planets(): planets_response.append( { "id": planet.id, - "title": planet.title, + "name": planet.name, "description": planet.description, "type": planet.type, } @@ -24,31 +24,31 @@ def handle_planets(): elif request.method == "POST": request_body = request.get_json() - new_planet = Planet(title=request_body["title"], + new_planet = Planet(name=request_body["name"], description=request_body["description"], type=request_body["type"], ) db.session.add(new_planet) db.session.commit() - return make_response(f"Planet {new_planet.title} successfully created", 201) + return make_response(f"Planet {new_planet.name} successfully created", 201) -@planet_bp.route("/", methods=["GET", "PUT", "DELETE"]) +@planet_bp.route("/", methods=["GET", "PUT", "DELETE", "PATCH"]) def planet(planet_id): planet = Planet.query.get(planet_id) if request.method == "GET": return { "id": planet.id, - "title": planet.title, + "name": planet.name, "description": planet.description, "type": planet.type, } elif request.method == "PUT": form_data = request.get_json() - planet.title = form_data["title"] + planet.name = form_data["name"] planet.description = form_data["description"] planet.type = form_data["type"] @@ -59,3 +59,19 @@ def planet(planet_id): db.session.delete(planet) db.session.commit() return make_response(f"Planet #{planet.id} successfully deleted") + + elif request.method == "PATCH": + request_body = request.get_json() + + if planet is not None: + if "name" in request_body: + planet.name = request_body["name"] + db.session.commit() + if "description" in request_body: + planet.description = request_body["description"] + db.session.commit() + + return jsonify(f"Planet # {planet.id} succesfully updated") + + else: + return jsonify("Error: Planet # {planet.id} not found", 404) From 729aa3bf9cfeb75fbd645a8cc8350dc0c3e3f80f Mon Sep 17 00:00:00 2001 From: kaitlyngore Date: Mon, 25 Oct 2021 17:45:11 -0400 Subject: [PATCH 11/20] added 404 error --- app/routes.py | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/app/routes.py b/app/routes.py index 0ab640a1e..6dd31bcc7 100644 --- a/app/routes.py +++ b/app/routes.py @@ -37,14 +37,17 @@ def handle_planets(): @planet_bp.route("/", methods=["GET", "PUT", "DELETE", "PATCH"]) def planet(planet_id): planet = Planet.query.get(planet_id) - + if planet is None: + return jsonify(f"Error: Planet {planet.id} not found", 404) + if request.method == "GET": return { "id": planet.id, "name": planet.name, "description": planet.description, "type": planet.type, - } + } + elif request.method == "PUT": form_data = request.get_json() @@ -53,25 +56,21 @@ def planet(planet_id): planet.type = form_data["type"] db.session.commit() - return make_response(f"Planet #{planet.id} successfully updated") + return jsonify(f"Planet #{planet.id} successfully updated") elif request.method == "DELETE": db.session.delete(planet) db.session.commit() - return make_response(f"Planet #{planet.id} successfully deleted") + return jsonify(f"Planet #{planet.id} successfully deleted") elif request.method == "PATCH": request_body = request.get_json() - if planet is not None: - if "name" in request_body: - planet.name = request_body["name"] - db.session.commit() - if "description" in request_body: - planet.description = request_body["description"] - db.session.commit() - - return jsonify(f"Planet # {planet.id} succesfully updated") + if "name" in request_body: + planet.name = request_body["name"] + db.session.commit() + if "description" in request_body: + planet.description = request_body["description"] + db.session.commit() - else: - return jsonify("Error: Planet # {planet.id} not found", 404) + return jsonify(f"Planet # {planet.id} succesfully updated") From 3dc1116d6214cbdf68043018def27d62ba46df5d Mon Sep 17 00:00:00 2001 From: kaitlyngore Date: Tue, 26 Oct 2021 13:20:47 -0400 Subject: [PATCH 12/20] change response to jsonify --- app/routes.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/routes.py b/app/routes.py index 6dd31bcc7..be9ae7a17 100644 --- a/app/routes.py +++ b/app/routes.py @@ -31,14 +31,14 @@ def handle_planets(): db.session.add(new_planet) db.session.commit() - return make_response(f"Planet {new_planet.name} successfully created", 201) + return jsonify(f"Planet {new_planet.name} successfully created"), 201 @planet_bp.route("/", methods=["GET", "PUT", "DELETE", "PATCH"]) def planet(planet_id): planet = Planet.query.get(planet_id) - if planet is None: - return jsonify(f"Error: Planet {planet.id} not found", 404) + if not planet: + return jsonify(f"Error: Planet {planet_id} not found"), 404 if request.method == "GET": return { From 82d0cd28b37a2682c6c544d832724195c108e2f6 Mon Sep 17 00:00:00 2001 From: kaitlyngore Date: Tue, 26 Oct 2021 20:42:50 -0400 Subject: [PATCH 13/20] add query filter for planet name --- app/routes.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index be9ae7a17..c5955e0c8 100644 --- a/app/routes.py +++ b/app/routes.py @@ -9,7 +9,15 @@ @planet_bp.route("", methods=["GET", "POST"]) def handle_planets(): if request.method == "GET": - planets = Planet.query.all() + name_from_url = request.args.get("name") + if name_from_url: + planets = Planet.query.filter_by(name=name_from_url) + # if planets is False: + # planets = Planet.query.filter(Planet.name.contains(name_from_url)) + + else: + planets = Planet.query.all() + planets_response = [] for planet in planets: planets_response.append( @@ -72,5 +80,8 @@ def planet(planet_id): if "description" in request_body: planet.description = request_body["description"] db.session.commit() + if "type" in request_body: + planet.type = request_body["type"] + db.session.commit() return jsonify(f"Planet # {planet.id} succesfully updated") From 3b1d71e0da0337947ec3b2f41637bf2fd0ffdc5e Mon Sep 17 00:00:00 2001 From: kaitlyngore Date: Tue, 26 Oct 2021 21:57:50 -0400 Subject: [PATCH 14/20] added test environment --- app/__init__.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 4122feb70..404639947 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,15 +1,25 @@ 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) From 798636320234654b6c5de124663f180880f38738 Mon Sep 17 00:00:00 2001 From: kaitlyngore Date: Wed, 27 Oct 2021 12:14:44 -0400 Subject: [PATCH 15/20] add test setup files --- tests/__init__.py | 0 tests/conftest.py | 20 ++++++++++++++++++++ tests/test_routes.py | 0 3 files changed, 20 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..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 c1517a0de6d994fa906545feb7ec7d778a5c923e Mon Sep 17 00:00:00 2001 From: kaitlyngore Date: Wed, 27 Oct 2021 14:12:49 -0400 Subject: [PATCH 16/20] added tests --- .gitignore | 1 + app/__init__.py | 4 ++-- app/routes.py | 8 ++++---- requirements.txt | 7 +++++++ tests/conftest.py | 18 +++++++++++++++++- tests/test_routes.py | 37 +++++++++++++++++++++++++++++++++++++ 6 files changed, 68 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index 4e9b18359..1f6919d4f 100644 --- a/.gitignore +++ b/.gitignore @@ -67,6 +67,7 @@ db.sqlite3-journal # Flask stuff: instance/ .webassets-cache +.flaskenv # Scrapy stuff: .scrapy diff --git a/app/__init__.py b/app/__init__.py index 404639947..18f67aed7 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -11,13 +11,13 @@ def create_app(test_config=None): app = Flask(__name__) + app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False + 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") diff --git a/app/routes.py b/app/routes.py index c5955e0c8..ed7294370 100644 --- a/app/routes.py +++ b/app/routes.py @@ -11,9 +11,9 @@ def handle_planets(): if request.method == "GET": name_from_url = request.args.get("name") if name_from_url: - planets = Planet.query.filter_by(name=name_from_url) - # if planets is False: - # planets = Planet.query.filter(Planet.name.contains(name_from_url)) + planets = Planet.query.filter_by(name=name_from_url).all() + if not planets: + planets = Planet.query.filter(Planet.name.contains(name_from_url)) else: planets = Planet.query.all() @@ -39,7 +39,7 @@ def handle_planets(): db.session.add(new_planet) db.session.commit() - return jsonify(f"Planet {new_planet.name} successfully created"), 201 + return jsonify(f"Planet with id:{new_planet.id} successfully created"), 201 @planet_bp.route("/", methods=["GET", "PUT", "DELETE", "PATCH"]) diff --git a/requirements.txt b/requirements.txt index fd90fffa8..6ee946d37 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.2 +pytest==6.2.5 python-dateutil==2.8.1 python-dotenv==0.15.0 python-editor==1.0.4 diff --git a/tests/conftest.py b/tests/conftest.py index 7c293ef65..6c00fe5f4 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,6 +1,7 @@ import pytest from app import create_app from app import db +from app.models.planet import Planet @pytest.fixture @@ -17,4 +18,19 @@ def app(): @pytest.fixture def client(app): - return app.test_client() \ No newline at end of file + return app.test_client() + +@pytest.fixture +def two_saved_planets(app): + # Arrange + planet_1 = Planet(name="Planet 1", + description="I'm planet 1", + type="gas giant") + planet_2 = Planet(name="Planet 2", + description="I'm planet 2", + type="gas giant") + + db.session.add(planet_1) + db.session.add(planet_2) + + db.session.commit() \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py index e69de29bb..0d4b33215 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -0,0 +1,37 @@ +from app.models.planet import Planet + +def test_get_all_planets_when_none_exist(client): + response = client.get("/planets") + + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == [] + +def test_get_planet_1_when_none_exist(client): + response = client.get("/planets/1") + + response_body = response.get_json() + + assert response.status_code == 404 + assert response_body == "Error: Planet 1 not found" + +def test_get_all_planets_when_some_exist(client, two_saved_planets): + planet1 = dict(id=1, name="Planet 1", description="I'm planet 1", type="gas giant") + planet2 = dict(id=2, name="Planet 2", description="I'm planet 2", type="gas giant") + + response = client.get("/planets") + + response_body = response.get_json() + + assert response.status_code == 200 + assert len(response_body) == 2 + assert planet1 in response_body + assert planet2 in response_body + +def test_create_a_planet_when_none_exist(client): + response = client.post("/planets", json=({"name":"Planet 1", "description":"I'm planet 1", "type":"gas giant"})) + response_body = response.get_json() + + assert response.status_code == 201 + assert response_body == "Planet with id:1 successfully created" \ No newline at end of file From 7acb4538cfc27dbc3b7ca110a902b21881abe720 Mon Sep 17 00:00:00 2001 From: kaitlyngore Date: Wed, 27 Oct 2021 15:03:33 -0400 Subject: [PATCH 17/20] added Planet method to create dictionary --- app/models/planet.py | 10 +++++++++- app/routes.py | 27 +++++++++++---------------- tests/test_routes.py | 9 +++++++++ 3 files changed, 29 insertions(+), 17 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index c0e0ce9b0..43391ca0d 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -4,4 +4,12 @@ class Planet(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String) description = db.Column(db.String) - type = db.Column(db.String) \ No newline at end of file + type = db.Column(db.String) + + def create_dict(self): + return { + "id": self.id, + "name": self.name, + "description": self.description, + "type": self.type, + } \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index ed7294370..0b0b85b81 100644 --- a/app/routes.py +++ b/app/routes.py @@ -14,20 +14,19 @@ def handle_planets(): planets = Planet.query.filter_by(name=name_from_url).all() if not planets: planets = Planet.query.filter(Planet.name.contains(name_from_url)) - + else: planets = Planet.query.all() planets_response = [] for planet in planets: - planets_response.append( - { - "id": planet.id, - "name": planet.name, - "description": planet.description, - "type": planet.type, - } - ) + planets_response.append(planet.create_dict()) + + if not planets_response: + planets = Planet.query.all() + for planet in planets: + planets_response.append(planet.create_dict()) + return jsonify(planets_response) elif request.method == "POST": @@ -39,9 +38,9 @@ def handle_planets(): db.session.add(new_planet) db.session.commit() + # return make_response(new_planet.create_dict(), 201) return jsonify(f"Planet with id:{new_planet.id} successfully created"), 201 - @planet_bp.route("/", methods=["GET", "PUT", "DELETE", "PATCH"]) def planet(planet_id): planet = Planet.query.get(planet_id) @@ -49,12 +48,8 @@ def planet(planet_id): return jsonify(f"Error: Planet {planet_id} not found"), 404 if request.method == "GET": - return { - "id": planet.id, - "name": planet.name, - "description": planet.description, - "type": planet.type, - } + return (planet.create_dict()) + elif request.method == "PUT": form_data = request.get_json() diff --git a/tests/test_routes.py b/tests/test_routes.py index 0d4b33215..ea33b6f51 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -30,6 +30,15 @@ def test_get_all_planets_when_some_exist(client, two_saved_planets): assert planet2 in response_body def test_create_a_planet_when_none_exist(client): + # tried to use the self.create_dict method to return a full dictionary + # but could not get the tests to work + # data = {"name":"Planet 1", "description":"I'm planet 1", "type":"gas giant"} + # response = client.post("/planets", json=(data)) + # response_body = response.get_json() + + # assert response.status_code == 201 + # assert "Planet 1" in response_body + response = client.post("/planets", json=({"name":"Planet 1", "description":"I'm planet 1", "type":"gas giant"})) response_body = response.get_json() From 2848b8d0631271b93e5d0a6f2a1e64a23936053f Mon Sep 17 00:00:00 2001 From: kaitlyngore Date: Tue, 2 Nov 2021 13:55:23 -0400 Subject: [PATCH 18/20] add deployment file --- 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 4ac51189cd9ba505181ba160cb86517f41ce1493 Mon Sep 17 00:00:00 2001 From: kaitlyngore Date: Tue, 2 Nov 2021 13:56:55 -0400 Subject: [PATCH 19/20] update requirements --- requirements.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/requirements.txt b/requirements.txt index 6ee946d37..09438102a 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 64b629377f04a29b637f76eecda2f626fdf69f5b Mon Sep 17 00:00:00 2001 From: kaitlyngore Date: Tue, 2 Nov 2021 14:23:21 -0400 Subject: [PATCH 20/20] updated migrations --- ..._planet_model.py => c0591105be81_adds_planet_model.py} | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) rename migrations/versions/{cef964a71fc1_adds_planet_model.py => c0591105be81_adds_planet_model.py} (82%) diff --git a/migrations/versions/cef964a71fc1_adds_planet_model.py b/migrations/versions/c0591105be81_adds_planet_model.py similarity index 82% rename from migrations/versions/cef964a71fc1_adds_planet_model.py rename to migrations/versions/c0591105be81_adds_planet_model.py index 593eeb0dc..adf1801e1 100644 --- a/migrations/versions/cef964a71fc1_adds_planet_model.py +++ b/migrations/versions/c0591105be81_adds_planet_model.py @@ -1,8 +1,8 @@ """adds Planet model -Revision ID: cef964a71fc1 +Revision ID: c0591105be81 Revises: -Create Date: 2021-10-22 13:31:15.944043 +Create Date: 2021-11-02 14:22:57.158289 """ from alembic import op @@ -10,7 +10,7 @@ # revision identifiers, used by Alembic. -revision = 'cef964a71fc1' +revision = 'c0591105be81' down_revision = None branch_labels = None depends_on = None @@ -20,7 +20,7 @@ def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('planet', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), - sa.Column('title', sa.String(), nullable=True), + sa.Column('name', sa.String(), nullable=True), sa.Column('description', sa.String(), nullable=True), sa.Column('type', sa.String(), nullable=True), sa.PrimaryKeyConstraint('id')