From 027ca21e7bf6fcd1bfbe279b1c3be5e50a056aa1 Mon Sep 17 00:00:00 2001 From: Esther Annorzie Date: Fri, 22 Apr 2022 14:04:45 -0400 Subject: [PATCH 01/10] finished wave 1 --- app/__init__.py | 3 +++ app/routes.py | 32 +++++++++++++++++++++++++++++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..243a5a1df 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 8e9dfe684..e0b61c3e6 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,32 @@ -from flask import Blueprint +from flask import Blueprint, jsonify +class Planets: + def __init__(self, id, name, description): + self.id = id + self.name = name + self.description = description + + +# create our instances +planets = [ + Planets(1, "Mercury", "Small hot planet"), + Planets(2, "Venus", "A gaseous planet"), + Planets(3, "Earth", "Has lots of life") +] + +# create the blueprint +planets_bp = Blueprint("planets", __name__, url_prefix="/planets") + +# do the decorator +@planets_bp.route("", methods=["GET"]) +def get_all_planets(): + all_planets = [] + for planet in planets: + all_planets.append( + { + "id": planet.id, + "name": planet.name, + "description": planet.description + } + ) + return jsonify(all_planets) \ No newline at end of file From 5b1e32edd32953d95834c8afbfaae71ef2ea6772 Mon Sep 17 00:00:00 2001 From: Esther Annorzie Date: Fri, 22 Apr 2022 14:08:03 -0400 Subject: [PATCH 02/10] refactored get_all_planets --- app/routes.py | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/app/routes.py b/app/routes.py index e0b61c3e6..6a32ba5b3 100644 --- a/app/routes.py +++ b/app/routes.py @@ -20,13 +20,12 @@ def __init__(self, id, name, description): # do the decorator @planets_bp.route("", methods=["GET"]) def get_all_planets(): - all_planets = [] - for planet in planets: - all_planets.append( - { - "id": planet.id, - "name": planet.name, - "description": planet.description - } - ) + all_planets = [{ + "id": planet.id, + "name": planet.name, + "description": planet.description + } + for planet in planets] + + return jsonify(all_planets) \ No newline at end of file From 1de456e894ed238cf93405b0355835a308a14d0f Mon Sep 17 00:00:00 2001 From: Esther Annorzie Date: Fri, 22 Apr 2022 19:59:49 -0400 Subject: [PATCH 03/10] cleaned up get_all_planets again --- app/routes.py | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/app/routes.py b/app/routes.py index 6a32ba5b3..b0c9abc45 100644 --- a/app/routes.py +++ b/app/routes.py @@ -20,12 +20,9 @@ def __init__(self, id, name, description): # do the decorator @planets_bp.route("", methods=["GET"]) def get_all_planets(): - all_planets = [{ - "id": planet.id, - "name": planet.name, - "description": planet.description - } - for planet in planets] - - - return jsonify(all_planets) \ No newline at end of file + return jsonify([ + {"id": planet.id, + "name": planet.name, + "description": planet.description} + for planet in planets + ]) \ No newline at end of file From 478f69b8fc4edba4cf1855034a522034655969b3 Mon Sep 17 00:00:00 2001 From: Danielle Date: Mon, 25 Apr 2022 13:55:47 -0500 Subject: [PATCH 04/10] created new endpoint to return one planet by planet id --- app/routes.py | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/app/routes.py b/app/routes.py index b0c9abc45..d278494d3 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,4 +1,4 @@ -from flask import Blueprint, jsonify +from flask import Blueprint, jsonify, abort, make_response class Planets: def __init__(self, id, name, description): @@ -21,8 +21,29 @@ def __init__(self, id, name, description): @planets_bp.route("", methods=["GET"]) def get_all_planets(): return jsonify([ - {"id": planet.id, - "name": planet.name, - "description": planet.description} + to_dict(planet) for planet in planets - ]) \ No newline at end of file + ]) + +@planets_bp.route("/", methods = ["GET"]) +def get_one_planet(planet_id): + + planet = validate_planet(planet_id) + + return jsonify(to_dict(planet)) + +def validate_planet(planet_id): + try: + planet_id = int(planet_id) + except ValueError: + abort(make_response({"message": f"invalid id {planet_id}"}, 400)) + + for planet in planets: + if planet.id == planet_id: + return planet + abort(make_response({"message": f"planet id {planet_id} not found"}, 404)) + +def to_dict(planet): + return {"id": planet.id, + "name": planet.name, + "description": planet.description} \ No newline at end of file From 28c5ea7c19b36f08d9b21451b1b05e51f54292bc Mon Sep 17 00:00:00 2001 From: Esther Annorzie Date: Fri, 29 Apr 2022 14:25:44 -0400 Subject: [PATCH 05/10] started creating database and planet model --- app/__init__.py | 12 +++ app/models/__init__.py | 0 app/models/planet.py | 7 ++ app/routes.py | 76 +++++++-------- migrations/README | 1 + migrations/alembic.ini | 45 +++++++++ migrations/env.py | 96 +++++++++++++++++++ migrations/script.py.mako | 24 +++++ .../97aca7ff74c7_adds_planet_model.py | 34 +++++++ 9 files changed, 256 insertions(+), 39 deletions(-) create mode 100644 app/models/__init__.py create mode 100644 app/models/planet.py create mode 100644 migrations/README create mode 100644 migrations/alembic.ini create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/97aca7ff74c7_adds_planet_model.py diff --git a/app/__init__.py b/app/__init__.py index 243a5a1df..b21dac6a2 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,9 +1,21 @@ from flask import Flask +from flask_sqlalchemy import SQLAlchemy +from flask_migrate import Migrate +db = SQLAlchemy() +migrate = Migrate() def create_app(test_config=None): app = Flask(__name__) + app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False + app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system_development' + + db.init_app(app) + migrate.init_app(app, db) + + from app.models.planet import Planet + from .routes import planets_bp app.register_blueprint(planets_bp) diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/app/models/planet.py b/app/models/planet.py new file mode 100644 index 000000000..4b822cd0d --- /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) + moons = db.Column(db.Integer) \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index d278494d3..bbfa384cf 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,49 +1,47 @@ from flask import Blueprint, jsonify, abort, make_response +from app.models.planet import Planet +from app import db -class Planets: - def __init__(self, id, name, description): - self.id = id - self.name = name - self.description = description +# class Planets: +# def __init__(self, id, name, description): +# self.id = id +# self.name = name +# self.description = description # create our instances -planets = [ - Planets(1, "Mercury", "Small hot planet"), - Planets(2, "Venus", "A gaseous planet"), - Planets(3, "Earth", "Has lots of life") -] +# planets = [ +# Planets(1, "Mercury", "Small hot planet"), +# Planets(2, "Venus", "A gaseous planet"), +# Planets(3, "Earth", "Has lots of life") +# ] # create the blueprint planets_bp = Blueprint("planets", __name__, url_prefix="/planets") + # do the decorator -@planets_bp.route("", methods=["GET"]) -def get_all_planets(): - return jsonify([ - to_dict(planet) - for planet in planets - ]) - -@planets_bp.route("/", methods = ["GET"]) -def get_one_planet(planet_id): - - planet = validate_planet(planet_id) - - return jsonify(to_dict(planet)) - -def validate_planet(planet_id): - try: - planet_id = int(planet_id) - except ValueError: - abort(make_response({"message": f"invalid id {planet_id}"}, 400)) - - for planet in planets: - if planet.id == planet_id: - return planet - abort(make_response({"message": f"planet id {planet_id} not found"}, 404)) - -def to_dict(planet): - return {"id": planet.id, - "name": planet.name, - "description": planet.description} \ No newline at end of file +# @planets_bp.route("", methods=["GET"]) +# def get_all_planets(): +# return jsonify([ +# to_dict(planet) +# for planet in planets +# ]) + +# @planets_bp.route("/", methods = ["GET"]) +# def get_one_planet(planet_id): + +# planet = validate_planet(planet_id) + +# return jsonify(to_dict(planet)) + +# def validate_planet(planet_id): +# try: +# planet_id = int(planet_id) +# except ValueError: +# abort(make_response({"message": f"invalid id {planet_id}"}, 400)) + +# for planet in planets: +# if planet.id == planet_id: +# return planet +# abort(make_response({"message": f"planet id {planet_id} not found"}, 404)) \ 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/97aca7ff74c7_adds_planet_model.py b/migrations/versions/97aca7ff74c7_adds_planet_model.py new file mode 100644 index 000000000..368ee4895 --- /dev/null +++ b/migrations/versions/97aca7ff74c7_adds_planet_model.py @@ -0,0 +1,34 @@ +"""adds Planet model + +Revision ID: 97aca7ff74c7 +Revises: +Create Date: 2022-04-29 14:25:01.866648 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '97aca7ff74c7' +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.Integer(), 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 c1badd8ea4100dcbb205741d48596b3577cc9377 Mon Sep 17 00:00:00 2001 From: Esther Annorzie Date: Fri, 29 Apr 2022 14:43:39 -0400 Subject: [PATCH 06/10] created routes --- app/routes.py | 35 +++++++++++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/app/routes.py b/app/routes.py index bbfa384cf..8e407dab2 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,4 +1,4 @@ -from flask import Blueprint, jsonify, abort, make_response +from flask import Blueprint, jsonify, abort, make_response, request from app.models.planet import Planet from app import db @@ -8,6 +8,21 @@ # self.name = name # self.description = description +# create the blueprint +planets_bp = Blueprint("planets", __name__, url_prefix="/planets") + +@planets_bp.route("", methods=["POST"]) +def handle_planets(): + 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() + + return make_response(f"Planet {new_planet.name} successfully created", 201) # create our instances # planets = [ @@ -16,9 +31,6 @@ # Planets(3, "Earth", "Has lots of life") # ] -# create the blueprint -planets_bp = Blueprint("planets", __name__, url_prefix="/planets") - # do the decorator # @planets_bp.route("", methods=["GET"]) @@ -28,6 +40,21 @@ # for planet in planets # ]) +@planets_bp.route("", methods=["GET"]) +def read_all_planets(): + planets_response = [] + planets = Planet.query.all() + for planet in planets: + planets_response.append( + { + "id": planet.id, + "name": planet.name, + "description": planet.description, + "moons": planet.moons + } + ) + return jsonify(planets_response) + # @planets_bp.route("/", methods = ["GET"]) # def get_one_planet(planet_id): From 97085ae5e7115a1e42d04899efbd4c10c2f056a1 Mon Sep 17 00:00:00 2001 From: Esther Annorzie Date: Tue, 3 May 2022 14:04:33 -0400 Subject: [PATCH 07/10] completed wave 4 --- app/models/planet.py | 10 ++++++- app/routes.py | 62 +++++++++++++++++++++++++++++--------------- 2 files changed, 50 insertions(+), 22 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index 4b822cd0d..5dfe1448b 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) - moons = db.Column(db.Integer) \ No newline at end of file + moons = db.Column(db.Integer) + + def to_dict(self): + 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 8e407dab2..133418cef 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,3 +1,4 @@ +from attr import validate from flask import Blueprint, jsonify, abort, make_response, request from app.models.planet import Planet from app import db @@ -45,30 +46,49 @@ def read_all_planets(): planets_response = [] planets = Planet.query.all() for planet in planets: - planets_response.append( - { - "id": planet.id, - "name": planet.name, - "description": planet.description, - "moons": planet.moons - } - ) + planets_response.append(planet.to_dict()) return jsonify(planets_response) -# @planets_bp.route("/", methods = ["GET"]) -# def get_one_planet(planet_id): -# planet = validate_planet(planet_id) +@planets_bp.route("/", methods = ["GET"]) +def get_one_planet(planet_id): -# return jsonify(to_dict(planet)) + planet = validate_planet(planet_id) -# def validate_planet(planet_id): -# try: -# planet_id = int(planet_id) -# except ValueError: -# abort(make_response({"message": f"invalid id {planet_id}"}, 400)) + return jsonify(planet.to_dict()) -# for planet in planets: -# if planet.id == planet_id: -# return planet -# abort(make_response({"message": f"planet id {planet_id} not found"}, 404)) \ No newline at end of file + +@planets_bp.route("/", methods = ["PUT"]) +def update_planet(planet_id): + request_body = request.get_json() + planet = validate_planet(planet_id) + + planet.name = request_body["name"] + planet.description = request_body["description"] + planet.moons = request_body["moons"] + + db.session.commit() + + return make_response(f"Planet succesfully updated. {planet.to_dict()}") + +@planets_bp.route("/", methods = ["DELETE"]) +def delete_planet(planet_id): + planet = validate_planet(planet_id) + + db.session.delete(planet) + db.session.commit() + + return make_response(f"Planet succesffuly deleted.") + +def validate_planet(planet_id): + try: + planet_id = int(planet_id) + except: + abort(make_response({"message": f"invalid id {planet_id}"}, 400)) + + planet = Planet.query.get(planet_id) + + if not planet: + abort(make_response({"message": f"planet id {planet_id} not found"}, 404)) + + return planet \ No newline at end of file From f76cfed04f29e913acfb4faa1ba65681437b8d83 Mon Sep 17 00:00:00 2001 From: Danielle Date: Wed, 4 May 2022 13:30:48 -0500 Subject: [PATCH 08/10] added query params and added class method from dict --- app/models/planet.py | 9 ++++++++- app/routes.py | 46 +++++++++++++++----------------------------- 2 files changed, 24 insertions(+), 31 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index 5dfe1448b..7fd67e993 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -12,4 +12,11 @@ def to_dict(self): "name": self.name, "description": self.description, "moons": self.moons - } \ No newline at end of file + } + + @classmethod + def from_dict(cls, data_dict): + return cls(name=data_dict["name"], + description=data_dict["description"], + moons=data_dict["moons"] + ) \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 133418cef..5a3a73728 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,50 +1,36 @@ -from attr import validate from flask import Blueprint, jsonify, abort, make_response, request from app.models.planet import Planet from app import db -# class Planets: -# def __init__(self, id, name, description): -# self.id = id -# self.name = name -# self.description = description - -# create the blueprint planets_bp = Blueprint("planets", __name__, url_prefix="/planets") @planets_bp.route("", methods=["POST"]) -def handle_planets(): +def create_planet(): request_body = request.get_json() - new_planet = Planet(name=request_body["name"], - description=request_body["description"], - moons=request_body["moons"] - ) + + new_planet = Planet.from_dict(request_body) db.session.add(new_planet) db.session.commit() return make_response(f"Planet {new_planet.name} successfully created", 201) -# create our instances -# planets = [ -# Planets(1, "Mercury", "Small hot planet"), -# Planets(2, "Venus", "A gaseous planet"), -# Planets(3, "Earth", "Has lots of life") -# ] - - -# do the decorator -# @planets_bp.route("", methods=["GET"]) -# def get_all_planets(): -# return jsonify([ -# to_dict(planet) -# for planet in planets -# ]) - @planets_bp.route("", methods=["GET"]) def read_all_planets(): + + name_query = request.args.get("name") + if name_query: + planets = Planet.query.filter_by(name=name_query) + else: + planets = Planet.query.all() + # description_query = request.args.get("description") + # if description_query: + # planets.extend(Planet.query.filter_by(description=description_query)) + + # if not planets: + # planets = Planet.query.all() + planets_response = [] - planets = Planet.query.all() for planet in planets: planets_response.append(planet.to_dict()) return jsonify(planets_response) From 121323f6582dcc02f0e068cda54ad703a54e079b Mon Sep 17 00:00:00 2001 From: Danielle Date: Thu, 5 May 2022 13:23:08 -0500 Subject: [PATCH 09/10] wrote tests for wave 06 --- app/__init__.py | 16 ++++++++++++---- app/routes.py | 8 ++++---- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index b21dac6a2..91026f3c6 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,16 +1,24 @@ from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate +import os +from dotenv import load_dotenv 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) diff --git a/app/routes.py b/app/routes.py index 5a3a73728..6914dbe2d 100644 --- a/app/routes.py +++ b/app/routes.py @@ -13,7 +13,7 @@ def create_planet(): db.session.add(new_planet) db.session.commit() - return make_response(f"Planet {new_planet.name} successfully created", 201) + return make_response(jsonify(f"Planet {new_planet.name} successfully created"), 201) @planets_bp.route("", methods=["GET"]) def read_all_planets(): @@ -55,7 +55,8 @@ def update_planet(planet_id): db.session.commit() - return make_response(f"Planet succesfully updated. {planet.to_dict()}") + return make_response(jsonify(f"Planet succesfully updated. {planet.to_dict()}")) + @planets_bp.route("/", methods = ["DELETE"]) def delete_planet(planet_id): @@ -64,7 +65,7 @@ def delete_planet(planet_id): db.session.delete(planet) db.session.commit() - return make_response(f"Planet succesffuly deleted.") + return make_response(jsonify(f"Planet succesffuly deleted.")) def validate_planet(planet_id): try: @@ -76,5 +77,4 @@ def validate_planet(planet_id): if not planet: abort(make_response({"message": f"planet id {planet_id} not found"}, 404)) - return planet \ No newline at end of file From 07aa8502f834456751bd2d7cfc793bba8b499d2d Mon Sep 17 00:00:00 2001 From: Danielle Date: Thu, 5 May 2022 14:18:17 -0500 Subject: [PATCH 10/10] refactored code to add jsonify_message --- app/routes.py | 25 +++++++++---------------- 1 file changed, 9 insertions(+), 16 deletions(-) diff --git a/app/routes.py b/app/routes.py index 6914dbe2d..0cb19b796 100644 --- a/app/routes.py +++ b/app/routes.py @@ -13,34 +13,23 @@ def create_planet(): db.session.add(new_planet) db.session.commit() - return make_response(jsonify(f"Planet {new_planet.name} successfully created"), 201) + return jsonify_message(f"Planet {new_planet.name} successfully created", 201) @planets_bp.route("", methods=["GET"]) def read_all_planets(): - name_query = request.args.get("name") if name_query: planets = Planet.query.filter_by(name=name_query) else: planets = Planet.query.all() - # description_query = request.args.get("description") - # if description_query: - # planets.extend(Planet.query.filter_by(description=description_query)) - - # if not planets: - # planets = Planet.query.all() - planets_response = [] - for planet in planets: - planets_response.append(planet.to_dict()) + planets_response = [planet.to_dict() for planet in planets] return jsonify(planets_response) @planets_bp.route("/", methods = ["GET"]) def get_one_planet(planet_id): - planet = validate_planet(planet_id) - return jsonify(planet.to_dict()) @@ -55,7 +44,7 @@ def update_planet(planet_id): db.session.commit() - return make_response(jsonify(f"Planet succesfully updated. {planet.to_dict()}")) + return jsonify_message(f"Planet succesfully updated. {planet.to_dict()}") @planets_bp.route("/", methods = ["DELETE"]) @@ -65,7 +54,7 @@ def delete_planet(planet_id): db.session.delete(planet) db.session.commit() - return make_response(jsonify(f"Planet succesffuly deleted.")) + return jsonify_message("Planet succesfully deleted.", 200) def validate_planet(planet_id): try: @@ -77,4 +66,8 @@ def validate_planet(planet_id): if not planet: abort(make_response({"message": f"planet id {planet_id} not found"}, 404)) - return planet \ No newline at end of file + return planet + + +def jsonify_message(message, status_code): + return make_response(jsonify(message),status_code) \ No newline at end of file