From eb672109611de1b14fffacf06ea8fa95334a2cb6 Mon Sep 17 00:00:00 2001 From: sana Date: Fri, 22 Apr 2022 21:02:14 +0300 Subject: [PATCH 01/19] add solar project --- app/routes/__init__.py | 0 app/routes/routes.py | 18 ++++++++++++++++++ 2 files changed, 18 insertions(+) create mode 100644 app/routes/__init__.py create mode 100644 app/routes/routes.py diff --git a/app/routes/__init__.py b/app/routes/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/app/routes/routes.py b/app/routes/routes.py new file mode 100644 index 000000000..3483e2667 --- /dev/null +++ b/app/routes/routes.py @@ -0,0 +1,18 @@ +from flask import Blueprint +# Define a Planet class with the attributes id, name, +# and description, and one additional attribute +# Create a list of Planet instances + +class Planet(): + def __init__(self, id, name, description, moons): + self.id = id + self.name = name + self.description = description + self.moons = moons + +planets = [ + Planet( 1, "Mercury", ["red", "hot"], False), + Planet( 2, "Venus", ["orange", "hot"], False), + Planet( 3, "Earth", ["blue", "hot"], True) +] + From eaa5fd0d38ec27e553f93a462aa1804b28b5aaff Mon Sep 17 00:00:00 2001 From: camilla Date: Fri, 22 Apr 2022 11:16:12 -0700 Subject: [PATCH 02/19] complete wave 1 --- app/__init__.py | 5 ++++- app/routes/planet_routes.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 app/routes/planet_routes.py diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..50aecd6b3 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -4,4 +4,7 @@ def create_app(test_config=None): app = Flask(__name__) - return app + from .routes.planet_routes import planet_bp + app.register_blueprint(planet_bp) + + return app \ No newline at end of file diff --git a/app/routes/planet_routes.py b/app/routes/planet_routes.py new file mode 100644 index 000000000..8c816e449 --- /dev/null +++ b/app/routes/planet_routes.py @@ -0,0 +1,30 @@ +from flask import Blueprint, jsonify +# Define a Planet class with the attributes id, name, +# and description, and one additional attribute +# Create a list of Planet instances + +class Planet(): + def __init__(self, id, name, description, moons): + self.id = id + self.name = name + self.description = description + self.moons = moons + +planets = [ + Planet( 1, "Mercury", ["red", "hot"], False), + Planet( 2, "Venus", ["orange", "hot"], False), + Planet( 3, "Earth", ["blue", "hot"], True) +] + +planet_bp = Blueprint("planet", __name__, url_prefix="/planets") + +#Get all planets +@planet_bp.route("", methods=["GET"]) +def read_all_planets(): + planets_response = [] + + for planet in planets: + planets_response.append(planet.to_json()) + + return jsonify(planets_response) + From bd072e323e432f35048f7f560b682dc6ec26abd9 Mon Sep 17 00:00:00 2001 From: camilla Date: Mon, 25 Apr 2022 11:55:30 -0700 Subject: [PATCH 03/19] Wave 1 --- app/routes.py | 2 -- app/routes/routes.py | 18 ------------------ 2 files changed, 20 deletions(-) delete mode 100644 app/routes.py delete mode 100644 app/routes/routes.py diff --git a/app/routes.py b/app/routes.py deleted file mode 100644 index 8e9dfe684..000000000 --- a/app/routes.py +++ /dev/null @@ -1,2 +0,0 @@ -from flask import Blueprint - diff --git a/app/routes/routes.py b/app/routes/routes.py deleted file mode 100644 index 3483e2667..000000000 --- a/app/routes/routes.py +++ /dev/null @@ -1,18 +0,0 @@ -from flask import Blueprint -# Define a Planet class with the attributes id, name, -# and description, and one additional attribute -# Create a list of Planet instances - -class Planet(): - def __init__(self, id, name, description, moons): - self.id = id - self.name = name - self.description = description - self.moons = moons - -planets = [ - Planet( 1, "Mercury", ["red", "hot"], False), - Planet( 2, "Venus", ["orange", "hot"], False), - Planet( 3, "Earth", ["blue", "hot"], True) -] - From 7ab1975778189a1cb0b9a7f5571d510adbf029ea Mon Sep 17 00:00:00 2001 From: camilla Date: Mon, 25 Apr 2022 12:06:10 -0700 Subject: [PATCH 04/19] NEW CHANGES --- app/routes/planet_routes.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/app/routes/planet_routes.py b/app/routes/planet_routes.py index 8c816e449..de4a663c4 100644 --- a/app/routes/planet_routes.py +++ b/app/routes/planet_routes.py @@ -10,16 +10,25 @@ def __init__(self, id, name, description, moons): self.description = description self.moons = moons + def to_json(self): + return { + "id": self.id, + "name": self.name, + "description": self.description, + "moons": self.moons + } + planets = [ Planet( 1, "Mercury", ["red", "hot"], False), Planet( 2, "Venus", ["orange", "hot"], False), Planet( 3, "Earth", ["blue", "hot"], True) ] -planet_bp = Blueprint("planet", __name__, url_prefix="/planets") +planet_bp = Blueprint("planet_bp", __name__) +# planet_bp = Blueprint("planet_bp", __name__, url_prefix="/planets") #Get all planets -@planet_bp.route("", methods=["GET"]) +@planet_bp.route("/planets", methods=["GET"]) def read_all_planets(): planets_response = [] From 8e32e29e47e4478ac4036460ad8593f1cdef85d7 Mon Sep 17 00:00:00 2001 From: camilla Date: Mon, 25 Apr 2022 12:34:19 -0700 Subject: [PATCH 05/19] Completed wave 2 --- app/routes/planet_routes.py | 61 ++++++++++++++++++++++++++++++++----- 1 file changed, 54 insertions(+), 7 deletions(-) diff --git a/app/routes/planet_routes.py b/app/routes/planet_routes.py index de4a663c4..f80292b06 100644 --- a/app/routes/planet_routes.py +++ b/app/routes/planet_routes.py @@ -1,4 +1,4 @@ -from flask import Blueprint, jsonify +from flask import Blueprint, jsonify, make_response, abort # Define a Planet class with the attributes id, name, # and description, and one additional attribute # Create a list of Planet instances @@ -19,16 +19,16 @@ def to_json(self): } planets = [ - Planet( 1, "Mercury", ["red", "hot"], False), - Planet( 2, "Venus", ["orange", "hot"], False), - Planet( 3, "Earth", ["blue", "hot"], True) + Planet(1, "Mercury", ["red", "hot"], False), + Planet(2, "Venus", ["orange", "hot"], False), + Planet(3, "Earth", ["blue", "hot"], True) ] -planet_bp = Blueprint("planet_bp", __name__) -# planet_bp = Blueprint("planet_bp", __name__, url_prefix="/planets") +# planet_bp = Blueprint("planet_bp", __name__) +planet_bp = Blueprint("planet_bp", __name__, url_prefix="/planets") #Get all planets -@planet_bp.route("/planets", methods=["GET"]) +@planet_bp.route("", methods=["GET"]) def read_all_planets(): planets_response = [] @@ -37,3 +37,50 @@ def read_all_planets(): return jsonify(planets_response) +''' +Create the following endpoint(s), with similar functionality +presented in the Hello Books API: + +As a client, I want to send a request... +...to get one existing planet, so that I can see the id, name, description, +and other data of the planet. +... such that trying to get one non-existing planet responds +with get a 404 response, so that I know the planet resource was not found. +... such that trying to get one planet with an invalid planet_id responds +with get a 400 response, so that I know the planet_id was invalid. +''' + +def validate_planet(id): + try: + id = int(id) + except: + return abort(make_response({"message": f"planet {id} is invalid"}, 400)) + + for planet in planets: + if planet.id == id: + return planet + + return abort(make_response({"message": f"planet {id} is not found"}, 404)) + +#Get one planet +@planet_bp.route("/", methods=["GET"]) +def read_one_planet(id): + planet = validate_planet(id) + + return jsonify(planet.to_json(), 200) + + +''' +def validate_cat(id): + try: + id = int(id) + except: + return abort(make_response({"message": f"cat {id} is invalid"}, 400)) + + for cat in cats: + if cat.id == id: + return cat + + return abort(make_response({"message":f"cat {id} not found"}, 404)) + +''' \ No newline at end of file From 101aa0e3e1c8e0b224833db3999ac36860b0211d Mon Sep 17 00:00:00 2001 From: sana Date: Tue, 26 Apr 2022 21:13:04 +0300 Subject: [PATCH 06/19] Add wave 1 and wave 2 --- app/routes/planet_routes.py | 43 +++++++++++++------------------------ 1 file changed, 15 insertions(+), 28 deletions(-) diff --git a/app/routes/planet_routes.py b/app/routes/planet_routes.py index f80292b06..a78c2b347 100644 --- a/app/routes/planet_routes.py +++ b/app/routes/planet_routes.py @@ -1,7 +1,9 @@ from flask import Blueprint, jsonify, make_response, abort -# Define a Planet class with the attributes id, name, -# and description, and one additional attribute -# Create a list of Planet instances +''' +Defined a Planet class with the attributes id, name, +and description, and moons. Also, Created a list of Planet instances. +''' + class Planet(): def __init__(self, id, name, description, moons): @@ -19,12 +21,16 @@ def to_json(self): } planets = [ - Planet(1, "Mercury", ["red", "hot"], False), - Planet(2, "Venus", ["orange", "hot"], False), - Planet(3, "Earth", ["blue", "hot"], True) + Planet(1, "Mercury", ["Grey", "closest to the sun", "smallest planet"], False), + Planet(2, "Venus", ["Brown and grey", "hottest planet"], False), + Planet(3, "Earth", ["Blue, brown green and white", "water world","1 moon"], True), + Planet(4, "Mars", ["Red, brown and tan", "2 moons"], True), + Planet(5, "Jupiter", ["Brown, orange and tan, with white cloud stripes","largest planet", "79 moons"], True), + Planet(6, "Saturn", ["Golden, brown, and blue-grey"," large and distinct ring system" ,"82 moons"], True), + Planet(7, "Uranus", ["Blue-green", " holds the record for the coldest temperature ever measured in the solar system ","27 moons"], True), + Planet(8, "Neptune", ["Blue"," on average the coldest planet" ,"14 moons"], True) ] -# planet_bp = Blueprint("planet_bp", __name__) planet_bp = Blueprint("planet_bp", __name__, url_prefix="/planets") #Get all planets @@ -38,10 +44,7 @@ def read_all_planets(): return jsonify(planets_response) ''' -Create the following endpoint(s), with similar functionality -presented in the Hello Books API: - -As a client, I want to send a request... +Created the following endpoint(s). This API can handle requests such as the following: ...to get one existing planet, so that I can see the id, name, description, and other data of the planet. ... such that trying to get one non-existing planet responds @@ -67,20 +70,4 @@ def validate_planet(id): def read_one_planet(id): planet = validate_planet(id) - return jsonify(planet.to_json(), 200) - - -''' -def validate_cat(id): - try: - id = int(id) - except: - return abort(make_response({"message": f"cat {id} is invalid"}, 400)) - - for cat in cats: - if cat.id == id: - return cat - - return abort(make_response({"message":f"cat {id} not found"}, 404)) - -''' \ No newline at end of file + return jsonify(planet.to_json(), 200) \ No newline at end of file From 6c98125994c8aae93988c328cbdffff3614bd93b Mon Sep 17 00:00:00 2001 From: camilla Date: Fri, 29 Apr 2022 11:56:28 -0700 Subject: [PATCH 07/19] Added changes --- app/__init__.py | 13 +++++++ app/routes/planet_routes.py | 71 +++++++++++++++++++++++-------------- 2 files changed, 58 insertions(+), 26 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 50aecd6b3..39c61f632 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,9 +1,22 @@ from flask import Flask +from flask_sqlalchemy import SQLAlchemy +from flask_migrate import Migrate +db = SQLAlchemy() +migrate = Migrate() def create_app(test_config=None): + # __name__ stores the name of the module we're in 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.planet_routes import planet_bp app.register_blueprint(planet_bp) diff --git a/app/routes/planet_routes.py b/app/routes/planet_routes.py index a78c2b347..803deccaa 100644 --- a/app/routes/planet_routes.py +++ b/app/routes/planet_routes.py @@ -1,38 +1,57 @@ -from flask import Blueprint, jsonify, make_response, abort +from flask import Blueprint, jsonify, make_response, abort, request +from app.models.planet import Planet +from app import db + ''' Defined a Planet class with the attributes id, name, and description, and moons. Also, Created a list of Planet instances. ''' +# class Planet(): +# def __init__(self, id, name, description, moons): +# self.id = id +# self.name = name +# self.description = description +# self.moons = moons + +# def to_json(self): +# return { +# "id": self.id, +# "name": self.name, +# "description": self.description, +# "moons": self.moons +# } -class Planet(): - def __init__(self, id, name, description, moons): - self.id = id - self.name = name - self.description = description - self.moons = moons - - def to_json(self): - return { - "id": self.id, - "name": self.name, - "description": self.description, - "moons": self.moons - } - -planets = [ - Planet(1, "Mercury", ["Grey", "closest to the sun", "smallest planet"], False), - Planet(2, "Venus", ["Brown and grey", "hottest planet"], False), - Planet(3, "Earth", ["Blue, brown green and white", "water world","1 moon"], True), - Planet(4, "Mars", ["Red, brown and tan", "2 moons"], True), - Planet(5, "Jupiter", ["Brown, orange and tan, with white cloud stripes","largest planet", "79 moons"], True), - Planet(6, "Saturn", ["Golden, brown, and blue-grey"," large and distinct ring system" ,"82 moons"], True), - Planet(7, "Uranus", ["Blue-green", " holds the record for the coldest temperature ever measured in the solar system ","27 moons"], True), - Planet(8, "Neptune", ["Blue"," on average the coldest planet" ,"14 moons"], True) -] +# planets = [ +# Planet(1, "Mercury", ["Grey", "closest to the sun", "smallest planet"], False), +# Planet(2, "Venus", ["Brown and grey", "hottest planet"], False), +# Planet(3, "Earth", ["Blue, brown green and white", "water world","1 moon"], True), +# Planet(4, "Mars", ["Red, brown and tan", "2 moons"], True), +# Planet(5, "Jupiter", ["Brown, orange and tan, with white cloud stripes","largest planet", "79 moons"], True), +# Planet(6, "Saturn", ["Golden, brown, and blue-grey"," large and distinct ring system" ,"82 moons"], True), +# Planet(7, "Uranus", ["Blue-green", " holds the record for the coldest temperature ever measured in the solar system ","27 moons"], True), +# Planet(8, "Neptune", ["Blue"," on average the coldest planet" ,"14 moons"], True) +# ] planet_bp = Blueprint("planet_bp", __name__, url_prefix="/planets") +#CREATE PLANET +@planet_bp.route("", methods=["POST"]) +def create_planet(): + request_body = request.get_json() + + 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} has been successfully created!", 201) + + #Get all planets @planet_bp.route("", methods=["GET"]) def read_all_planets(): From 651bb49d6a8e92d37d2ef74d31dbbad4dcd2cda7 Mon Sep 17 00:00:00 2001 From: sana Date: Tue, 3 May 2022 20:42:28 +0300 Subject: [PATCH 08/19] add new migration for boolean --- migrations/README | 1 + migrations/alembic.ini | 45 +++++++++ migrations/env.py | 96 +++++++++++++++++++ migrations/script.py.mako | 24 +++++ .../versions/1b989253add6_add_boolean.py | 28 ++++++ .../8478c5f52267_adds_planetk_model.py | 33 +++++++ 6 files changed, 227 insertions(+) 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/1b989253add6_add_boolean.py create mode 100644 migrations/versions/8478c5f52267_adds_planetk_model.py 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/1b989253add6_add_boolean.py b/migrations/versions/1b989253add6_add_boolean.py new file mode 100644 index 000000000..e3ca2ec9b --- /dev/null +++ b/migrations/versions/1b989253add6_add_boolean.py @@ -0,0 +1,28 @@ +"""add boolean + +Revision ID: 1b989253add6 +Revises: 8478c5f52267 +Create Date: 2022-05-03 20:40:51.676253 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '1b989253add6' +down_revision = '8478c5f52267' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('planet', sa.Column('moons', sa.Boolean(), nullable=True)) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_column('planet', 'moons') + # ### end Alembic commands ### diff --git a/migrations/versions/8478c5f52267_adds_planetk_model.py b/migrations/versions/8478c5f52267_adds_planetk_model.py new file mode 100644 index 000000000..32fd19eba --- /dev/null +++ b/migrations/versions/8478c5f52267_adds_planetk_model.py @@ -0,0 +1,33 @@ +"""adds Planetk model + +Revision ID: 8478c5f52267 +Revises: +Create Date: 2022-05-03 19:05:46.484035 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '8478c5f52267' +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.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('planet') + # ### end Alembic commands ### From 059841712e27228c969b00630b151f9eba0d2c0b Mon Sep 17 00:00:00 2001 From: sana Date: Tue, 3 May 2022 21:03:22 +0300 Subject: [PATCH 09/19] add routes --- app/__init__.py | 3 +-- app/routes/planet_routes.py | 27 +++++++++++++++++---------- 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 39c61f632..9202f0c24 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -8,14 +8,13 @@ def create_app(test_config=None): # __name__ stores the name of the module we're in app = Flask(__name__) - + from app.models.planet import Planet #? 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.planet_routes import planet_bp app.register_blueprint(planet_bp) diff --git a/app/routes/planet_routes.py b/app/routes/planet_routes.py index 803deccaa..d4c84d64a 100644 --- a/app/routes/planet_routes.py +++ b/app/routes/planet_routes.py @@ -36,29 +36,36 @@ planet_bp = Blueprint("planet_bp", __name__, url_prefix="/planets") #CREATE PLANET + +# Create planet @planet_bp.route("", methods=["POST"]) def create_planet(): request_body = request.get_json() - - Planet( - name=request_body['name'], - # description=request_body['description'], - moons=request_body['moons'], - ) + new_planet = Planet(title=request_body["title"], + description=request_body["description"], + moons = request_body["moons"] + ) db.session.add(new_planet) db.session.commit() - return make_response(f"Planet {new_planet.name} has been successfully created!", 201) - + return make_response(f"Planet {new_planet.title} successfully created", 201) #Get all planets @planet_bp.route("", methods=["GET"]) def read_all_planets(): planets_response = [] - + planets = Planet.query.all() for planet in planets: - planets_response.append(planet.to_json()) + #planets_response.append(planet.to_json()) + planets_response.append( + { + "id": planet.id, + "title": planet.title, + "description": planet.description, + "moons": planet.moons + } + ) return jsonify(planets_response) From fde39b3b825fff541767a2a9c41c57271cd19ba1 Mon Sep 17 00:00:00 2001 From: sana Date: Tue, 3 May 2022 21:10:13 +0300 Subject: [PATCH 10/19] add everything --- app/models/__init__.py | 0 app/models/planet.py | 17 ++++++++++ migrations/versions/aaa15afb4525_added.py | 38 +++++++++++++++++++++++ 3 files changed, 55 insertions(+) create mode 100644 app/models/__init__.py create mode 100644 app/models/planet.py create mode 100644 migrations/versions/aaa15afb4525_added.py diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/app/models/planet.py b/app/models/planet.py new file mode 100644 index 000000000..799c1d91a --- /dev/null +++ b/app/models/planet.py @@ -0,0 +1,17 @@ +from app import db + + +class Planet(db.Model): + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + title = db.Column(db.String, nullable=False) + description = db.Column(db.String) + moons = db.Column(db.Boolean, nullable=False) + + + def to_json(self): + return { + "id": self.id, + "title": self.title, + "description": self.description, + "moons": self.moons + } diff --git a/migrations/versions/aaa15afb4525_added.py b/migrations/versions/aaa15afb4525_added.py new file mode 100644 index 000000000..cc6711fa0 --- /dev/null +++ b/migrations/versions/aaa15afb4525_added.py @@ -0,0 +1,38 @@ +"""added + +Revision ID: aaa15afb4525 +Revises: 1b989253add6 +Create Date: 2022-05-03 21:05:12.563656 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'aaa15afb4525' +down_revision = '1b989253add6' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.alter_column('planet', 'moons', + existing_type=sa.BOOLEAN(), + nullable=False) + op.alter_column('planet', 'title', + existing_type=sa.VARCHAR(), + nullable=False) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.alter_column('planet', 'title', + existing_type=sa.VARCHAR(), + nullable=True) + op.alter_column('planet', 'moons', + existing_type=sa.BOOLEAN(), + nullable=True) + # ### end Alembic commands ### From 4d63fbc32488765b0a61981968230e6f1955e28c Mon Sep 17 00:00:00 2001 From: sana Date: Tue, 3 May 2022 21:53:36 +0300 Subject: [PATCH 11/19] add 04) --- app/routes/planet_routes.py | 43 ++++++++++++++++++++++++++++++------- 1 file changed, 35 insertions(+), 8 deletions(-) diff --git a/app/routes/planet_routes.py b/app/routes/planet_routes.py index d4c84d64a..8650e5e64 100644 --- a/app/routes/planet_routes.py +++ b/app/routes/planet_routes.py @@ -56,6 +56,8 @@ def create_planet(): def read_all_planets(): planets_response = [] planets = Planet.query.all() + #make_response.append(planet.to_json()) + for planet in planets: #planets_response.append(planet.to_json()) planets_response.append( @@ -84,16 +86,41 @@ def validate_planet(id): id = int(id) except: return abort(make_response({"message": f"planet {id} is invalid"}, 400)) - - for planet in planets: - if planet.id == id: - return planet - - return abort(make_response({"message": f"planet {id} is not found"}, 404)) - + planet= Planet.query.get(id) + + # for planet in planets: + if not planet: + return abort(make_response({"message": f"planet {id} is not found"}, 404)) + return planet + + #Get one planet @planet_bp.route("/", methods=["GET"]) def read_one_planet(id): planet = validate_planet(id) - return jsonify(planet.to_json(), 200) \ No newline at end of file + return jsonify(planet.to_json(), 200) + + +# UPDATE ONE planet +@planet_bp.route("/", methods = ["PUT"]) +def update_one_planet(id): + planet = validate_planet(id) + request_body = request.get_json() # would get response body we put int + + planet.title = request_body["title"] + planet.description = request_body["description"] + planet.moons = request_body["moons"] + + db.session.commit() + return make_response(f"Planet # {planet.id} successfully updated"), 200 + +# DELETE ONE Planet +@planet_bp.route("/", methods = ["DELETE"]) +def delete_one_planet(id): + planet = validate_planet(id) + + db.session.delete(planet) + db.session.commit() + + return make_response(f"Planet # {planet.id} successfully deleted"), 200 \ No newline at end of file From c98e2619e16b41047c134d06f206f9251e74cc1e Mon Sep 17 00:00:00 2001 From: sana Date: Wed, 4 May 2022 21:06:31 +0300 Subject: [PATCH 12/19] add wave 5 --- app/models/planet.py | 15 +++++++++++++ app/routes/helpers.py | 14 +++++++++++++ app/routes/planet_routes.py | 42 +++++++++++++++++++++---------------- 3 files changed, 53 insertions(+), 18 deletions(-) create mode 100644 app/routes/helpers.py diff --git a/app/models/planet.py b/app/models/planet.py index 799c1d91a..c18ff8e1b 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -15,3 +15,18 @@ def to_json(self): "description": self.description, "moons": self.moons } + + def update(self, request_body): + self.title = request_body["title"] + self.description = request_body["description"] + self.moons = request_body["moons"] + + + @classmethod + def create(cls,request_body): + new_planet = cls( + title=request_body["title"], + description=request_body["description"], + moons = request_body["moons"] + ) + return new_planet diff --git a/app/routes/helpers.py b/app/routes/helpers.py new file mode 100644 index 000000000..9c721ffab --- /dev/null +++ b/app/routes/helpers.py @@ -0,0 +1,14 @@ +# from flask import Blueprint, jsonify, make_response, abort, request +# from app.models.planet import Planet + +def validate_planet(id): + try: + id = int(id) + except: + return abort(make_response({"message": f"planet {id} is invalid"}, 400)) + planet= Planet.query.get(id) + + # for planet in planets: + if not planet: + return abort(make_response({"message": f"planet {id} is not found"}, 404)) + return planet diff --git a/app/routes/planet_routes.py b/app/routes/planet_routes.py index 8650e5e64..0e77c3179 100644 --- a/app/routes/planet_routes.py +++ b/app/routes/planet_routes.py @@ -1,6 +1,7 @@ from flask import Blueprint, jsonify, make_response, abort, request from app.models.planet import Planet from app import db +from .helpers import validate_planet ''' Defined a Planet class with the attributes id, name, @@ -41,10 +42,7 @@ @planet_bp.route("", methods=["POST"]) def create_planet(): request_body = request.get_json() - new_planet = Planet(title=request_body["title"], - description=request_body["description"], - moons = request_body["moons"] - ) + new_planet = Planet.create(request_body) db.session.add(new_planet) db.session.commit() @@ -54,8 +52,13 @@ def create_planet(): #Get all planets @planet_bp.route("", methods=["GET"]) def read_all_planets(): + title_query = request.args.get("title") + if title_query: + planets = Planet.query.filter_by(title=title_query) + else: + planets = Planet.query.all() + planets_response = [] - planets = Planet.query.all() #make_response.append(planet.to_json()) for planet in planets: @@ -71,6 +74,8 @@ def read_all_planets(): return jsonify(planets_response) + + ''' Created the following endpoint(s). This API can handle requests such as the following: ...to get one existing planet, so that I can see the id, name, description, @@ -81,17 +86,17 @@ def read_all_planets(): with get a 400 response, so that I know the planet_id was invalid. ''' -def validate_planet(id): - try: - id = int(id) - except: - return abort(make_response({"message": f"planet {id} is invalid"}, 400)) - planet= Planet.query.get(id) +# def validate_planet(id): +# try: +# id = int(id) +# except: +# return abort(make_response({"message": f"planet {id} is invalid"}, 400)) +# planet= Planet.query.get(id) - # for planet in planets: - if not planet: - return abort(make_response({"message": f"planet {id} is not found"}, 404)) - return planet +# # for planet in planets: +# if not planet: +# return abort(make_response({"message": f"planet {id} is not found"}, 404)) +# return planet #Get one planet @@ -108,9 +113,10 @@ def update_one_planet(id): planet = validate_planet(id) request_body = request.get_json() # would get response body we put int - planet.title = request_body["title"] - planet.description = request_body["description"] - planet.moons = request_body["moons"] + planet.update(request_body) + # planet.title = request_body["title"] + # planet.description = request_body["description"] + # planet.moons = request_body["moons"] db.session.commit() return make_response(f"Planet # {planet.id} successfully updated"), 200 From 7cf65b31f5c48296130bf8f3f4afa1f8c7fc238e Mon Sep 17 00:00:00 2001 From: sana Date: Wed, 4 May 2022 21:25:21 +0300 Subject: [PATCH 13/19] add wave 5 refactored --- app/__init__.py | 4 +- app/models/planet.py | 7 +++- app/routes/helpers.py | 2 +- app/routes/planet_routes.py | 77 +++++-------------------------------- 4 files changed, 17 insertions(+), 73 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 9202f0c24..06ef390e2 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -6,16 +6,14 @@ migrate = Migrate() def create_app(test_config=None): - # __name__ stores the name of the module we're in app = Flask(__name__) - from app.models.planet import Planet #? + from app.models.planet import Planet 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 .routes.planet_routes import planet_bp app.register_blueprint(planet_bp) diff --git a/app/models/planet.py b/app/models/planet.py index c18ff8e1b..ee24e0f1d 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -1,5 +1,10 @@ from app import db +''' +Defined a Planet model with the attributes id, title, +and description, and moons. Created instance method, update, to update our model. +Class method, create, to create a new instance of planet. +''' class Planet(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) @@ -7,7 +12,6 @@ class Planet(db.Model): description = db.Column(db.String) moons = db.Column(db.Boolean, nullable=False) - def to_json(self): return { "id": self.id, @@ -21,7 +25,6 @@ def update(self, request_body): self.description = request_body["description"] self.moons = request_body["moons"] - @classmethod def create(cls,request_body): new_planet = cls( diff --git a/app/routes/helpers.py b/app/routes/helpers.py index 9c721ffab..0dbf679aa 100644 --- a/app/routes/helpers.py +++ b/app/routes/helpers.py @@ -8,7 +8,7 @@ def validate_planet(id): return abort(make_response({"message": f"planet {id} is invalid"}, 400)) planet= Planet.query.get(id) - # for planet in planets: if not planet: return abort(make_response({"message": f"planet {id} is not found"}, 404)) + return planet diff --git a/app/routes/planet_routes.py b/app/routes/planet_routes.py index 0e77c3179..48e6d6c7b 100644 --- a/app/routes/planet_routes.py +++ b/app/routes/planet_routes.py @@ -3,42 +3,9 @@ from app import db from .helpers import validate_planet -''' -Defined a Planet class with the attributes id, name, -and description, and moons. Also, Created a list of Planet instances. -''' - -# class Planet(): -# def __init__(self, id, name, description, moons): -# self.id = id -# self.name = name -# self.description = description -# self.moons = moons - -# def to_json(self): -# return { -# "id": self.id, -# "name": self.name, -# "description": self.description, -# "moons": self.moons -# } - -# planets = [ -# Planet(1, "Mercury", ["Grey", "closest to the sun", "smallest planet"], False), -# Planet(2, "Venus", ["Brown and grey", "hottest planet"], False), -# Planet(3, "Earth", ["Blue, brown green and white", "water world","1 moon"], True), -# Planet(4, "Mars", ["Red, brown and tan", "2 moons"], True), -# Planet(5, "Jupiter", ["Brown, orange and tan, with white cloud stripes","largest planet", "79 moons"], True), -# Planet(6, "Saturn", ["Golden, brown, and blue-grey"," large and distinct ring system" ,"82 moons"], True), -# Planet(7, "Uranus", ["Blue-green", " holds the record for the coldest temperature ever measured in the solar system ","27 moons"], True), -# Planet(8, "Neptune", ["Blue"," on average the coldest planet" ,"14 moons"], True) -# ] - planet_bp = Blueprint("planet_bp", __name__, url_prefix="/planets") -#CREATE PLANET - -# Create planet +#Create planet @planet_bp.route("", methods=["POST"]) def create_planet(): request_body = request.get_json() @@ -59,10 +26,8 @@ def read_all_planets(): planets = Planet.query.all() planets_response = [] - #make_response.append(planet.to_json()) for planet in planets: - #planets_response.append(planet.to_json()) planets_response.append( { "id": planet.id, @@ -74,31 +39,15 @@ def read_all_planets(): return jsonify(planets_response) - - ''' Created the following endpoint(s). This API can handle requests such as the following: -...to get one existing planet, so that I can see the id, name, description, -and other data of the planet. -... such that trying to get one non-existing planet responds -with get a 404 response, so that I know the planet resource was not found. -... such that trying to get one planet with an invalid planet_id responds -with get a 400 response, so that I know the planet_id was invalid. + - to get one existing planet, so that I can see the id, name, description, and other data of the planet. + - such that trying to get one non-existing planet responds + with get a 404 response, so that I know the planet resource was not found. + - such that trying to get one planet with an invalid planet_id responds + with get a 400 response, so that I know the planet_id was invalid. ''' -# def validate_planet(id): -# try: -# id = int(id) -# except: -# return abort(make_response({"message": f"planet {id} is invalid"}, 400)) -# planet= Planet.query.get(id) - -# # for planet in planets: -# if not planet: -# return abort(make_response({"message": f"planet {id} is not found"}, 404)) -# return planet - - #Get one planet @planet_bp.route("/", methods=["GET"]) def read_one_planet(id): @@ -106,26 +55,20 @@ def read_one_planet(id): return jsonify(planet.to_json(), 200) - -# UPDATE ONE planet +#Update one planet @planet_bp.route("/", methods = ["PUT"]) def update_one_planet(id): planet = validate_planet(id) - request_body = request.get_json() # would get response body we put int - + request_body = request.get_json() planet.update(request_body) - # planet.title = request_body["title"] - # planet.description = request_body["description"] - # planet.moons = request_body["moons"] + db.session.commit() - db.session.commit() return make_response(f"Planet # {planet.id} successfully updated"), 200 -# DELETE ONE Planet +#Delete one planet @planet_bp.route("/", methods = ["DELETE"]) def delete_one_planet(id): planet = validate_planet(id) - db.session.delete(planet) db.session.commit() From a6aeaafb029b27476d080ad08bacf8d9f6a10776 Mon Sep 17 00:00:00 2001 From: camilla Date: Thu, 5 May 2022 11:20:37 -0700 Subject: [PATCH 14/19] Create testing routes, configurations --- app/__init__.py | 12 +++++++++++- app/tests/__init__.py | 0 app/tests/conftest.py | 23 +++++++++++++++++++++++ app/tests/test_routes.py | 8 ++++++++ 4 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 app/tests/__init__.py create mode 100644 app/tests/conftest.py create mode 100644 app/tests/test_routes.py diff --git a/app/__init__.py b/app/__init__.py index 06ef390e2..4fe593018 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,15 +1,25 @@ from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate +from dotenv import load_dotenv +import os + db = SQLAlchemy() migrate = Migrate() +load_dotenv() def create_app(test_config=None): app = Flask(__name__) from app.models.planet import Planet 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_TEST_DATABASE_URI'] = os.environ.get("SQLALCHEMY_TEST_DATABASE_URI") + else: + app.config["TESTING"] = True + app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( "SQLALCHEMY_TEST_DATABASE_URI") + db.init_app(app) migrate.init_app(app, db) diff --git a/app/tests/__init__.py b/app/tests/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/app/tests/conftest.py b/app/tests/conftest.py new file mode 100644 index 000000000..cdefdc6ff --- /dev/null +++ b/app/tests/conftest.py @@ -0,0 +1,23 @@ +import pytest +from app import create_app +from app import db +from flask.signals import request_finished + +@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() \ No newline at end of file diff --git a/app/tests/test_routes.py b/app/tests/test_routes.py new file mode 100644 index 000000000..4fd55c2ea --- /dev/null +++ b/app/tests/test_routes.py @@ -0,0 +1,8 @@ +#Create a test to check GET /planets returns 200 and an empty array. + +def test_get_all_planets_with_no_records(client): + response = client.get("/planets") + response_body = response.get_json() + assert response.status_code == 200 + assert response_body == [] + From e1c2d9d6664439746829d5c69fef881a34699ae2 Mon Sep 17 00:00:00 2001 From: camilla Date: Thu, 5 May 2022 11:48:51 -0700 Subject: [PATCH 15/19] Fix bug --- app/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index 4fe593018..c05bb3b7e 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -15,7 +15,7 @@ def create_app(test_config=None): app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False if not test_config: - app.config['SQLALCHEMY_TEST_DATABASE_URI'] = os.environ.get("SQLALCHEMY_TEST_DATABASE_URI") + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("SQLALCHEMY_DATABASE_URI") else: app.config["TESTING"] = True app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( "SQLALCHEMY_TEST_DATABASE_URI") From c419281965fd4fb3c8b4e1a296a1d1bdb4c3eb4e Mon Sep 17 00:00:00 2001 From: camilla Date: Thu, 5 May 2022 12:59:18 -0700 Subject: [PATCH 16/19] create fixtures and tests --- app/routes/helpers.py | 6 +-- app/tests/conftest.py | 13 +++++- app/tests/test_routes.py | 99 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 114 insertions(+), 4 deletions(-) diff --git a/app/routes/helpers.py b/app/routes/helpers.py index 0dbf679aa..23c28ab90 100644 --- a/app/routes/helpers.py +++ b/app/routes/helpers.py @@ -1,5 +1,5 @@ -# from flask import Blueprint, jsonify, make_response, abort, request -# from app.models.planet import Planet +from flask import Blueprint, jsonify, make_response, abort, request +from app.models.planet import Planet def validate_planet(id): try: @@ -7,7 +7,7 @@ def validate_planet(id): except: return abort(make_response({"message": f"planet {id} is invalid"}, 400)) planet= Planet.query.get(id) - + if not planet: return abort(make_response({"message": f"planet {id} is not found"}, 404)) diff --git a/app/tests/conftest.py b/app/tests/conftest.py index cdefdc6ff..6b3df4ae7 100644 --- a/app/tests/conftest.py +++ b/app/tests/conftest.py @@ -2,6 +2,8 @@ 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(): @@ -20,4 +22,13 @@ def expire_session(sender, response, **extra): @pytest.fixture def client(app): - return app.test_client() \ No newline at end of file + return app.test_client() + +@pytest.fixture +def two_saved_planets(app): + mercury_planet = Planet(title="Mercury", description="Best planet, grey", moons=False) + venus_planet = Planet(title="Venus", description="Hottest planet", moons=False) + + db.session.add_all([mercury_planet, venus_planet]) + db.session.commit() + diff --git a/app/tests/test_routes.py b/app/tests/test_routes.py index 4fd55c2ea..a110d0aae 100644 --- a/app/tests/test_routes.py +++ b/app/tests/test_routes.py @@ -1,8 +1,107 @@ #Create a test to check GET /planets returns 200 and an empty array. 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 == [] +''' +Create test fixtures and unit tests for the following test cases: + +GET /planets/1 returns a response body that matches our fixture DONE +GET /planets/1 with no data in test database (no fixture) returns a 404 DONE +GET /planets with valid test data (fixtures) returns a 200 with an array including appropriate test data +POST /planets with a JSON request body returns a 201 +''' +def test_get_one_planet_that_matches_our_fixture(client, two_saved_planets): + #Act + response = client.get("/planets/1") + response_body = response.get_json() + + #Assert + assert response.status_code == 200 + assert response_body == { + "title": "Mercury", + "description": "Best planet, grey", + "moons": False + } + +# def test_get_one_planet_with_no_records(client): +# #Act +# response = client.get("/planets/1") +# response_body = response.get_json() + +# #Assert +# assert response.status_code == 404 +# assert response_body == {} + +# def test_get_all_planets_matching_our_fixture(client): +# #Act +# response = client.get("/planets") +# response_body = response.get_json() + +# #Assert +# assert response.status_code == 200 +# assert response_body == [ +# { +# "description": "Grey, closest to the sun, smallest planet", +# "id": 1, +# "moons": false, +# "title": "Mercury" +# }, +# { +# "description": "Brown and grey, hottest planet", +# "id": 2, +# "moons": false, +# "title": "Venus" +# }, +# { +# "description": "Blue, brown green and white, water world, 1 moon", +# "id": 3, +# "moons": true, +# "title": "Earth" +# }, +# { +# "description": "Red, brown and tan, 2 moons", +# "id": 4, +# "moons": true, +# "title": "Mars" +# }, +# { +# "description": "Brown, orange and tan, with white cloud stripes, largest planet, 79 moons", +# "id": 5, +# "moons": true, +# "title": "Jupiter" +# }, +# { +# "description": "Golden, brown, and blue-grey, large and distinct ring system, 82 moons", +# "id": 6, +# "moons": true, +# "title": "Saturn" +# }, +# { +# "description": "Blue-green, holds the record for the coldest temperature ever measured in the solar system, 27 moons", +# "id": 7, +# "moons": true, +# "title": "Uranus" +# }, +# { +# "description": "Blue, on average the coldest planet, 14 moons", +# "id": 8, +# "moons": true, +# "title": "Neptune" +# } +# ] + +# def test_post_first_planet(client): +# response = client.post("/planets", json={ +# "title": "Mercury", +# "description": "NICE PLANET!!!!!", +# "moons": false}) +# response_body = response.get_json() +# assert response.statuscode == 201 +# assert response_body == "Planet Mercury has been successfully created!" From 20d75b68493860de4e126c8cb5c409a0f58b90a7 Mon Sep 17 00:00:00 2001 From: camilla Date: Thu, 5 May 2022 15:20:38 -0700 Subject: [PATCH 17/19] Pass all tests --- app/routes/planet_routes.py | 4 +- app/tests/conftest.py | 13 ++++ app/tests/test_routes.py | 136 ++++++++++++++++-------------------- 3 files changed, 74 insertions(+), 79 deletions(-) diff --git a/app/routes/planet_routes.py b/app/routes/planet_routes.py index 48e6d6c7b..785b1a777 100644 --- a/app/routes/planet_routes.py +++ b/app/routes/planet_routes.py @@ -24,7 +24,7 @@ def read_all_planets(): planets = Planet.query.filter_by(title=title_query) else: planets = Planet.query.all() - + planets_response = [] for planet in planets: @@ -63,7 +63,7 @@ def update_one_planet(id): planet.update(request_body) db.session.commit() - return make_response(f"Planet # {planet.id} successfully updated"), 200 + return make_response(jsonify(f"Planet # {planet.id} successfully updated"), 200) #Delete one planet @planet_bp.route("/", methods = ["DELETE"]) diff --git a/app/tests/conftest.py b/app/tests/conftest.py index 6b3df4ae7..826601d78 100644 --- a/app/tests/conftest.py +++ b/app/tests/conftest.py @@ -32,3 +32,16 @@ def two_saved_planets(app): db.session.add_all([mercury_planet, venus_planet]) db.session.commit() +@pytest.fixture +def all_planets(app): + mercury_planet = Planet(title="Mercury", description="Best planet, grey", moons=False) + venus_planet = Planet(title="Venus", description="Hottest planet", moons=False) + earth_planet = Planet(title="Earth", description="Our planet", moons=True) + mars_planet = Planet(title="Mars", description="There's a Rover", moons=True) + jupiter_planet = Planet(title="Jupiter", description="Big", moons=True) + saturn_planet = Planet(title="Saturn", description="Has a ring", moons=True) + uranus_planet = Planet(title="Uranus", description="Far away", moons=True) + neptune_planet = Planet(title="Neptune", description="So lonely", moons=True) + + db.session.add_all([mercury_planet, venus_planet, earth_planet, mars_planet, jupiter_planet, saturn_planet, uranus_planet, neptune_planet]) + db.session.commit() diff --git a/app/tests/test_routes.py b/app/tests/test_routes.py index a110d0aae..d732022ca 100644 --- a/app/tests/test_routes.py +++ b/app/tests/test_routes.py @@ -1,4 +1,4 @@ -#Create a test to check GET /planets returns 200 and an empty array. +from flask import jsonify, make_response def test_get_all_planets_with_no_records(client): #Act @@ -24,84 +24,66 @@ def test_get_one_planet_that_matches_our_fixture(client, two_saved_planets): #Assert assert response.status_code == 200 - assert response_body == { - "title": "Mercury", - "description": "Best planet, grey", - "moons": False - } + assert response_body[0] == {"title": "Mercury", "id": 1, "moons": False, "description": "Best planet, grey"} -# def test_get_one_planet_with_no_records(client): -# #Act -# response = client.get("/planets/1") -# response_body = response.get_json() -# #Assert -# assert response.status_code == 404 -# assert response_body == {} +def test_get_one_planet_with_no_records(client): + #Act + response = client.get("/planets/1") + response_body = response.get_json() -# def test_get_all_planets_matching_our_fixture(client): -# #Act -# response = client.get("/planets") -# response_body = response.get_json() + #Assert + assert response.status_code == 404 + assert response_body == {'message': 'planet 1 is not found'} + +def test_get_all_planets_matching_our_fixture(client, all_planets): + #Act + response = client.get("/planets") + response_body = response.get_json() + + #Assert + assert response.status_code == 200 + assert response_body == [ + {"title": "Mercury", + "id": 1, + "moons": False, + "description": "Best planet, grey"}, + {"title": "Venus", + "id": 2, + "moons": False, + "description": "Hottest planet"}, + {"title": "Earth", + "id": 3, + "moons": True, + "description": "Our planet"}, + {"title": "Mars", + "id": 4, + "moons": True, + "description": "There's a Rover"}, + {"title": "Jupiter", + "id": 5, + "moons": True, + "description": "Big"}, + {"title": "Saturn", + "id": 6, + "moons": True, + "description": "Has a ring"}, + {"title": "Uranus", + "id": 7, + "moons": True, + "description": "Far away"}, + {"title": "Neptune", + "id": 8, + "moons": True, + "description": "So lonely"} + ] + +def test_post_first_planet(client): + response = client.post("/planets", json={ + "title": "Mercury", + "description": "NICE PLANET!!!!!", + "moons": False}) + response_body = response.get_json() -# #Assert -# assert response.status_code == 200 -# assert response_body == [ -# { -# "description": "Grey, closest to the sun, smallest planet", -# "id": 1, -# "moons": false, -# "title": "Mercury" -# }, -# { -# "description": "Brown and grey, hottest planet", -# "id": 2, -# "moons": false, -# "title": "Venus" -# }, -# { -# "description": "Blue, brown green and white, water world, 1 moon", -# "id": 3, -# "moons": true, -# "title": "Earth" -# }, -# { -# "description": "Red, brown and tan, 2 moons", -# "id": 4, -# "moons": true, -# "title": "Mars" -# }, -# { -# "description": "Brown, orange and tan, with white cloud stripes, largest planet, 79 moons", -# "id": 5, -# "moons": true, -# "title": "Jupiter" -# }, -# { -# "description": "Golden, brown, and blue-grey, large and distinct ring system, 82 moons", -# "id": 6, -# "moons": true, -# "title": "Saturn" -# }, -# { -# "description": "Blue-green, holds the record for the coldest temperature ever measured in the solar system, 27 moons", -# "id": 7, -# "moons": true, -# "title": "Uranus" -# }, -# { -# "description": "Blue, on average the coldest planet, 14 moons", -# "id": 8, -# "moons": true, -# "title": "Neptune" -# } -# ] + return make_response(jsonify(f"Mercury successfully created"), 201) -# def test_post_first_planet(client): -# response = client.post("/planets", json={ -# "title": "Mercury", -# "description": "NICE PLANET!!!!!", -# "moons": false}) -# response_body = response.get_json() -# assert response.statuscode == 201 -# assert response_body == "Planet Mercury has been successfully created!" From be8029022939da6aee503ca47260ed26e9a5911c Mon Sep 17 00:00:00 2001 From: sana Date: Wed, 11 May 2022 20:29:42 +0300 Subject: [PATCH 18/19] add relationships with moon --- app/__init__.py | 18 ++++-- app/models/moon.py | 24 ++++++++ app/models/planet.py | 2 + app/routes/moon_helpers.py | 14 +++++ app/routes/moon_routes.py | 61 +++++++++++++++++++ app/routes/{helpers.py => planet_helpers.py} | 0 app/routes/planet_routes.py | 32 +++++++++- .../versions/1b989253add6_add_boolean.py | 28 --------- ...adds_planetk_model.py => 61d6d115d837_.py} | 19 ++++-- migrations/versions/aaa15afb4525_added.py | 38 ------------ 10 files changed, 157 insertions(+), 79 deletions(-) create mode 100644 app/models/moon.py create mode 100644 app/routes/moon_helpers.py create mode 100644 app/routes/moon_routes.py rename app/routes/{helpers.py => planet_helpers.py} (100%) delete mode 100644 migrations/versions/1b989253add6_add_boolean.py rename migrations/versions/{8478c5f52267_adds_planetk_model.py => 61d6d115d837_.py} (53%) delete mode 100644 migrations/versions/aaa15afb4525_added.py diff --git a/app/__init__.py b/app/__init__.py index c05bb3b7e..faad546e2 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -12,19 +12,25 @@ def create_app(test_config=None): app = Flask(__name__) from app.models.planet import Planet - app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False + from app.models.moon import Moon - if not test_config: - app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("SQLALCHEMY_DATABASE_URI") - else: - app.config["TESTING"] = True - app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( "SQLALCHEMY_TEST_DATABASE_URI") + app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False + # if not test_config: + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("SQLALCHEMY_DATABASE_URI") + # else: + # app.config["TESTING"] = True + # app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( "SQLALCHEMY_TEST_DATABASE_URI") db.init_app(app) migrate.init_app(app, db) + from .routes.planet_routes import planet_bp + from .routes.moon_routes import moon_bp + app.register_blueprint(planet_bp) + app.register_blueprint(moon_bp) + return app \ No newline at end of file diff --git a/app/models/moon.py b/app/models/moon.py new file mode 100644 index 000000000..1a7ea6946 --- /dev/null +++ b/app/models/moon.py @@ -0,0 +1,24 @@ +from app import db + +class Moon(db.Model): + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + name = db.Column(db.String, nullable=False) + planet_id = db.Column(db.Integer, db.ForeignKey('planet.id')) + planet = db.relationship("Planet", back_populates="planet_moons") + + def to_json(self): + return { + "id": self.id, + "name": self.name, + } + + def update(self, request_body): + self.name = request_body["name"] + self.planet_id = request_body["planet_id"] + + @classmethod + def create(cls, request_body): + return cls( + name=request_body["name"], + planet_id=request_body["planet_id"], + ) diff --git a/app/models/planet.py b/app/models/planet.py index ee24e0f1d..9b8b24684 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -11,6 +11,8 @@ class Planet(db.Model): title = db.Column(db.String, nullable=False) description = db.Column(db.String) moons = db.Column(db.Boolean, nullable=False) + planet_moons = db.relationship("Moon", back_populates="planet") + def to_json(self): return { diff --git a/app/routes/moon_helpers.py b/app/routes/moon_helpers.py new file mode 100644 index 000000000..e1f21ae56 --- /dev/null +++ b/app/routes/moon_helpers.py @@ -0,0 +1,14 @@ +from flask import Blueprint, jsonify, make_response, abort, request +from app.models.moon import Moon + +def validate_moon(id): + try: + id = int(id) + except: + return abort(make_response({"message": f"moon {id} is invalid"}, 400)) + moon= Moon.query.get(id) + + if not moon: + return abort(make_response({"message": f"moon {id} is not found"}, 404)) + + return moon diff --git a/app/routes/moon_routes.py b/app/routes/moon_routes.py new file mode 100644 index 000000000..055482d2b --- /dev/null +++ b/app/routes/moon_routes.py @@ -0,0 +1,61 @@ +from app import db +from app.models.planet import Planet +from flask import Blueprint, jsonify, make_response, request , abort +from app.models.moon import Moon +from .moon_helpers import validate_moon + + +moon_bp = Blueprint("moon_bp", __name__, url_prefix="/moons") + + +# CREATE Moon +@moon_bp.route("", methods=["POST"]) +def create_moon(): + request_body = request.get_json() + + new_moon = Moon.create(request_body) + + db.session.add(new_moon) + db.session.commit() + + return make_response(f"Moon {new_moon.name} has been successfully created!",201) + +# GET ALL Moons +@moon_bp.route("", methods=["GET"]) +def read_all_moons(): + name_query = request.args.get("name") + + if name_query: + moons = Moon.query.filter_by(name =name_query) + else: + moons = Moon.query.all() + + moons_response = [] + for moon in moons: + moons_response.append(moon.to_json()) + + return jsonify(moons_response), 200 + +# GET one Moon +@moon_bp.route("/", methods = ["GET"]) +def read_one_moon(id): + moon = validate_moon(id) + return jsonify(moon.to_json()), 200 + +@moon_bp.route("/", methods = ["PUT"]) +def update_one_moon(id): + moon = validate_moon(id) + request_body = request.get_json() + + moon.update(request_body) + + db.session.commit() + return make_response(f"Moon #{moon.id} successfully updated"), 200 + +@moon_bp.route("/", methods = ["DELETE"]) +def delete_one_moon(id): + moon = validate_moon(id) + db.session.delete(moon) + db.session.commit() + + return make_response(f"Moon #{moon.id} successfully deleted"), 200 diff --git a/app/routes/helpers.py b/app/routes/planet_helpers.py similarity index 100% rename from app/routes/helpers.py rename to app/routes/planet_helpers.py diff --git a/app/routes/planet_routes.py b/app/routes/planet_routes.py index 785b1a777..60896646c 100644 --- a/app/routes/planet_routes.py +++ b/app/routes/planet_routes.py @@ -1,7 +1,9 @@ from flask import Blueprint, jsonify, make_response, abort, request from app.models.planet import Planet from app import db -from .helpers import validate_planet +from .planet_helpers import validate_planet + + planet_bp = Blueprint("planet_bp", __name__, url_prefix="/planets") @@ -72,4 +74,30 @@ def delete_one_planet(id): db.session.delete(planet) db.session.commit() - return make_response(f"Planet # {planet.id} successfully deleted"), 200 \ No newline at end of file + return make_response(f"Planet # {planet.id} successfully deleted"), 200 + + +# @planet_bp.route("//cats", methods=["POST"]) +# def create_moon(id): +# planet = validate_planet(id) + +# request_body = request.get_json() +# new_moon = Moon.create(request_body) + +# new_moon.planet = planet +# db.session.add(new_moon) +# db.session.commit() + +# return make_response(jsonify(f"Moon {new_moon.name} orbiting around \ +# {new_moon.planet.title} successfully created"), 201) + + +@planet_bp.route("//moons", methods=["GET"]) +def read_moons(id): + planet = validate_planet(id) + + moons_response = [] + for moon in planet.planet_moons: + moons_response.append(moon.to_json()) + + return jsonify(moons_response), 200 diff --git a/migrations/versions/1b989253add6_add_boolean.py b/migrations/versions/1b989253add6_add_boolean.py deleted file mode 100644 index e3ca2ec9b..000000000 --- a/migrations/versions/1b989253add6_add_boolean.py +++ /dev/null @@ -1,28 +0,0 @@ -"""add boolean - -Revision ID: 1b989253add6 -Revises: 8478c5f52267 -Create Date: 2022-05-03 20:40:51.676253 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = '1b989253add6' -down_revision = '8478c5f52267' -branch_labels = None -depends_on = None - - -def upgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.add_column('planet', sa.Column('moons', sa.Boolean(), nullable=True)) - # ### end Alembic commands ### - - -def downgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.drop_column('planet', 'moons') - # ### end Alembic commands ### diff --git a/migrations/versions/8478c5f52267_adds_planetk_model.py b/migrations/versions/61d6d115d837_.py similarity index 53% rename from migrations/versions/8478c5f52267_adds_planetk_model.py rename to migrations/versions/61d6d115d837_.py index 32fd19eba..64702147f 100644 --- a/migrations/versions/8478c5f52267_adds_planetk_model.py +++ b/migrations/versions/61d6d115d837_.py @@ -1,8 +1,8 @@ -"""adds Planetk model +"""empty message -Revision ID: 8478c5f52267 +Revision ID: 61d6d115d837 Revises: -Create Date: 2022-05-03 19:05:46.484035 +Create Date: 2022-05-11 03:42:29.271519 """ from alembic import op @@ -10,7 +10,7 @@ # revision identifiers, used by Alembic. -revision = '8478c5f52267' +revision = '61d6d115d837' down_revision = None branch_labels = None depends_on = None @@ -20,8 +20,16 @@ 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('title', sa.String(), nullable=False), sa.Column('description', sa.String(), nullable=True), + sa.Column('moons', sa.Boolean(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('moon', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('planet_id', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['planet_id'], ['planet.id'], ), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### @@ -29,5 +37,6 @@ def upgrade(): def downgrade(): # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('moon') op.drop_table('planet') # ### end Alembic commands ### diff --git a/migrations/versions/aaa15afb4525_added.py b/migrations/versions/aaa15afb4525_added.py deleted file mode 100644 index cc6711fa0..000000000 --- a/migrations/versions/aaa15afb4525_added.py +++ /dev/null @@ -1,38 +0,0 @@ -"""added - -Revision ID: aaa15afb4525 -Revises: 1b989253add6 -Create Date: 2022-05-03 21:05:12.563656 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = 'aaa15afb4525' -down_revision = '1b989253add6' -branch_labels = None -depends_on = None - - -def upgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.alter_column('planet', 'moons', - existing_type=sa.BOOLEAN(), - nullable=False) - op.alter_column('planet', 'title', - existing_type=sa.VARCHAR(), - nullable=False) - # ### end Alembic commands ### - - -def downgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.alter_column('planet', 'title', - existing_type=sa.VARCHAR(), - nullable=True) - op.alter_column('planet', 'moons', - existing_type=sa.BOOLEAN(), - nullable=True) - # ### end Alembic commands ### From 8e202450edc01e5c8c44809cf2b0442cd4edef40 Mon Sep 17 00:00:00 2001 From: sana Date: Wed, 11 May 2022 20:35:32 +0300 Subject: [PATCH 19/19] add Procfile --- Procfile | 1 + requirements.txt | 8 ++++++++ 2 files changed, 9 insertions(+) create mode 100644 Procfile diff --git a/Procfile b/Procfile new file mode 100644 index 000000000..066ed31d9 --- /dev/null +++ b/Procfile @@ -0,0 +1 @@ +web: gunicorn 'app:create_app()' diff --git a/requirements.txt b/requirements.txt index a506b4d12..37b7c1d29 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,19 +1,27 @@ alembic==1.5.4 +attrs==21.4.0 autopep8==1.5.5 blinker==1.4 certifi==2020.12.5 chardet==4.0.0 click==7.1.2 +coverage==6.3.2 Flask==1.1.2 Flask-Migrate==2.6.0 Flask-SQLAlchemy==2.4.4 +gunicorn==20.1.0 idna==2.10 +iniconfig==1.1.1 itsdangerous==1.1.0 Jinja2==2.11.3 Mako==1.1.4 MarkupSafe==1.1.1 +packaging==21.3 +pluggy==0.13.1 psycopg2-binary==2.8.6 +py==1.11.0 pycodestyle==2.6.0 +pyparsing==3.0.8 pytest==6.2.3 pytest-cov==2.12.1 python-dateutil==2.8.1