From d3c133b8d71e8dfd5b6483ca3d42f7b292fefa7f Mon Sep 17 00:00:00 2001 From: Rebeca Date: Mon, 18 Oct 2021 14:29:36 -0700 Subject: [PATCH 01/13] Create planet class and instances. --- app/__init__.py | 4 +++- app/routes.py | 13 +++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..2a77b41b8 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,7 +1,9 @@ from flask import Flask -def create_app(test_config=None): +def create_app(): 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..1b6975797 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,15 @@ from flask import Blueprint +class Planet: + def __init__(self, id, name, description, moon): + self.id = id + self.name = name + self.description = description + self.moon = moon +planets = [ + Planet(1, "Saturn", "A gassy, heavy, giant who's sixth from the sun. Most likely compposed of iron, nickel, and rock.", 82), + Planet(2, "Mercury", "When it retrogrades everything in the world sucks.", 0), + Planet(3, "Venus", "It is named after the goddess of love and beauty. Second brightest object in the sky.", 0) +] + +planets_bp = Blueprint("planets", __name__, url_prefix="/planets") \ No newline at end of file From 85ae3bd1dd0fedcbc7d7c447d503c6410daaf9a2 Mon Sep 17 00:00:00 2001 From: Rebeca Date: Mon, 18 Oct 2021 14:49:55 -0700 Subject: [PATCH 02/13] Created blueprint and endpoints --- app/routes.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index 1b6975797..f9e496cca 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,4 +1,6 @@ from flask import Blueprint +from flask import Blueprint, jsonify + class Planet: def __init__(self, id, name, description, moon): self.id = id @@ -12,4 +14,16 @@ def __init__(self, id, name, description, moon): Planet(3, "Venus", "It is named after the goddess of love and beauty. Second brightest object in the sky.", 0) ] -planets_bp = Blueprint("planets", __name__, url_prefix="/planets") \ No newline at end of file +planets_bp = Blueprint("planets", __name__, url_prefix="/planets") + +@planets_bp.route("", methods=["GET"]) +def read_planets(): + planet_response = [] + for planet in planets: + planet_response.append({ + "id": planet.id, + "name": planet.name, + "description": planet.description, + "moon": planet.moon + }) + return jsonify(planet_response) \ No newline at end of file From 617241ebeba43eb17a8cbf976118661eceab15c7 Mon Sep 17 00:00:00 2001 From: Rebeca Date: Mon, 18 Oct 2021 15:14:10 -0700 Subject: [PATCH 03/13] Create a route for single planet --- app/routes.py | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index f9e496cca..12bfce706 100644 --- a/app/routes.py +++ b/app/routes.py @@ -17,6 +17,7 @@ def __init__(self, id, name, description, moon): planets_bp = Blueprint("planets", __name__, url_prefix="/planets") @planets_bp.route("", methods=["GET"]) + def read_planets(): planet_response = [] for planet in planets: @@ -26,4 +27,18 @@ def read_planets(): "description": planet.description, "moon": planet.moon }) - return jsonify(planet_response) \ No newline at end of file + return jsonify(planet_response) + +@planets_bp.route("/", methods=["GET"]) +def read_single_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, + "moon": planet.moon + } + + From dc2f7113b074d97e4430aac8be46c31f9f95e562 Mon Sep 17 00:00:00 2001 From: Lizet Tovar Date: Thu, 21 Oct 2021 14:43:54 -0700 Subject: [PATCH 04/13] DRY up code. Create to_json helper function. --- app/__init__.py | 1 + app/routes.py | 31 ++++++++++++++++--------------- 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 2a77b41b8..0683a37f0 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -3,6 +3,7 @@ def create_app(): app = Flask(__name__) + from .routes import planets_bp app.register_blueprint(planets_bp) diff --git a/app/routes.py b/app/routes.py index 12bfce706..e16aad345 100644 --- a/app/routes.py +++ b/app/routes.py @@ -7,6 +7,14 @@ def __init__(self, id, name, description, moon): self.name = name self.description = description self.moon = moon + + def to_json(self): + return { + "id": self.id, + "name": self.name, + "description": self.description, + "moon": self.moon + } planets = [ Planet(1, "Saturn", "A gassy, heavy, giant who's sixth from the sun. Most likely compposed of iron, nickel, and rock.", 82), @@ -21,24 +29,17 @@ def __init__(self, id, name, description, moon): def read_planets(): planet_response = [] for planet in planets: - planet_response.append({ - "id": planet.id, - "name": planet.name, - "description": planet.description, - "moon": planet.moon - }) + planet_response.append( + planet.to_json() + ) return jsonify(planet_response) @planets_bp.route("/", methods=["GET"]) def read_single_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, - "moon": planet.moon - } - - + if planet.id == planet_id: + return planet.to_json() + # consider writing conditional that returns + # a message if planet id does not exist. + \ No newline at end of file From 4cded86807bbdf66c8cb941ec22e314a89df598c Mon Sep 17 00:00:00 2001 From: Lizet Tovar Date: Mon, 25 Oct 2021 14:50:09 -0700 Subject: [PATCH 05/13] Create database, model, and configured to flask and db. --- app/__init__.py | 14 +++++++++++++- app/models/__init__.py | 0 app/models/planet.py | 15 +++++++++++++++ app/routes.py | 41 ++++++++++++++++++++++------------------- 4 files changed, 50 insertions(+), 20 deletions(-) create mode 100644 app/models/__init__.py create mode 100644 app/models/planet.py diff --git a/app/__init__.py b/app/__init__.py index 0683a37f0..4bf10a1df 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,10 +1,22 @@ from flask import Flask +from flask_sqlalchemy import SQLAlchemy +from flask_migrate import Migrate +db = SQLAlchemy() +migrate = Migrate() -def create_app(): +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/planets_development' + + db.init_app(app) + migrate.init_app(app, db) + from .routes import planets_bp app.register_blueprint(planets_bp) + from app.models.planet import Planet + return app diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/app/models/planet.py b/app/models/planet.py new file mode 100644 index 000000000..a762b9d0b --- /dev/null +++ b/app/models/planet.py @@ -0,0 +1,15 @@ +from app import db + +class Planet(db.Model): + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + title = db.Column(db.String) + description = db.Column(db.String) + moon = db.Column(db.Integer) + + def to_json(self): + return { + "id": self.id, + "name": self.name, + "description": self.description, + "moon": self.moon + } \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index e16aad345..4cd977cdd 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,5 +1,8 @@ from flask import Blueprint from flask import Blueprint, jsonify +from flask_sqlalchemy import SQLAlchemy + +db = SQLAlchemy() class Planet: def __init__(self, id, name, description, moon): @@ -16,30 +19,30 @@ def to_json(self): "moon": self.moon } -planets = [ - Planet(1, "Saturn", "A gassy, heavy, giant who's sixth from the sun. Most likely compposed of iron, nickel, and rock.", 82), - Planet(2, "Mercury", "When it retrogrades everything in the world sucks.", 0), - Planet(3, "Venus", "It is named after the goddess of love and beauty. Second brightest object in the sky.", 0) -] +# planets = [ +# Planet(1, "Saturn", "A gassy, heavy, giant who's sixth from the sun. Most likely compposed of iron, nickel, and rock.", 82), +# Planet(2, "Mercury", "When it retrogrades everything in the world sucks.", 0), +# Planet(3, "Venus", "It is named after the goddess of love and beauty. Second brightest object in the sky.", 0) +# ] planets_bp = Blueprint("planets", __name__, url_prefix="/planets") -@planets_bp.route("", methods=["GET"]) +# @planets_bp.route("", methods=["GET"]) -def read_planets(): - planet_response = [] - for planet in planets: - planet_response.append( - planet.to_json() - ) - return jsonify(planet_response) +# def read_planets(): +# planet_response = [] +# for planet in planets: +# planet_response.append( +# planet.to_json() +# ) +# return jsonify(planet_response) -@planets_bp.route("/", methods=["GET"]) -def read_single_planet(planet_id): - planet_id = int(planet_id) - for planet in planets: - if planet.id == planet_id: - return planet.to_json() +# @planets_bp.route("/", methods=["GET"]) +# def read_single_planet(planet_id): +# planet_id = int(planet_id) +# for planet in planets: +# if planet.id == planet_id: +# return planet.to_json() # consider writing conditional that returns # a message if planet id does not exist. \ No newline at end of file From 5f4682530fddf756d1fb4c4962021aacb9d90d27 Mon Sep 17 00:00:00 2001 From: Lizet Tovar Date: Mon, 25 Oct 2021 19:04:32 -0700 Subject: [PATCH 06/13] Created a POST method and route. --- app/routes.py | 73 ++++++++------ migrations/README | 1 + migrations/alembic.ini | 45 +++++++++ migrations/env.py | 96 +++++++++++++++++++ migrations/script.py.mako | 24 +++++ .../9ff38066f950_adds_planet_model.py | 34 +++++++ 6 files changed, 245 insertions(+), 28 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/9ff38066f950_adds_planet_model.py diff --git a/app/routes.py b/app/routes.py index 4cd977cdd..185b4ed4e 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,23 +1,48 @@ -from flask import Blueprint -from flask import Blueprint, jsonify -from flask_sqlalchemy import SQLAlchemy - -db = SQLAlchemy() - -class Planet: - def __init__(self, id, name, description, moon): - self.id = id - self.name = name - self.description = description - self.moon = moon +from app import db +from app.models.planet import Planet +from flask import Blueprint, jsonify, make_response, request + +planets_bp = Blueprint("planets", __name__, url_prefix="/planets") + +@planets_bp.route("", methods=["POST"]) +def read_planets(): + if request.method == "POST": + request_body = request.get_json() + if "name" not in request_body or "description" not in request_body: + return make_response("Invalid Request", 400) + new_planet = Planet( + name=request_body["name"], + description=request_body["description"] + ) + db.session.add(new_planet) + db.session.commit() + + return make_response( + # We are specifcyig 201 for something created. Otherwsie 200 is the default. + f"Book {new_planet.title} created", 201 + ) + + # planet_response = [] + # for planet in planets: + # planet_response.append( + # planet.to_json() + # ) + # return jsonify(planet_response) + +# class Planet: +# def __init__(self, id, name, description, moon): +# self.id = id +# self.name = name +# self.description = description +# self.moon = moon - def to_json(self): - return { - "id": self.id, - "name": self.name, - "description": self.description, - "moon": self.moon - } +# def to_json(self): +# return { +# "id": self.id, +# "name": self.name, +# "description": self.description, +# "moon": self.moon +# } # planets = [ # Planet(1, "Saturn", "A gassy, heavy, giant who's sixth from the sun. Most likely compposed of iron, nickel, and rock.", 82), @@ -25,17 +50,9 @@ def to_json(self): # Planet(3, "Venus", "It is named after the goddess of love and beauty. Second brightest object in the sky.", 0) # ] -planets_bp = Blueprint("planets", __name__, url_prefix="/planets") - # @planets_bp.route("", methods=["GET"]) -# def read_planets(): -# planet_response = [] -# for planet in planets: -# planet_response.append( -# planet.to_json() -# ) -# return jsonify(planet_response) + # @planets_bp.route("/", methods=["GET"]) # def read_single_planet(planet_id): diff --git a/migrations/README b/migrations/README new file mode 100644 index 000000000..98e4f9c44 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 000000000..f8ed4801f --- /dev/null +++ b/migrations/alembic.ini @@ -0,0 +1,45 @@ +# A generic, single database configuration. + +[alembic] +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 000000000..8b3fb3353 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,96 @@ +from __future__ import with_statement + +import logging +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool +from flask import current_app + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) +logger = logging.getLogger('alembic.env') + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +config.set_main_option( + 'sqlalchemy.url', + str(current_app.extensions['migrate'].db.engine.url).replace('%', '%%')) +target_metadata = current_app.extensions['migrate'].db.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, target_metadata=target_metadata, literal_binds=True + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + # this callback is used to prevent an auto-migration from being generated + # when there are no changes to the schema + # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html + def process_revision_directives(context, revision, directives): + if getattr(config.cmd_opts, 'autogenerate', False): + script = directives[0] + if script.upgrade_ops.is_empty(): + directives[:] = [] + logger.info('No changes in schema detected.') + + connectable = engine_from_config( + config.get_section(config.config_ini_section), + prefix='sqlalchemy.', + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=target_metadata, + process_revision_directives=process_revision_directives, + **current_app.extensions['migrate'].configure_args + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 000000000..2c0156303 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,24 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} diff --git a/migrations/versions/9ff38066f950_adds_planet_model.py b/migrations/versions/9ff38066f950_adds_planet_model.py new file mode 100644 index 000000000..71d4e6849 --- /dev/null +++ b/migrations/versions/9ff38066f950_adds_planet_model.py @@ -0,0 +1,34 @@ +"""adds Planet model + +Revision ID: 9ff38066f950 +Revises: +Create Date: 2021-10-25 14:51:26.456748 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '9ff38066f950' +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('moon', 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 09654d1cd963ad81c91ccc6b4f4033b9c68928c9 Mon Sep 17 00:00:00 2001 From: Lizet Tovar Date: Mon, 25 Oct 2021 19:26:53 -0700 Subject: [PATCH 07/13] Cleaned up syntax. --- app/models/planet.py | 2 +- app/routes.py | 22 +++++++++++++++------- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index a762b9d0b..dcf8ca05d 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -2,7 +2,7 @@ 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) moon = db.Column(db.Integer) diff --git a/app/routes.py b/app/routes.py index 185b4ed4e..dfcaf3c0d 100644 --- a/app/routes.py +++ b/app/routes.py @@ -4,24 +4,32 @@ planets_bp = Blueprint("planets", __name__, url_prefix="/planets") -@planets_bp.route("", methods=["POST"]) +@planets_bp.route("", methods=["POST", "GET"]) def read_planets(): if request.method == "POST": request_body = request.get_json() if "name" not in request_body or "description" not in request_body: - return make_response("Invalid Request", 400) + return {"error": "Incomplete request body"}, 400 + new_planet = Planet( name=request_body["name"], description=request_body["description"] + # moon=request_body["moon"] ) db.session.add(new_planet) db.session.commit() - return make_response( - # We are specifcyig 201 for something created. Otherwsie 200 is the default. - f"Book {new_planet.title} created", 201 - ) - + return make_response(f"Planet {new_planet.name} created!", 201) + + elif request.method == "GET": + planets = Planet.query.all() + planets_response = [] + for planet in planets: + planets_response.append( + planet.to_dict() + ) + return jsonify(planets_response) + # planet_response = [] # for planet in planets: # planet_response.append( From ab4eb0e8e089992b1ca535f922887caee25fb160 Mon Sep 17 00:00:00 2001 From: Lizet Tovar Date: Mon, 25 Oct 2021 19:32:08 -0700 Subject: [PATCH 08/13] Create read_planet route and function. --- app/routes.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/app/routes.py b/app/routes.py index dfcaf3c0d..63952e5a4 100644 --- a/app/routes.py +++ b/app/routes.py @@ -30,6 +30,16 @@ def read_planets(): ) return jsonify(planets_response) +@planets_bp.route("/", methods=["GET"]) +def read_planet(planet_id): + try: + planet_id = int(planet_id) + except: + return {"error": "planet_id must be an int"}, 400 + + planet = Planet.query.get(planet_id) + return planet.to_dict() + # planet_response = [] # for planet in planets: # planet_response.append( From af006a997b7807bf4f6a6d3b61ab05a6296cb998 Mon Sep 17 00:00:00 2001 From: Lizet Tovar Date: Tue, 26 Oct 2021 11:40:18 -0700 Subject: [PATCH 09/13] Fix planet model and database. --- app/routes.py | 4 ++-- ...anet_model.py => 65ee8822bc22_adds_planet_model.py} | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) rename migrations/versions/{9ff38066f950_adds_planet_model.py => 65ee8822bc22_adds_planet_model.py} (80%) diff --git a/app/routes.py b/app/routes.py index 63952e5a4..f82d1ee96 100644 --- a/app/routes.py +++ b/app/routes.py @@ -13,8 +13,8 @@ def read_planets(): new_planet = Planet( name=request_body["name"], - description=request_body["description"] - # moon=request_body["moon"] + description=request_body["description"], + moon=request_body["moon"] ) db.session.add(new_planet) db.session.commit() diff --git a/migrations/versions/9ff38066f950_adds_planet_model.py b/migrations/versions/65ee8822bc22_adds_planet_model.py similarity index 80% rename from migrations/versions/9ff38066f950_adds_planet_model.py rename to migrations/versions/65ee8822bc22_adds_planet_model.py index 71d4e6849..e14f63aca 100644 --- a/migrations/versions/9ff38066f950_adds_planet_model.py +++ b/migrations/versions/65ee8822bc22_adds_planet_model.py @@ -1,8 +1,8 @@ -"""adds Planet model +"""Adds planet model -Revision ID: 9ff38066f950 +Revision ID: 65ee8822bc22 Revises: -Create Date: 2021-10-25 14:51:26.456748 +Create Date: 2021-10-26 11:39:44.923088 """ from alembic import op @@ -10,7 +10,7 @@ # revision identifiers, used by Alembic. -revision = '9ff38066f950' +revision = '65ee8822bc22' 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('moon', sa.Integer(), nullable=True), sa.PrimaryKeyConstraint('id') From b5749fbec94a318e910a8e9bd734382a218475f0 Mon Sep 17 00:00:00 2001 From: Lizet Tovar Date: Tue, 26 Oct 2021 11:53:18 -0700 Subject: [PATCH 10/13] Fix route for all and single planets --- app/routes.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/routes.py b/app/routes.py index f82d1ee96..ac820c4f8 100644 --- a/app/routes.py +++ b/app/routes.py @@ -26,7 +26,7 @@ def read_planets(): planets_response = [] for planet in planets: planets_response.append( - planet.to_dict() + planet.to_json() ) return jsonify(planets_response) @@ -38,7 +38,7 @@ def read_planet(planet_id): return {"error": "planet_id must be an int"}, 400 planet = Planet.query.get(planet_id) - return planet.to_dict() + return planet.to_json() # planet_response = [] # for planet in planets: From f434a4a89a3a4c65ec5dd2600212e8eea7f296a5 Mon Sep 17 00:00:00 2001 From: Lizet Tovar Date: Tue, 26 Oct 2021 12:04:10 -0700 Subject: [PATCH 11/13] Add PUT and DELETE methods --- app/routes.py | 40 +++++++++++++++++++++++++++++++++------- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/app/routes.py b/app/routes.py index ac820c4f8..a3656b3e7 100644 --- a/app/routes.py +++ b/app/routes.py @@ -30,15 +30,41 @@ def read_planets(): ) return jsonify(planets_response) -@planets_bp.route("/", methods=["GET"]) +@planets_bp.route("/", methods=["GET", "PUT", "DELETE"]) def read_planet(planet_id): - try: - planet_id = int(planet_id) - except: - return {"error": "planet_id must be an int"}, 400 - planet = Planet.query.get(planet_id) - return planet.to_json() + if planet is None: + return make_response ("This planet does not exist"), 404 + request_body = request.get_json() + + if request.method == "GET": + return planet.to_json() + + elif request.method == "PUT": + planet.name = request_body["name"] + planet.description = request_body["description"] + + db.session.commit() + + return make_response(f"Planet #{planet.id} successfully updated") + + elif "name" not in request_body or "description" not in request_body: + return { + "message": "Request requires both a name and description" + }, 400 + + elif request.method == "DELETE": + db.session.delete(planet) + db.session.commit() + return make_response(f"Planet #{planet.id} successfully deleted"), 200 + + # try: + # planet_id = int(planet_id) + # except: + # return {"error": "planet_id must be an int"}, 400 + + # planet = Planet.query.get(planet_id) + # return planet.to_json() # planet_response = [] # for planet in planets: From f22abf2f97346a7dccfd1321483570b75f33c239 Mon Sep 17 00:00:00 2001 From: Lizet Tovar Date: Wed, 27 Oct 2021 11:25:20 -0700 Subject: [PATCH 12/13] Clean up code. --- app/routes.py | 52 +-------------------------------------------------- 1 file changed, 1 insertion(+), 51 deletions(-) diff --git a/app/routes.py b/app/routes.py index a3656b3e7..0fd4a1fb4 100644 --- a/app/routes.py +++ b/app/routes.py @@ -56,54 +56,4 @@ def read_planet(planet_id): elif request.method == "DELETE": db.session.delete(planet) db.session.commit() - return make_response(f"Planet #{planet.id} successfully deleted"), 200 - - # try: - # planet_id = int(planet_id) - # except: - # return {"error": "planet_id must be an int"}, 400 - - # planet = Planet.query.get(planet_id) - # return planet.to_json() - - # planet_response = [] - # for planet in planets: - # planet_response.append( - # planet.to_json() - # ) - # return jsonify(planet_response) - -# class Planet: -# def __init__(self, id, name, description, moon): -# self.id = id -# self.name = name -# self.description = description -# self.moon = moon - -# def to_json(self): -# return { -# "id": self.id, -# "name": self.name, -# "description": self.description, -# "moon": self.moon -# } - -# planets = [ -# Planet(1, "Saturn", "A gassy, heavy, giant who's sixth from the sun. Most likely compposed of iron, nickel, and rock.", 82), -# Planet(2, "Mercury", "When it retrogrades everything in the world sucks.", 0), -# Planet(3, "Venus", "It is named after the goddess of love and beauty. Second brightest object in the sky.", 0) -# ] - -# @planets_bp.route("", methods=["GET"]) - - - -# @planets_bp.route("/", methods=["GET"]) -# def read_single_planet(planet_id): -# planet_id = int(planet_id) -# for planet in planets: -# if planet.id == planet_id: -# return planet.to_json() - # consider writing conditional that returns - # a message if planet id does not exist. - \ No newline at end of file + return make_response(f"Planet #{planet.id} successfully deleted"), 200 \ No newline at end of file From d2ccf56e1c3b0c076b79622de9911670213292dd Mon Sep 17 00:00:00 2001 From: Rebeca Date: Wed, 3 Nov 2021 11:33:55 -0700 Subject: [PATCH 13/13] procfile changes --- Procfile | 1 + app/routes.py | 2 +- requirements.txt | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) 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 diff --git a/app/routes.py b/app/routes.py index 0fd4a1fb4..df0288e10 100644 --- a/app/routes.py +++ b/app/routes.py @@ -20,7 +20,7 @@ def read_planets(): db.session.commit() return make_response(f"Planet {new_planet.name} created!", 201) - + elif request.method == "GET": planets = Planet.query.all() planets_response = [] diff --git a/requirements.txt b/requirements.txt index fd90fffa8..d2f045e58 100644 --- a/requirements.txt +++ b/requirements.txt @@ -6,6 +6,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 itsdangerous==1.1.0 Jinja2==2.11.3