From a6e4ee0a2c4e21902c704fbd99b2135d6efaa210 Mon Sep 17 00:00:00 2001 From: Jaime Mitchell Date: Fri, 21 Oct 2022 17:58:59 -0400 Subject: [PATCH 01/18] Completed Wave 1 --- app/__init__.py | 3 ++- app/routes.py | 61 ++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 62 insertions(+), 2 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..946d63f01 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 bp + app.register_blueprint(bp) return app diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..cb083350d 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,61 @@ -from flask import Blueprint +from flask import Blueprint, jsonify + +class Planet: + def __init__(self, id, name, description, temperature): + self.id = id + self.name = name + self.description = description + self.temperature = temperature + + +planets = [ + Planet(1, "Venus", "yellow-white", "1000F"), + Planet(2, "Earth", "blue-green", "70F"), + Planet(3, "Mars", "red", "300F") +] + +bp = Blueprint("planets", __name__, url_prefix="/planets") # ENDPOINT + + +@bp.route("", methods=["GET"]) # CRUD METHOD created a new endpoint that catches requests going to "" (assumed +# "/books") with the HTTP method GET +# RESPONSE BODY +def handle_planets(): + results_list = [] + for planet in planets: + results_list.append(dict( + id=planet.id, + name=planet.name, + temperature=planet.temperature + )) + return jsonify(results_list) + +#from flask import Blueprint, jsonify + +# class Cat: +# def __init__(self, id, name, color, personality): +# self.id = id +# self.name = name +# self.color = color +# self.personality = personality + +# cats = [ +# Cat(1, "Luna", "grey", "naughty"), +# Cat(2, "Orange Cat", "orange", "antagonistic"), +# Cat(3, "Big Ears", "grey and white", "sleepy") +# ] + +# bp = Blueprint("cats", __name__, url_prefix="/cats") + +# @bp.route("", methods=["GET"]) +# def handle_cats(): +# results_list = [] +# for cat in cats: +# results_list.append(dict( +# id=cat.id, +# name=cat.name, +# color=cat.color, +# personality=cat.personality +# )) +# return jsonify(results_list) From dfec29d374e31f7862164d4e2d0a49195e3898b7 Mon Sep 17 00:00:00 2001 From: Jaime Mitchell Date: Sun, 23 Oct 2022 21:06:34 -0400 Subject: [PATCH 02/18] deleted comments --- app/routes.py | 43 ++++++++++++++----------------------------- 1 file changed, 14 insertions(+), 29 deletions(-) diff --git a/app/routes.py b/app/routes.py index cb083350d..29f009537 100644 --- a/app/routes.py +++ b/app/routes.py @@ -18,7 +18,8 @@ def __init__(self, id, name, description, temperature): bp = Blueprint("planets", __name__, url_prefix="/planets") # ENDPOINT -@bp.route("", methods=["GET"]) # CRUD METHOD created a new endpoint that catches requests going to "" (assumed +# CRUD METHOD created a new endpoint that catches requests going to "" (assumed +@bp.route("", methods=["GET"]) # "/books") with the HTTP method GET # RESPONSE BODY def handle_planets(): @@ -31,31 +32,15 @@ def handle_planets(): )) return jsonify(results_list) -#from flask import Blueprint, jsonify - -# class Cat: -# def __init__(self, id, name, color, personality): -# self.id = id -# self.name = name -# self.color = color -# self.personality = personality - -# cats = [ -# Cat(1, "Luna", "grey", "naughty"), -# Cat(2, "Orange Cat", "orange", "antagonistic"), -# Cat(3, "Big Ears", "grey and white", "sleepy") -# ] - -# bp = Blueprint("cats", __name__, url_prefix="/cats") - -# @bp.route("", methods=["GET"]) -# def handle_cats(): -# results_list = [] -# for cat in cats: -# results_list.append(dict( -# id=cat.id, -# name=cat.name, -# color=cat.color, -# personality=cat.personality -# )) -# return jsonify(results_list) +@bp.route("/", methods=['GET']) +def handle_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, + "temperature": planet.temperature + } + pass From 67f91a6e1b43b0df8ab307de252c764fc9291a92 Mon Sep 17 00:00:00 2001 From: Jaime Mitchell Date: Sun, 23 Oct 2022 21:16:40 -0400 Subject: [PATCH 03/18] changed return to dictionary to try out ashley's method of writing a dict --- app/routes.py | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/app/routes.py b/app/routes.py index 29f009537..c3d74be09 100644 --- a/app/routes.py +++ b/app/routes.py @@ -32,15 +32,10 @@ def handle_planets(): )) return jsonify(results_list) + @bp.route("/", methods=['GET']) def handle_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, - "temperature": planet.temperature - } - pass + return dict(id=planet.id, name=planet.name, temperature=planet.temperature) From 28c1426e0a415fd5106025eccfe9a30c81ff9568 Mon Sep 17 00:00:00 2001 From: Jaime Mitchell Date: Sun, 23 Oct 2022 21:27:34 -0400 Subject: [PATCH 04/18] Finished Planet 400 and 404 --- app/routes.py | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/app/routes.py b/app/routes.py index c3d74be09..64a82b484 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 Planet: @@ -33,9 +33,20 @@ def handle_planets(): return jsonify(results_list) -@bp.route("/", methods=['GET']) -def handle_planet(planet_id): - planet_id = int(planet_id) +def validate_planet(planet_id): + try: + planet_id = int(planet_id) + except: + abort(make_response( + {"message": f"planet {planet_id} is not valid"}, 400)) for planet in planets: if planet.id == planet_id: - return dict(id=planet.id, name=planet.name, temperature=planet.temperature) + return(planet) + abort(make_response( + {"message": f"planet {planet_id} does not exist"}, 404)) + + +@bp.route("/", methods=['GET']) +def handle_planet(planet_id): + planet = validate_planet(planet_id) + return dict(id=planet.id, name=planet.name, temperature=planet.temperature) From fc34f46b20b80d48ec4bf604a7d38d8523ec1255 Mon Sep 17 00:00:00 2001 From: Franklyn Rodriguez Date: Mon, 24 Oct 2022 15:15:40 -0400 Subject: [PATCH 05/18] Completed Wave 2 --- app/routes.py | 59 ++++++++++++++++++++---------------------------- requirements.txt | 8 +++++++ 2 files changed, 32 insertions(+), 35 deletions(-) diff --git a/app/routes.py b/app/routes.py index cb083350d..c8f8314d4 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,4 +1,5 @@ -from flask import Blueprint, jsonify +from flask import Blueprint, jsonify, abort, make_response +import json class Planet: @@ -7,7 +8,12 @@ def __init__(self, id, name, description, temperature): self.name = name self.description = description self.temperature = temperature - + def to_planet_dict(self): + return dict( + id=self.id, + name=self.name, + temperature=self.temperature + ) planets = [ Planet(1, "Venus", "yellow-white", "1000F"), @@ -17,6 +23,16 @@ def __init__(self, id, name, description, temperature): bp = Blueprint("planets", __name__, url_prefix="/planets") # ENDPOINT +def validate_planet(planet_id): + try: + planet_id = int(planet_id) + except: + abort(make_response({"message":f"planet{planet_id} not valid"},400)) + for planet in planets: + if planet.id == planet_id: + return planet + return abort(make_response({"message": f"planet{planet_id} not found"}, 404)) + @bp.route("", methods=["GET"]) # CRUD METHOD created a new endpoint that catches requests going to "" (assumed # "/books") with the HTTP method GET @@ -24,38 +40,11 @@ def __init__(self, id, name, description, temperature): def handle_planets(): results_list = [] for planet in planets: - results_list.append(dict( - id=planet.id, - name=planet.name, - temperature=planet.temperature - )) + results_list.append(planet.to_planet_dict()) return jsonify(results_list) + +@bp.route("/", methods=["GET"]) +def get_planet(planet_id): + planet = validate_planet(planet_id) + return jsonify(planet.to_planet_dict()) -#from flask import Blueprint, jsonify - -# class Cat: -# def __init__(self, id, name, color, personality): -# self.id = id -# self.name = name -# self.color = color -# self.personality = personality - -# cats = [ -# Cat(1, "Luna", "grey", "naughty"), -# Cat(2, "Orange Cat", "orange", "antagonistic"), -# Cat(3, "Big Ears", "grey and white", "sleepy") -# ] - -# bp = Blueprint("cats", __name__, url_prefix="/cats") - -# @bp.route("", methods=["GET"]) -# def handle_cats(): -# results_list = [] -# for cat in cats: -# results_list.append(dict( -# id=cat.id, -# name=cat.name, -# color=cat.color, -# personality=cat.personality -# )) -# return jsonify(results_list) diff --git a/requirements.txt b/requirements.txt index fba2b3e38..1eeabccdc 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,19 +1,26 @@ alembic==1.5.4 +attrs==22.1.0 autopep8==1.5.5 blinker==1.4 certifi==2020.12.5 chardet==4.0.0 click==7.1.2 +coverage==6.5.0 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.3 +pluggy==1.0.0 psycopg2-binary==2.9.4 +py==1.11.0 pycodestyle==2.6.0 +pyparsing==3.0.9 pytest==7.1.1 pytest-cov==2.12.1 python-dateutil==2.8.1 @@ -23,5 +30,6 @@ requests==2.25.1 six==1.15.0 SQLAlchemy==1.3.23 toml==0.10.2 +tomli==2.0.1 urllib3==1.26.4 Werkzeug==1.0.1 From c21dbc3981aae9ec9d5db8f51e67a7f81fdf27f8 Mon Sep 17 00:00:00 2001 From: Jaime Mitchell Date: Mon, 24 Oct 2022 15:16:39 -0400 Subject: [PATCH 06/18] my roundtable refactor with ashleys sweet dict in class method --- app/routes.py | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/app/routes.py b/app/routes.py index 64a82b484..1b8120f69 100644 --- a/app/routes.py +++ b/app/routes.py @@ -8,6 +8,14 @@ def __init__(self, id, name, description, temperature): self.description = description self.temperature = temperature + def to_planet_dict(self): + return dict( + id=self.id, + name=self.name, + description=self.description, + temperature=self.temperature + ) + planets = [ Planet(1, "Venus", "yellow-white", "1000F"), @@ -25,11 +33,7 @@ def __init__(self, id, name, description, temperature): def handle_planets(): results_list = [] for planet in planets: - results_list.append(dict( - id=planet.id, - name=planet.name, - temperature=planet.temperature - )) + results_list.append(planet.to_planet_dict()) return jsonify(results_list) @@ -39,9 +43,11 @@ def validate_planet(planet_id): except: abort(make_response( {"message": f"planet {planet_id} is not valid"}, 400)) + for planet in planets: if planet.id == planet_id: return(planet) + abort(make_response( {"message": f"planet {planet_id} does not exist"}, 404)) @@ -49,4 +55,4 @@ def validate_planet(planet_id): @bp.route("/", methods=['GET']) def handle_planet(planet_id): planet = validate_planet(planet_id) - return dict(id=planet.id, name=planet.name, temperature=planet.temperature) + return jsonify(planet.to_planet_dict()) From f23447a8e06252055d74cfc48f27f096c2db70b6 Mon Sep 17 00:00:00 2001 From: Jaime Mitchell Date: Mon, 24 Oct 2022 21:05:59 -0400 Subject: [PATCH 07/18] fixing some errors --- app/routes.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/app/routes.py b/app/routes.py index a996966ac..8615cc5f3 100644 --- a/app/routes.py +++ b/app/routes.py @@ -8,6 +8,7 @@ def __init__(self, id, name, description, temperature): self.name = name self.description = description self.temperature = temperature + def to_planet_dict(self): return dict( id=self.id, @@ -23,29 +24,29 @@ def to_planet_dict(self): Planet(3, "Mars", "red", "300F") ] -bp = Blueprint("planets", __name__, url_prefix="/planets") +bp = Blueprint("planets", __name__, url_prefix="/planets") + def validate_planet(planet_id): try: planet_id = int(planet_id) except: - abort(make_response({"message":f"planet{planet_id} not valid"},400)) + abort(make_response({"message": f"planet {planet_id} not valid"}, 400)) for planet in planets: if planet.id == planet_id: return planet - return abort(make_response({"message": f"planet{planet_id} not found"}, 404)) - + abort(make_response({"message": f"planet {planet_id} not found"}, 404)) -@bp.route("", methods=["GET"]) +@bp.route("", methods=["GET"]) def handle_planets(): results_list = [] for planet in planets: results_list.append(planet.to_planet_dict()) return jsonify(results_list) - + + @bp.route("/", methods=["GET"]) def get_planet(planet_id): planet = validate_planet(planet_id) return jsonify(planet.to_planet_dict()) - From 9c126d5e18aa50397fa5150c8474e6741ed83797 Mon Sep 17 00:00:00 2001 From: Jaime Mitchell Date: Fri, 28 Oct 2022 13:40:59 -0400 Subject: [PATCH 08/18] added files to practice with, SQL, CSV AND solar_system.py, are for personal practice. --- app/routes.py | 7 ++++--- planets.CSV | 9 +++++++++ planets.sql | 35 +++++++++++++++++++++++++++++++++++ solar_system.py | 6 ++++++ 4 files changed, 54 insertions(+), 3 deletions(-) create mode 100644 planets.CSV create mode 100644 planets.sql create mode 100644 solar_system.py diff --git a/app/routes.py b/app/routes.py index 8615cc5f3..435abbb74 100644 --- a/app/routes.py +++ b/app/routes.py @@ -19,9 +19,10 @@ def to_planet_dict(self): planets = [ - Planet(1, "Venus", "yellow-white", "1000F"), - Planet(2, "Earth", "blue-green", "70F"), - Planet(3, "Mars", "red", "300F") + Planet(1, 'Mercury', 'Grey', '333˚F(167˚C)'), + Planet(2, 'Venus', 'yellow-white', '967˚F(15°C)'), + Planet(3, 'Earth', 'blue-green', '59˚F(15°C)'), + Planet(4, 'Mars', 'red', '-85˚F(-65˚C') ] bp = Blueprint("planets", __name__, url_prefix="/planets") diff --git a/planets.CSV b/planets.CSV new file mode 100644 index 000000000..4978587d6 --- /dev/null +++ b/planets.CSV @@ -0,0 +1,9 @@ +Name,Surface Area,Moons,Distance from Sun,Namesake +Jupiter,23710000000,79,483300000,"King of the Roman gods, aka Zeus." +Mars,55910000,2,141000000,"Roman god of war, aka Ares." +Venus,67400000,0,177700000,"Roman goddess of love, aka Aphrodite." +Earth,57510000,1,93123021,"A variation on the word ""ground"" in several languages." +Neptune,2941000000,14,2793000000,"Roman god of the sea aka, Poseidon." +Saturn,16490000000,62,890900000,"Jupiter's father and titan aka, Chronos." +Uranus,3171000000,27,1784000000,"Greek personificatino of the sky or heavens, aka Caelus." +Mercury,28880000,0,35980000,"Roman god of travellers, aka Hermes." diff --git a/planets.sql b/planets.sql new file mode 100644 index 000000000..30b516d51 --- /dev/null +++ b/planets.sql @@ -0,0 +1,35 @@ +CREATE DATABASE solar_system; + +CREATE TABLE planets ( + + name VARCHAR(50), + surface_area BIGINT, + moons INT, + distance_from_sun BIGINT, + namesake TEXT +); + +INSERT INTO planets ( + name, + surface_area, + moons, + distance_from_sun, + namesake + ) + VALUES ('Jupiter',23710000000,79,483300000,'King of the Roman gods, aka Zeus.'), + ('Mars',55910000,2,141000000,'Roman god of war, aka Ares.'), + ('Venus',67400000,0,177700000,'Roman goddess of love, aka Aphrodite.'), + ('Earth',57510000,1,93123021,'A variation on the word ''ground'' in several languages'), + ('Neptune',2941000000,14,2793000000,'Roman god of the sea aka, Poseidon.'), + ('Saturn',16490000000,62,890900000,'Jupiter''s'' father and titan aka, Chronos.'), + ('Uranus',3171000000,27,1784000000,'Greek personificatino of the sky or heavens, aka Caelus.'), + ('Mercury',28880000,0,35980000,'Roman god of travellers, aka Hermes.'); + +DELETE FROM planets WHERE name = 'Jupiter' +-- # How many planets are there? +SELECT COUNT (*) FROM planets +-- What are the names of all the planets and the number of their moons that have a distance from the -- sun greater than 500,000,000 miles? +SELECT name , moons FROM planets WHERE distance_from_sun > 500000000; +-- What is the ID of the record with the 62 moons? +INSERT INTO planets (id) +VALUES (PRIMARY KEY GENERATED ALWAYS AS IDENTITY); diff --git a/solar_system.py b/solar_system.py new file mode 100644 index 000000000..8388de93c --- /dev/null +++ b/solar_system.py @@ -0,0 +1,6 @@ +import csv + +with open("planets.csv", "r", encoding="utf-8", newline="") as fid: + reader = csv.reader(fid, delimiter=",") + for planet in reader: + print(planet[0]) \ No newline at end of file From 04e7601c2681118363aebffc1795c8512c7a89e9 Mon Sep 17 00:00:00 2001 From: Jaime Mitchell Date: Fri, 28 Oct 2022 13:46:05 -0400 Subject: [PATCH 09/18] created wave 3 --- planets.CSV | 9 --------- planets.sql | 35 ----------------------------------- 2 files changed, 44 deletions(-) delete mode 100644 planets.CSV delete mode 100644 planets.sql diff --git a/planets.CSV b/planets.CSV deleted file mode 100644 index 4978587d6..000000000 --- a/planets.CSV +++ /dev/null @@ -1,9 +0,0 @@ -Name,Surface Area,Moons,Distance from Sun,Namesake -Jupiter,23710000000,79,483300000,"King of the Roman gods, aka Zeus." -Mars,55910000,2,141000000,"Roman god of war, aka Ares." -Venus,67400000,0,177700000,"Roman goddess of love, aka Aphrodite." -Earth,57510000,1,93123021,"A variation on the word ""ground"" in several languages." -Neptune,2941000000,14,2793000000,"Roman god of the sea aka, Poseidon." -Saturn,16490000000,62,890900000,"Jupiter's father and titan aka, Chronos." -Uranus,3171000000,27,1784000000,"Greek personificatino of the sky or heavens, aka Caelus." -Mercury,28880000,0,35980000,"Roman god of travellers, aka Hermes." diff --git a/planets.sql b/planets.sql deleted file mode 100644 index 30b516d51..000000000 --- a/planets.sql +++ /dev/null @@ -1,35 +0,0 @@ -CREATE DATABASE solar_system; - -CREATE TABLE planets ( - - name VARCHAR(50), - surface_area BIGINT, - moons INT, - distance_from_sun BIGINT, - namesake TEXT -); - -INSERT INTO planets ( - name, - surface_area, - moons, - distance_from_sun, - namesake - ) - VALUES ('Jupiter',23710000000,79,483300000,'King of the Roman gods, aka Zeus.'), - ('Mars',55910000,2,141000000,'Roman god of war, aka Ares.'), - ('Venus',67400000,0,177700000,'Roman goddess of love, aka Aphrodite.'), - ('Earth',57510000,1,93123021,'A variation on the word ''ground'' in several languages'), - ('Neptune',2941000000,14,2793000000,'Roman god of the sea aka, Poseidon.'), - ('Saturn',16490000000,62,890900000,'Jupiter''s'' father and titan aka, Chronos.'), - ('Uranus',3171000000,27,1784000000,'Greek personificatino of the sky or heavens, aka Caelus.'), - ('Mercury',28880000,0,35980000,'Roman god of travellers, aka Hermes.'); - -DELETE FROM planets WHERE name = 'Jupiter' --- # How many planets are there? -SELECT COUNT (*) FROM planets --- What are the names of all the planets and the number of their moons that have a distance from the -- sun greater than 500,000,000 miles? -SELECT name , moons FROM planets WHERE distance_from_sun > 500000000; --- What is the ID of the record with the 62 moons? -INSERT INTO planets (id) -VALUES (PRIMARY KEY GENERATED ALWAYS AS IDENTITY); From 37407398862c4865e96fccfcc840c4a90b7164e5 Mon Sep 17 00:00:00 2001 From: Jaime Mitchell Date: Fri, 28 Oct 2022 22:47:03 -0400 Subject: [PATCH 10/18] POST finito --- app/__init__.py | 17 +++- app/models/__init__.py | 0 app/models/planet.py | 8 ++ app/routes.py | 63 +++--------- migrations/README | 1 + migrations/alembic.ini | 45 +++++++++ migrations/env.py | 96 +++++++++++++++++++ migrations/script.py.mako | 24 +++++ .../e28a44e90eb7_adds_planet_model.py | 34 +++++++ solar_system.py | 6 -- 10 files changed, 237 insertions(+), 57 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/e28a44e90eb7_adds_planet_model.py delete mode 100644 solar_system.py diff --git a/app/__init__.py b/app/__init__.py index 946d63f01..dc1f1f85a 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__) - from.routes import bp - app.register_blueprint(bp) + + 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) + 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..966f059d4 --- /dev/null +++ b/app/models/planet.py @@ -0,0 +1,8 @@ +from app import db + +class Planet(db.Model): #The class Planet inherits from db.Model from SQLAlchemy + id= db.Column(db.Integer, primary_key=True, autoincrement=True) + name= db.Column(db.String) + description = db.Column(db.String) + temperature = db.Column(db.Integer) + \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 435abbb74..332e9aab8 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,53 +1,18 @@ -from flask import Blueprint, jsonify, abort, make_response -import json +from app import db +from app.models.planet import Planet +from flask import Blueprint, jsonify, abort, make_response, request +planets_bp = Blueprint("planets", __name__, url_prefix="/planets") -class Planet: - def __init__(self, id, name, description, temperature): - self.id = id - self.name = name - self.description = description - self.temperature = temperature - def to_planet_dict(self): - return dict( - id=self.id, - name=self.name, - description=self.description, - temperature=self.temperature - ) - - -planets = [ - Planet(1, 'Mercury', 'Grey', '333˚F(167˚C)'), - Planet(2, 'Venus', 'yellow-white', '967˚F(15°C)'), - Planet(3, 'Earth', 'blue-green', '59˚F(15°C)'), - Planet(4, 'Mars', 'red', '-85˚F(-65˚C') -] - -bp = Blueprint("planets", __name__, url_prefix="/planets") - - -def validate_planet(planet_id): - try: - planet_id = int(planet_id) - except: - abort(make_response({"message": f"planet {planet_id} not valid"}, 400)) - for planet in planets: - if planet.id == planet_id: - return planet - abort(make_response({"message": f"planet {planet_id} not found"}, 404)) - - -@bp.route("", methods=["GET"]) +# ("/",strict_slashes=False,methods=["POST"]) +@planets_bp.route("", methods=["POST"]) def handle_planets(): - results_list = [] - for planet in planets: - results_list.append(planet.to_planet_dict()) - return jsonify(results_list) - - -@bp.route("/", methods=["GET"]) -def get_planet(planet_id): - planet = validate_planet(planet_id) - return jsonify(planet.to_planet_dict()) + request_body = request.get_json() + new_planet = Planet(name=request_body["name"], + description=request_body["description"], + temperature=request_body["temperature"]) + db.session.add(new_planet) + db.session.commit() + + return make_response(f"Planet {new_planet.name} successful", 201) 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/e28a44e90eb7_adds_planet_model.py b/migrations/versions/e28a44e90eb7_adds_planet_model.py new file mode 100644 index 000000000..06c6db9ca --- /dev/null +++ b/migrations/versions/e28a44e90eb7_adds_planet_model.py @@ -0,0 +1,34 @@ +"""adds Planet model + +Revision ID: e28a44e90eb7 +Revises: +Create Date: 2022-10-28 15:40:07.924958 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'e28a44e90eb7' +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('temperature', 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 ### diff --git a/solar_system.py b/solar_system.py deleted file mode 100644 index 8388de93c..000000000 --- a/solar_system.py +++ /dev/null @@ -1,6 +0,0 @@ -import csv - -with open("planets.csv", "r", encoding="utf-8", newline="") as fid: - reader = csv.reader(fid, delimiter=",") - for planet in reader: - print(planet[0]) \ No newline at end of file From 1e825cc9e0873e37bc28b655e1cec6ce4269f94b Mon Sep 17 00:00:00 2001 From: Jaime Mitchell Date: Sat, 29 Oct 2022 20:40:37 -0400 Subject: [PATCH 11/18] finished wave 3 --- app/routes.py | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/app/routes.py b/app/routes.py index 332e9aab8..ad3f47d91 100644 --- a/app/routes.py +++ b/app/routes.py @@ -6,8 +6,9 @@ # ("/",strict_slashes=False,methods=["POST"]) -@planets_bp.route("", methods=["POST"]) -def handle_planets(): +# strict_slashes can use (or not) slash after endpoint! +@planets_bp.route("/", strict_slashes=False, methods=["POST"]) +def create_planets(): request_body = request.get_json() new_planet = Planet(name=request_body["name"], description=request_body["description"], @@ -16,3 +17,16 @@ def handle_planets(): db.session.commit() return make_response(f"Planet {new_planet.name} successful", 201) + +@planets_bp.route("/", strict_slashes=False, methods=["GET"]) +def read_planets(): + planets = Planet.query.all() + planets_response = [] + for planet in planets: + planets_response.append({ + "id": planet.id, + "name": planet.name, + "description": planet.description, + "temperature": planet.temperature + }) + return jsonify(planets_response) From 3223563812228ef42ead83dd63ae8cd236e8803a Mon Sep 17 00:00:00 2001 From: Jaime Mitchell Date: Tue, 1 Nov 2022 10:35:36 -0400 Subject: [PATCH 12/18] finished read one planet --- app/models/planet.py | 12 ++++++------ app/routes.py | 30 +++++++++++++++++++++++++++--- 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index 966f059d4..830ddbc06 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -1,8 +1,8 @@ from app import db -class Planet(db.Model): #The class Planet inherits from db.Model from SQLAlchemy - id= db.Column(db.Integer, primary_key=True, autoincrement=True) - name= db.Column(db.String) - description = db.Column(db.String) - temperature = db.Column(db.Integer) - \ No newline at end of file + +class Planet(db.Model): # The class Planet inherits from db.Model from SQLAlchemy + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + name = db.Column(db.String, nullable=False) + description = db.Column(db.String, nullable=False) + temperature = db.Column(db.Integer, nullable=False) diff --git a/app/routes.py b/app/routes.py index ad3f47d91..412b5dabd 100644 --- a/app/routes.py +++ b/app/routes.py @@ -4,9 +4,10 @@ planets_bp = Blueprint("planets", __name__, url_prefix="/planets") - # ("/",strict_slashes=False,methods=["POST"]) # strict_slashes can use (or not) slash after endpoint! + + @planets_bp.route("/", strict_slashes=False, methods=["POST"]) def create_planets(): request_body = request.get_json() @@ -18,9 +19,10 @@ def create_planets(): return make_response(f"Planet {new_planet.name} successful", 201) + @planets_bp.route("/", strict_slashes=False, methods=["GET"]) -def read_planets(): - planets = Planet.query.all() +def handle_planets(): + planets = Planet.query.all() # response body from request planets_response = [] for planet in planets: planets_response.append({ @@ -30,3 +32,25 @@ def read_planets(): "temperature": planet.temperature }) return jsonify(planets_response) + + +def validate_planet(planet_id): + try: + planet_id = int(planet_id) + except: + abort(make_response({"message": f"{planet_id} is not valid"}, 400)) + planet = Planet.query.get(planet_id) + if not planet: + abort(make_response({"message": f"{planet_id} can't be found"}, 404)) + return planet # this returns the query response body + + +@planets_bp.route("/", strict_slashes=False, methods=["GET"]) +def read_one_planet(planet_id): + planet = validate_planet(planet_id) + return { + "id": planet.id, + "name": planet.name, + "description": planet.description, + "temperature": planet.temperature + } From 76824a0e21ca912b03e894346f574449995557c8 Mon Sep 17 00:00:00 2001 From: Jaime Mitchell Date: Wed, 2 Nov 2022 08:11:49 -0400 Subject: [PATCH 13/18] wave 4 complete --- app/models/planet.py | 15 ++++++++++ app/routes.py | 65 ++++++++++++++++++++++++++------------------ 2 files changed, 54 insertions(+), 26 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index 830ddbc06..a9bc5f035 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -6,3 +6,18 @@ class Planet(db.Model): # The class Planet inherits from db.Model from SQLAlche name = db.Column(db.String, nullable=False) description = db.Column(db.String, nullable=False) temperature = db.Column(db.Integer, nullable=False) + + def to_dict(self): + return dict( + id=self.id, + name=self.name, + description=self.description, + temperature=self.temperature + ) + # can also return traditional dictionary: + # return { + # id=self.id, + # name=self.name, + # description=self.description, + # temperature=self.temperature + # } diff --git a/app/routes.py b/app/routes.py index 412b5dabd..e38033ceb 100644 --- a/app/routes.py +++ b/app/routes.py @@ -2,36 +2,33 @@ from app.models.planet import Planet from flask import Blueprint, jsonify, abort, make_response, request +# INSTANIATE BLUEPRINT FOR ROUTES planets_bp = Blueprint("planets", __name__, url_prefix="/planets") -# ("/",strict_slashes=False,methods=["POST"]) -# strict_slashes can use (or not) slash after endpoint! - @planets_bp.route("/", strict_slashes=False, methods=["POST"]) -def create_planets(): +def create_planet(): request_body = request.get_json() - new_planet = Planet(name=request_body["name"], - description=request_body["description"], - temperature=request_body["temperature"]) + new_planet = Planet( + name=request_body["name"], description=request_body["description"], temperature=request_body["temperature"]) db.session.add(new_planet) db.session.commit() - - return make_response(f"Planet {new_planet.name} successful", 201) + return make_response(f"Planet #{new_planet.name} successfully created", 200) @planets_bp.route("/", strict_slashes=False, methods=["GET"]) -def handle_planets(): - planets = Planet.query.all() # response body from request - planets_response = [] - for planet in planets: - planets_response.append({ - "id": planet.id, - "name": planet.name, - "description": planet.description, - "temperature": planet.temperature - }) +def read_all_planets(): + planets = Planet.query.all() + planets_response = [planet.to_dict() for planet in planets] return jsonify(planets_response) + # for planet in planets: + # planets_response.append({ + # "id": planet.id, + # "name": planet.name, + # "description": planet.description, + # "temperature": planet.temperature + # }) + # NEED JSONIFY FOR LISTS (BUT NOT DICTIONARIES) def validate_planet(planet_id): @@ -39,18 +36,34 @@ def validate_planet(planet_id): planet_id = int(planet_id) except: abort(make_response({"message": f"{planet_id} is not valid"}, 400)) + planet = Planet.query.get(planet_id) + if not planet: abort(make_response({"message": f"{planet_id} can't be found"}, 404)) - return planet # this returns the query response body + return planet @planets_bp.route("/", strict_slashes=False, methods=["GET"]) def read_one_planet(planet_id): planet = validate_planet(planet_id) - return { - "id": planet.id, - "name": planet.name, - "description": planet.description, - "temperature": planet.temperature - } + return planet.to_dict(), 200 + + +@planets_bp.route("/", strict_slashes=False, methods=["PUT"]) +def update_planet(planet_id): + planet = validate_planet(planet_id) + request_body = request.get_json() + planet.name = request_body["name"] + planet.description = request_body["description"] + planet.temperature = request_body["temperature"] + db.session.commit() + return make_response(f"Planet #{planet.id} successfully updated", 200) + + +@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 #{planet.id} successfully deleted", 200) From 4c7bae569709a5dd553a4d7897d5bdb3aaede1db Mon Sep 17 00:00:00 2001 From: Jaime Mitchell Date: Wed, 2 Nov 2022 20:42:03 -0400 Subject: [PATCH 14/18] finished wave 5 --- app/models/planet.py | 12 +++--- app/routes.py | 87 +++++++++++++++++++++++++++----------------- 2 files changed, 58 insertions(+), 41 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index a9bc5f035..6f13c618a 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -7,6 +7,10 @@ class Planet(db.Model): # The class Planet inherits from db.Model from SQLAlche description = db.Column(db.String, nullable=False) temperature = db.Column(db.Integer, nullable=False) + @classmethod + def from_dict(cls, data_dict): + return cls(name=data_dict["name"], description=data_dict["description"], temperature=data_dict["temperature"]) + def to_dict(self): return dict( id=self.id, @@ -14,10 +18,4 @@ def to_dict(self): description=self.description, temperature=self.temperature ) - # can also return traditional dictionary: - # return { - # id=self.id, - # name=self.name, - # description=self.description, - # temperature=self.temperature - # } + \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index e38033ceb..a27dadeca 100644 --- a/app/routes.py +++ b/app/routes.py @@ -6,64 +6,83 @@ planets_bp = Blueprint("planets", __name__, url_prefix="/planets") +def validate_model(cls, model_id): + try: + model_id = int(model_id) + except: + abort(make_response( + {"message": f"{cls.__name__} {model_id} invalid"}, 400)) + + planet = cls.query.get(model_id) + + if not planet: + abort(make_response( + {"message": f"{cls.__name__} {model_id} can't be found"}, 404)) + + return planet + + @planets_bp.route("/", strict_slashes=False, methods=["POST"]) def create_planet(): + request_body = request.get_json() - new_planet = Planet( - name=request_body["name"], description=request_body["description"], temperature=request_body["temperature"]) + 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", 200) + + return make_response(f"Planet #{new_planet.name} successfully created", 201) @planets_bp.route("/", strict_slashes=False, methods=["GET"]) def read_all_planets(): - planets = Planet.query.all() - planets_response = [planet.to_dict() for planet in planets] - return jsonify(planets_response) - # for planet in planets: - # planets_response.append({ - # "id": planet.id, - # "name": planet.name, - # "description": planet.description, - # "temperature": planet.temperature - # }) - # NEED JSONIFY FOR LISTS (BUT NOT DICTIONARIES) - - -def validate_planet(planet_id): - try: - planet_id = int(planet_id) - except: - abort(make_response({"message": f"{planet_id} is not valid"}, 400)) + name_query = request.args.get("name") + description_query = request.args.get("description") + temperature_query = request.args.get("temperature") - planet = Planet.query.get(planet_id) + planet_query = Planet.query # like SELECT * from planets - if not planet: - abort(make_response({"message": f"{planet_id} can't be found"}, 404)) - return planet + if name_query: + planet_query = planet_query.filter_by(name=name_query) # ask Isabella + + if description_query: + planet_query = planet_query.filter_by(description=description_query) + + if temperature_query: + planet_query = planet_query.filter_by(temperature=temperature_query) + + planets = planet_query.all() + + planet_response = [planet.to_dict() for planet in planets] + return jsonify(planet_response) -@planets_bp.route("/", strict_slashes=False, methods=["GET"]) -def read_one_planet(planet_id): - planet = validate_planet(planet_id) + +@planets_bp.route("/", strict_slashes=False, methods=["GET"]) +def read_one_planet(id): + + planet = validate_model(Planet, id) return planet.to_dict(), 200 -@planets_bp.route("/", strict_slashes=False, methods=["PUT"]) -def update_planet(planet_id): - planet = validate_planet(planet_id) +@planets_bp.route("/", strict_slashes=False, methods=["PUT"]) +def update_planet(id): + + planet = validate_model(Planet, id) request_body = request.get_json() + planet.name = request_body["name"] planet.description = request_body["description"] planet.temperature = request_body["temperature"] + db.session.commit() return make_response(f"Planet #{planet.id} successfully updated", 200) -@planets_bp.route("/", methods=["DELETE"]) -def delete_planet(planet_id): - planet = validate_planet(planet_id) +@planets_bp.route("/", methods=["DELETE"]) +def delete_planet(id): + + planet = validate_model(Planet, id) db.session.delete(planet) db.session.commit() return make_response(f"Planet #{planet.id} successfully deleted", 200) From 453c76a66a732303ceea2cf000973e34c8c8a5e1 Mon Sep 17 00:00:00 2001 From: Franklyn Rodriguez Date: Thu, 3 Nov 2022 15:26:53 -0400 Subject: [PATCH 15/18] Completed Get all and Get 1 test method --- app/__init__.py | 13 ++++++++++--- tests/__init__.py | 0 tests/conftest.py | 37 +++++++++++++++++++++++++++++++++++++ tests/test_routes.py | 21 +++++++++++++++++++++ 4 files changed, 68 insertions(+), 3 deletions(-) create mode 100644 tests/__init__.py create mode 100644 tests/conftest.py create mode 100644 tests/test_routes.py diff --git a/app/__init__.py b/app/__init__.py index dc1f1f85a..09bb2fd71 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,16 +1,23 @@ 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) 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..dc078bc52 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,37 @@ +import pytest +from app import create_app +from app import db +from flask.signals import request_finished +from app.models.planet import Planet + +@pytest.fixture +def app(): + app = create_app({"TESTING": True}) + + @request_finished.connect_via(app) + def expire_session(sender, response, **extra): + db.session.remove() + + 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() + +@pytest.fixture +def two_saved_planets(app): + # Arrange + ocean_planet = Planet(name="Ocean Planet", description="watr 4evr planet", temperature = 1000) + mountain_planet = Planet(name="Mountain Planet", description="i luv 2 climb rocks planet", temperature = 500) + + db.session.add_all([ocean_planet, mountain_planet]) + # Alternatively, we could do + # db.session.add(ocean_book) + # db.session.add(mountain_book) + db.session.commit() diff --git a/tests/test_routes.py b/tests/test_routes.py new file mode 100644 index 000000000..db0d37c6f --- /dev/null +++ b/tests/test_routes.py @@ -0,0 +1,21 @@ +def test_get_all_planets_with_no_records(client): + # Act + response = client.get("/planets") + response_body = response.get_json() + # Assert + assert response.status_code == 200 + assert response_body == [] + + +def test_get_one_planet(client,two_saved_planets): + # Act + response = client.get("/planets/1") + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert response_body == { + "id": 1, + "name":"Ocean Planet", + "description": "watr 4evr planet", + "temperature" : 1000} From f2ba9c7e585d36c042202541df8a736dc14b5851 Mon Sep 17 00:00:00 2001 From: Jaime Mitchell Date: Thu, 3 Nov 2022 21:03:56 -0400 Subject: [PATCH 16/18] finished wave_6 tests --- app/routes.py | 2 +- tests/test_routes.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index a27dadeca..f9e521ffc 100644 --- a/app/routes.py +++ b/app/routes.py @@ -31,7 +31,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("/", strict_slashes=False, methods=["GET"]) diff --git a/tests/test_routes.py b/tests/test_routes.py index db0d37c6f..e05da4c0f 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -6,6 +6,14 @@ def test_get_all_planets_with_no_records(client): assert response.status_code == 200 assert response_body == [] +def test_get_all_planets(client,two_saved_planets): + # Act + response = client.get("/planets") + response_body = response.get_json() + # Assert + assert response.status_code == 200 + assert len(response_body) == 2 + def test_get_one_planet(client,two_saved_planets): # Act @@ -19,3 +27,25 @@ def test_get_one_planet(client,two_saved_planets): "name":"Ocean Planet", "description": "watr 4evr planet", "temperature" : 1000} + +def test_get_one_planet_no_fixture(client): + # Act + response = client.get("/planets/1") + + # Assert + assert response.status_code == 404 + +def test_create_one_planet(client): + # Act + response = client.post("/planets", json={ + "name":"Ocean Planet", + "description": "watr 4evr planet", + "temperature" : 1000} + ) + response_body = response.get_json() + + # Assert + assert response.status_code == 201 + assert response_body == "Planet Ocean Planet successfully created" + +# def test_update_one_planet \ No newline at end of file From afc25e181c91258c587111ee4f1c7013f22450d9 Mon Sep 17 00:00:00 2001 From: Franklyn Rodriguez Date: Thu, 3 Nov 2022 22:02:03 -0400 Subject: [PATCH 17/18] Wrapping up wave 6 --- app/routes.py | 2 +- tests/test_routes.py | 19 ++++++++++++++++--- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/app/routes.py b/app/routes.py index a27dadeca..f9e521ffc 100644 --- a/app/routes.py +++ b/app/routes.py @@ -31,7 +31,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("/", strict_slashes=False, methods=["GET"]) diff --git a/tests/test_routes.py b/tests/test_routes.py index db0d37c6f..b35fd2376 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -16,6 +16,19 @@ def test_get_one_planet(client,two_saved_planets): assert response.status_code == 200 assert response_body == { "id": 1, - "name":"Ocean Planet", - "description": "watr 4evr planet", - "temperature" : 1000} + "name":"Ocean Planet", + "description": "watr 4evr planet", + "temperature" : 1000} + +def test_create_one_planet(client): + # Act + response = client.post("/books", json={ + "name":"Cheethra Planet", + "description": "snow leopards", + "temperature" : 10 + }) + response_body = response.get_data(as_text=True) + + # Assert + assert response.status_code == 201 + assert response_body == "Planet New Planet successfully created" \ No newline at end of file From c80c7a6c11fa699602049dc5c46c1aad89cb1ca6 Mon Sep 17 00:00:00 2001 From: Franklyn Rodriguez Date: Thu, 3 Nov 2022 23:19:53 -0400 Subject: [PATCH 18/18] Jsonify the methods --- app/routes.py | 4 ++-- tests/test_routes.py | 14 +++++++------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/app/routes.py b/app/routes.py index f9e521ffc..912ffcdae 100644 --- a/app/routes.py +++ b/app/routes.py @@ -76,7 +76,7 @@ def update_planet(id): planet.temperature = request_body["temperature"] db.session.commit() - return make_response(f"Planet #{planet.id} successfully updated", 200) + return make_response(jsonify(f"Planet #{planet.id} successfully updated"), 200) @planets_bp.route("/", methods=["DELETE"]) @@ -85,4 +85,4 @@ def delete_planet(id): planet = validate_model(Planet, id) db.session.delete(planet) db.session.commit() - return make_response(f"Planet #{planet.id} successfully deleted", 200) + return make_response(jsonify(f"Planet #{planet.id} successfully deleted"), 200) diff --git a/tests/test_routes.py b/tests/test_routes.py index 78030c81f..6db66064c 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -7,7 +7,7 @@ def test_get_all_planets_with_no_records(client): assert response_body == [] def test_get_all_planets(client,two_saved_planets): - # Act + # Act response = client.get("/planets") response_body = response.get_json() # Assert @@ -24,9 +24,9 @@ def test_get_one_planet(client,two_saved_planets): assert response.status_code == 200 assert response_body == { "id": 1, - "name":"Ocean Planet", - "description": "watr 4evr planet", - "temperature" : 1000} + "name":"Ocean Planet", + "description": "watr 4evr planet", + "temperature" : 1000} def test_get_one_planet_no_fixture(client): # Act @@ -38,9 +38,9 @@ def test_get_one_planet_no_fixture(client): def test_create_one_planet(client): # Act response = client.post("/planets", json={ - "name":"Ocean Planet", - "description": "watr 4evr planet", - "temperature" : 1000} + "name":"Ocean Planet", + "description": "watr 4evr planet", + "temperature" : 1000} ) response_body = response.get_json()