From f02b6d012597faafa1ce8882312cf1b4e4556aa4 Mon Sep 17 00:00:00 2001 From: Khandice Date: Mon, 18 Oct 2021 13:40:56 -0700 Subject: [PATCH 01/14] Created Planet class and registered blueprint with app --- app/__init__.py | 4 ++++ app/routes.py | 16 +++++++++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..61ba6d482 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,7 +1,11 @@ from flask import Flask + 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 8e9dfe684..609cb2377 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,16 @@ -from flask import Blueprint +from flask import Blueprint, jsonify + +class Planet: + def __init__(self, id, name, description, matter): + self.id = id + self.name = name + self.description = description + self.matter = matter + + +planets = [Planet(1, "Mercury", "small and red", "solid"), Planet(5, "Jupiter", "big and swirly", "gaseous"), +Planet(6, "Saturn", "rings and swirls", "gaseous")] + + +planets_bp = Blueprint("planets", __name__, url_prefix="/planets") From 1c46357c0dd5f14ae7e900b8a45c440a9144cd21 Mon Sep 17 00:00:00 2001 From: Rae Date: Mon, 18 Oct 2021 14:09:32 -0700 Subject: [PATCH 02/14] created get_all_planets and get_one_planet function --- app/routes.py | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index 609cb2377..180bc25cc 100644 --- a/app/routes.py +++ b/app/routes.py @@ -8,9 +8,33 @@ def __init__(self, id, name, description, matter): self.matter = matter -planets = [Planet(1, "Mercury", "small and red", "solid"), Planet(5, "Jupiter", "big and swirly", "gaseous"), +planets = [Planet(1, "Mercury", "small and red", "solid"), +Planet(5, "Jupiter", "big and swirly", "gaseous"), Planet(6, "Saturn", "rings and swirls", "gaseous")] planets_bp = Blueprint("planets", __name__, url_prefix="/planets") +@planets_bp.route("",methods=["GET"]) +def get_all_planets(): + planet_list=[] + for planet in planets: + planet_list.append({"id" : planet.id, + "name":planet.name, + "description":planet.description, + "matter":planet.matter}) + return jsonify(planet_list) + +@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 {"id" : planet.id, + "name":planet.name, + "description":planet.description, + "matter":planet.matter} + +# return_value=vars(Planet) +# return jsonify(return_value) +# make __dict__ in planet class to work with vars \ No newline at end of file From 5bd2806323e0a172b84a33204a725cc9270fc27f Mon Sep 17 00:00:00 2001 From: Rae Date: Mon, 18 Oct 2021 14:33:48 -0700 Subject: [PATCH 03/14] refactored to vars with exception handling --- app/routes.py | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/app/routes.py b/app/routes.py index 180bc25cc..9dd8356f0 100644 --- a/app/routes.py +++ b/app/routes.py @@ -19,22 +19,15 @@ def __init__(self, id, name, description, matter): def get_all_planets(): planet_list=[] for planet in planets: - planet_list.append({"id" : planet.id, - "name":planet.name, - "description":planet.description, - "matter":planet.matter}) + planet_list.append(vars(planet)) return jsonify(planet_list) @planets_bp.route("/",methods=["GET"]) def get_one_planet(planet_id): + if not planet_id.isdigit(): + return("Not a number!") planet_id=int(planet_id) for planet in planets: if planet.id == planet_id: - return {"id" : planet.id, - "name":planet.name, - "description":planet.description, - "matter":planet.matter} - -# return_value=vars(Planet) -# return jsonify(return_value) -# make __dict__ in planet class to work with vars \ No newline at end of file + return jsonify(vars(planet)) + return ("Not Found!") \ No newline at end of file From 896363ba0991d0b25a68b7ec6d2d84fdd2d42345 Mon Sep 17 00:00:00 2001 From: Khandice Date: Mon, 18 Oct 2021 20:01:26 -0700 Subject: [PATCH 04/14] Cleaned up some spacing --- app/routes.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/app/routes.py b/app/routes.py index 9dd8356f0..1143db3b6 100644 --- a/app/routes.py +++ b/app/routes.py @@ -15,18 +15,18 @@ def __init__(self, id, name, description, matter): planets_bp = Blueprint("planets", __name__, url_prefix="/planets") -@planets_bp.route("",methods=["GET"]) +@planets_bp.route("", methods=["GET"]) def get_all_planets(): - planet_list=[] + planet_list = [] for planet in planets: planet_list.append(vars(planet)) return jsonify(planet_list) -@planets_bp.route("/",methods=["GET"]) +@planets_bp.route("/", methods=["GET"]) def get_one_planet(planet_id): if not planet_id.isdigit(): return("Not a number!") - planet_id=int(planet_id) + planet_id = int(planet_id) for planet in planets: if planet.id == planet_id: return jsonify(vars(planet)) From 919cb19a80e623272ac457e842efa9cebbdff5f5 Mon Sep 17 00:00:00 2001 From: Rae Date: Mon, 25 Oct 2021 13:43:26 -0700 Subject: [PATCH 05/14] refactors vars methods and creates new models folder --- app/models/__init__.py | 0 app/models/planet.py | 0 app/routes.py | 15 +++++++++++---- 3 files changed, 11 insertions(+), 4 deletions(-) create mode 100644 app/models/__init__.py create mode 100644 app/models/planet.py 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/routes.py b/app/routes.py index 9dd8356f0..22239cead 100644 --- a/app/routes.py +++ b/app/routes.py @@ -6,6 +6,12 @@ def __init__(self, id, name, description, matter): self.name = name self.description = description self.matter = matter + + def make_dict(self): + return {"id": self.id, + "name": self.name, + "description": self.description, + "matter": self.matter} planets = [Planet(1, "Mercury", "small and red", "solid"), @@ -19,15 +25,16 @@ def __init__(self, id, name, description, matter): def get_all_planets(): planet_list=[] for planet in planets: - planet_list.append(vars(planet)) + planet_list.append(planet.make_dict()) return jsonify(planet_list) @planets_bp.route("/",methods=["GET"]) def get_one_planet(planet_id): - if not planet_id.isdigit(): + try: + planet_id=int(planet_id) + except: return("Not a number!") - planet_id=int(planet_id) for planet in planets: if planet.id == planet_id: - return jsonify(vars(planet)) + return jsonify(planet.make_dict()) return ("Not Found!") \ No newline at end of file From 52b5374b0559b08b647f67c94eaef1dda43ae96f Mon Sep 17 00:00:00 2001 From: Rae Date: Mon, 25 Oct 2021 13:56:42 -0700 Subject: [PATCH 06/14] adds database config in models --- app/__init__.py | 15 +++++++++++- app/models/planet.py | 14 +++++++++++ app/routes.py | 57 +++++++++++++++++--------------------------- 3 files changed, 50 insertions(+), 36 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 61ba6d482..90a405c38 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,11 +1,24 @@ from flask import Flask +from flask_sqlalchemy import SQLAlchemy +from flask_migrate import Migrate - +db = SQLAlchemy +migrate = Migrate() +DATABASE = 'postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system_development' def create_app(test_config=None): app = Flask(__name__) + app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False + app.config['SQLALCHEMY_DATABSE_URI'] = DATABASE + + 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/planet.py b/app/models/planet.py index e69de29bb..559b341e9 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -0,0 +1,14 @@ +from app import routes + +class Planet: + def __init__(self, id, name, description, matter): + self.id = id + self.name = name + self.description = description + self.matter = matter + + def make_dict(self): + return {"id": self.id, + "name": self.name, + "description": self.description, + "matter": self.matter} \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index cc88f8441..f4acc0369 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,41 +1,28 @@ -from flask import Blueprint, jsonify +from flask import Blueprint, jsonify, make_response, request +from app.models.planet import Planet -class Planet: - def __init__(self, id, name, description, matter): - self.id = id - self.name = name - self.description = description - self.matter = matter - - def make_dict(self): - return {"id": self.id, - "name": self.name, - "description": self.description, - "matter": self.matter} - - -planets = [Planet(1, "Mercury", "small and red", "solid"), -Planet(5, "Jupiter", "big and swirly", "gaseous"), -Planet(6, "Saturn", "rings and swirls", "gaseous")] +# planets = [Planet(1, "Mercury", "small and red", "solid"), +# Planet(5, "Jupiter", "big and swirly", "gaseous"), +# Planet(6, "Saturn", "rings and swirls", "gaseous")] planets_bp = Blueprint("planets", __name__, url_prefix="/planets") -@planets_bp.route("", methods=["GET"]) -def get_all_planets(): - planet_list = [] - for planet in planets: - planet_list.append(planet.make_dict()) - return jsonify(planet_list) +# @planets_bp.route("", methods=["GET"]) +# def get_all_planets(): +# planet_list = [] +# for planet in planets: +# planet_list.append(planet.make_dict()) +# return jsonify(planet_list) -@planets_bp.route("/", methods=["GET"]) -def get_one_planet(planet_id): - try: - planet_id=int(planet_id) - except: - return("Not a number!") - planet_id = int(planet_id) - for planet in planets: - if planet.id == planet_id: - return jsonify(planet.make_dict()) - return ("Not Found!") \ No newline at end of file +# @planets_bp.route("/", methods=["GET"]) +# def get_one_planet(planet_id): +# try: +# planet_id=int(planet_id) +# except: +# return("Not a number!") +# planet_id = int(planet_id) +# for planet in planets: +# if planet.id == planet_id: +# return jsonify(planet.make_dict()) +# return ("Not Found!") \ No newline at end of file From c30e7fa0093922f955b54e1bc7347e1381b0bc0c Mon Sep 17 00:00:00 2001 From: Rae Date: Mon, 25 Oct 2021 14:00:41 -0700 Subject: [PATCH 07/14] refactors class planet into database class --- app/models/planet.py | 13 ++++++------- app/routes.py | 1 + 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index 559b341e9..893c8f638 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -1,11 +1,10 @@ -from app import routes +from app import routes, db -class Planet: - def __init__(self, id, name, description, matter): - self.id = id - self.name = name - self.description = description - self.matter = matter +class Planet(db.Model): + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + name = db.Column(db.String) + description = db.Column(db.String) + matter = db.Column(db.String) def make_dict(self): return {"id": self.id, diff --git a/app/routes.py b/app/routes.py index f4acc0369..cc7d8752a 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,5 +1,6 @@ from flask import Blueprint, jsonify, make_response, request from app.models.planet import Planet +from app import db # planets = [Planet(1, "Mercury", "small and red", "solid"), # Planet(5, "Jupiter", "big and swirly", "gaseous"), From 4300cb64d988eca66596e4219afa77ccabe40ae0 Mon Sep 17 00:00:00 2001 From: Rae Date: Mon, 25 Oct 2021 14:14:44 -0700 Subject: [PATCH 08/14] creates migrations folder --- app/__init__.py | 4 +- app/models/planet.py | 2 +- app/routes.py | 2 +- migrations/README | 1 + migrations/alembic.ini | 45 +++++++++++++ migrations/env.py | 96 ++++++++++++++++++++++++++++ migrations/script.py.mako | 24 +++++++ migrations/versions/7681246a2f35_.py | 34 ++++++++++ 8 files changed, 204 insertions(+), 4 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/7681246a2f35_.py diff --git a/app/__init__.py b/app/__init__.py index 90a405c38..5b8df9c99 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -2,7 +2,7 @@ from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate -db = SQLAlchemy +db = SQLAlchemy() migrate = Migrate() DATABASE = 'postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system_development' @@ -10,7 +10,7 @@ def create_app(test_config=None): app = Flask(__name__) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False - app.config['SQLALCHEMY_DATABSE_URI'] = DATABASE + app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE db.init_app(app) migrate.init_app(app,db) diff --git a/app/models/planet.py b/app/models/planet.py index 893c8f638..bce4f05b2 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -1,4 +1,4 @@ -from app import routes, db +from app import db class Planet(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) diff --git a/app/routes.py b/app/routes.py index cc7d8752a..d1b8077e5 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,6 +1,6 @@ +from app import db from flask import Blueprint, jsonify, make_response, request from app.models.planet import Planet -from app import db # planets = [Planet(1, "Mercury", "small and red", "solid"), # Planet(5, "Jupiter", "big and swirly", "gaseous"), 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/7681246a2f35_.py b/migrations/versions/7681246a2f35_.py new file mode 100644 index 000000000..ff08a3705 --- /dev/null +++ b/migrations/versions/7681246a2f35_.py @@ -0,0 +1,34 @@ +"""empty message + +Revision ID: 7681246a2f35 +Revises: +Create Date: 2021-10-25 14:11:40.322891 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '7681246a2f35' +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('matter', 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 caba01d4f1a2de1414a8543787d7429b49f95d6c Mon Sep 17 00:00:00 2001 From: Khandice Date: Tue, 26 Oct 2021 11:23:53 -0700 Subject: [PATCH 09/14] Creates read and post method routes --- app/models/planet.py | 10 ++++++---- app/routes.py | 35 ++++++++++++++++++++++++++++------- 2 files changed, 34 insertions(+), 11 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index bce4f05b2..c599d0313 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -7,7 +7,9 @@ class Planet(db.Model): matter = db.Column(db.String) def make_dict(self): - return {"id": self.id, - "name": self.name, - "description": self.description, - "matter": self.matter} \ No newline at end of file + return { + "id": self.id, + "name": self.name, + "description": self.description, + "matter": self.matter + } \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index d1b8077e5..b74eb8fcc 100644 --- a/app/routes.py +++ b/app/routes.py @@ -9,12 +9,33 @@ planets_bp = Blueprint("planets", __name__, url_prefix="/planets") -# @planets_bp.route("", methods=["GET"]) -# def get_all_planets(): -# planet_list = [] -# for planet in planets: -# planet_list.append(planet.make_dict()) -# return jsonify(planet_list) +@planets_bp.route("", methods=["GET"]) +def read_all_planets(): + planets = Planet.query.all() + planet_list = [] + for planet in planets: + planet_list.append(planet.make_dict()) + return jsonify(planet_list) + + +@planets_bp.route("", methods=["POST"]) +def post_new_planet(): + request_body = request.get_json() + new_planet = Planet(name=request_body["name"], + description=request_body["description"], + matter=request_body["matter"]) + + db.session.add(new_planet) + db.session.commit() + + return make_response(f"Planet {new_planet.name} successfully created!", 201) + + +@planets_bp.route("/", methods=["GET"]) +def read_planet(planet_id): + planet = Planet.query.get(planet_id) + + return planet.make_dict() # @planets_bp.route("/", methods=["GET"]) # def get_one_planet(planet_id): @@ -26,4 +47,4 @@ # for planet in planets: # if planet.id == planet_id: # return jsonify(planet.make_dict()) -# return ("Not Found!") \ No newline at end of file +# return ("Not Found!") From b22b2fb391e58c5f0a7fca6699e52aa9d6f11508 Mon Sep 17 00:00:00 2001 From: Khandice Date: Tue, 26 Oct 2021 11:37:56 -0700 Subject: [PATCH 10/14] Creates put and delete methods routes for planet model --- app/routes.py | 37 ++++++++++++++++++++++++++----------- 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/app/routes.py b/app/routes.py index b74eb8fcc..655872855 100644 --- a/app/routes.py +++ b/app/routes.py @@ -37,14 +37,29 @@ def read_planet(planet_id): return planet.make_dict() -# @planets_bp.route("/", methods=["GET"]) -# def get_one_planet(planet_id): -# try: -# planet_id=int(planet_id) -# except: -# return("Not a number!") -# planet_id = int(planet_id) -# for planet in planets: -# if planet.id == planet_id: -# return jsonify(planet.make_dict()) -# return ("Not Found!") + +@planets_bp.route("/", methods=["PUT"]) +def update_planet(planet_id): + planet = Planet.query.get(planet_id) + form_data = request.get_json() + + planet.name = form_data["name"] + planet.description = form_data["description"] + planet.matter = form_data["matter"] + + db.session.commit() + + return make_response(f"Planet {planet.name} successfully updated!", 200) + + +@planets_bp.route("/", methods=["DELETE"]) +def delete_planet(planet_id): + planet = Planet.query.get(planet_id) + + db.session.delete(planet) + db.session.commit() + + return make_response(f"Planet {planet.name} successfully deleted!", 200) + + + From a3fea77452449c1cdc9f4dae4f1f4e9e7958dccc Mon Sep 17 00:00:00 2001 From: Rae Date: Tue, 26 Oct 2021 11:51:50 -0700 Subject: [PATCH 11/14] cleans up code --- app/routes.py | 5 ----- 1 file changed, 5 deletions(-) diff --git a/app/routes.py b/app/routes.py index 655872855..ff86ca3df 100644 --- a/app/routes.py +++ b/app/routes.py @@ -2,11 +2,6 @@ from flask import Blueprint, jsonify, make_response, request from app.models.planet import Planet -# planets = [Planet(1, "Mercury", "small and red", "solid"), -# Planet(5, "Jupiter", "big and swirly", "gaseous"), -# Planet(6, "Saturn", "rings and swirls", "gaseous")] - - planets_bp = Blueprint("planets", __name__, url_prefix="/planets") @planets_bp.route("", methods=["GET"]) From 24466c2768976990a56755f4ef2d8716ee7e8aa9 Mon Sep 17 00:00:00 2001 From: Rae Date: Wed, 27 Oct 2021 11:41:23 -0700 Subject: [PATCH 12/14] adds input validation, creates patch method --- app/routes.py | 41 +++++++++++++++++++++++++++++++++-------- 1 file changed, 33 insertions(+), 8 deletions(-) diff --git a/app/routes.py b/app/routes.py index ff86ca3df..78c1465a7 100644 --- a/app/routes.py +++ b/app/routes.py @@ -4,6 +4,18 @@ planets_bp = Blueprint("planets", __name__, url_prefix="/planets") +def make_input_valid(number): + try: + int(number) + except: + return make_response(f"{number} is not an int!", 400) + +def is_parameter_valid(parameter_id): + if make_input_valid(parameter_id) is not None: + return make_input_valid(parameter_id) + elif Planet.query.get(parameter_id) is None: + return make_response(f"{parameter_id} is not a valid id!", 404) + @planets_bp.route("", methods=["GET"]) def read_all_planets(): planets = Planet.query.all() @@ -18,8 +30,7 @@ def post_new_planet(): request_body = request.get_json() new_planet = Planet(name=request_body["name"], description=request_body["description"], - matter=request_body["matter"]) - + matter=request_body["matter"]) db.session.add(new_planet) db.session.commit() @@ -28,32 +39,46 @@ def post_new_planet(): @planets_bp.route("/", methods=["GET"]) def read_planet(planet_id): + if is_parameter_valid(planet_id) is not None: + return is_parameter_valid(planet_id) planet = Planet.query.get(planet_id) - return planet.make_dict() @planets_bp.route("/", methods=["PUT"]) def update_planet(planet_id): + if is_parameter_valid(planet_id) is not None: + return is_parameter_valid(planet_id) planet = Planet.query.get(planet_id) form_data = request.get_json() - planet.name = form_data["name"] planet.description = form_data["description"] planet.matter = form_data["matter"] - db.session.commit() - return make_response(f"Planet {planet.name} successfully updated!", 200) +@planets_bp.route("/", methods=["PATCH"]) +def update_planet_parameter(planet_id): + if is_parameter_valid(planet_id) is not None: + return is_parameter_valid(planet_id) + planet = Planet.query.get(planet_id) + form_data = request.get_json() + if "name" in form_data: + planet.name = form_data["name"] + if "description" in form_data: + planet.description = form_data["description"] + if "matter" in form_data: + planet.matter = form_data["matter"] + db.session.commit() + return make_response(f"Planet {planet.name} successfully updated!", 200) @planets_bp.route("/", methods=["DELETE"]) def delete_planet(planet_id): + if is_parameter_valid(planet_id) is not None: + return is_parameter_valid(planet_id) planet = Planet.query.get(planet_id) - db.session.delete(planet) db.session.commit() - return make_response(f"Planet {planet.name} successfully deleted!", 200) From aa9e5bbfd87d29e8756b031860cadf1a9228d573 Mon Sep 17 00:00:00 2001 From: Khandice Date: Wed, 3 Nov 2021 11:29:39 -0700 Subject: [PATCH 13/14] Updates path of uri to .env file --- app/__init__.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 5b8df9c99..640448f8e 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,16 +1,25 @@ from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate +import os +from dotenv import load_dotenv db = SQLAlchemy() migrate = Migrate() -DATABASE = 'postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system_development' + +load_dotenv() def create_app(test_config=None): app = Flask(__name__) - - app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False - app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE + app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False + + if test_config is None: + app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( + "SQLALCHEMY_DATABASE_URI") + else: + app.config["TESTING"] = True + app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( + "SQLALCHEMY_TEST_DATABASE_URI") db.init_app(app) migrate.init_app(app,db) From e4223d77208ea80f30d8ea9d8164a4c2817e7021 Mon Sep 17 00:00:00 2001 From: Khandice Date: Wed, 3 Nov 2021 11:34:20 -0700 Subject: [PATCH 14/14] Creates 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