From 4da0aeb8a66a493069d745f20a7aaefe4d014dff Mon Sep 17 00:00:00 2001 From: Rachael Date: Mon, 18 Oct 2021 16:41:41 -0400 Subject: [PATCH 01/10] Added all planets endpoint and defined planets --- app/__init__.py | 4 +++- app/routes.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..01ddd0208 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,7 +1,9 @@ from flask import Flask - def create_app(test_config=None): app = Flask(__name__) + from .routes import planets_bp + app.register_blueprint(planets_bp) + return app diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..6cadf8456 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,34 @@ from flask import Blueprint +class Planet: + def __init__(self, id, name, description, num_of_moons): + self.id = id + self.name = name + self.description = description + self.num_of_moons = num_of_moons + +planets = [ + Planet(1, "Mercury", "First planet from the sun", 0), + Planet(2, "Venus", "Second planet from the sun", 0), + Planet(3, "Earth", "Third planet from the sun", 1), + Planet(4, "Mars", "Fourth planet from the sun", 2), + Planet(5, "Jupiter", "Fifth planet from the sun", 79) +] + +planets_bp = Blueprint("planets_bp", __name__, url_prefix="/planets") + +@planets_bp.route("", methods=["GET"]) +def handle_planets(): + planets_response = [] + + for planet in planets: + planets_response.append( + { + "id" : planet.id, + "name" : planet.name, + "description" : planet.description, + "num_of_moons" : planet.num_of_moons + } + ) + + return jsonify(planets_response) \ No newline at end of file From d60813dfb5b2e09908059c1328a442807d09beaf Mon Sep 17 00:00:00 2001 From: kristina Date: Mon, 18 Oct 2021 17:00:30 -0400 Subject: [PATCH 02/10] added route to get one planet --- app/routes.py | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/app/routes.py b/app/routes.py index 6cadf8456..5dcd231f6 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,4 +1,4 @@ -from flask import Blueprint +from flask import Blueprint, jsonify class Planet: def __init__(self, id, name, description, num_of_moons): @@ -17,18 +17,31 @@ def __init__(self, id, name, description, num_of_moons): planets_bp = Blueprint("planets_bp", __name__, url_prefix="/planets") -@planets_bp.route("", methods=["GET"]) -def handle_planets(): - planets_response = [] - - for planet in planets: - planets_response.append( - { +def make_planet_dict(planet): + return { "id" : planet.id, "name" : planet.name, "description" : planet.description, "num_of_moons" : planet.num_of_moons } - ) - return jsonify(planets_response) \ No newline at end of file + +@planets_bp.route("", methods=["GET"]) +def handle_planets(): + planets_response = [] + + for planet in planets: + current_planet = make_planet_dict(planet) + planets_response.append(current_planet) + + return jsonify(planets_response) + +@planets_bp.route("/", methods=["GET"]) +def handle_one_planet(planet_id): + planet_response = jsonify("Not a valid planet") + + for planet in planets: + if planet.id == int(planet_id): + planet_response = make_planet_dict(planet) + + return planet_response \ No newline at end of file From 47465a45b566b5b7fb247fa27ab251b0e6a94468 Mon Sep 17 00:00:00 2001 From: kristina Date: Fri, 22 Oct 2021 13:59:25 -0400 Subject: [PATCH 03/10] Created Planet model, configuration and added POST route --- app/__init__.py | 12 +++ app/models/__init__.py | 0 app/models/planet.py | 8 ++ app/routes.py | 49 ++++++---- migrations/README | 1 + migrations/alembic.ini | 45 +++++++++ migrations/env.py | 96 +++++++++++++++++++ migrations/script.py.mako | 24 +++++ .../57a73e0d96bd_adds_planet_model.py | 34 +++++++ 9 files changed, 252 insertions(+), 17 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/57a73e0d96bd_adds_planet_model.py diff --git a/app/__init__.py b/app/__init__.py index 01ddd0208..9844894ed 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,8 +1,20 @@ from flask import Flask +from flask_sqlalchemy import SQLAlchemy +from flask_migrate import Migrate + +db = SQLAlchemy() +migrate = Migrate() def create_app(test_config=None): app = Flask(__name__) + app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False + app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system_development" + + from app.models.planet import Planet + db.init_app(app) + migrate.init_app(app, db) + from .routes import planets_bp app.register_blueprint(planets_bp) diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/app/models/planet.py b/app/models/planet.py new file mode 100644 index 000000000..2cc85c3eb --- /dev/null +++ b/app/models/planet.py @@ -0,0 +1,8 @@ +from app import db + +class Planet(db.Model): + id = db.Column(db.Integer, primary_key = True, autoincrement = True) + name = db.Column(db.String) + description = db.Column(db.String) + num_of_moons = db.Column(db.Integer) + diff --git a/app/routes.py b/app/routes.py index 5dcd231f6..8b30445d5 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,4 +1,6 @@ -from flask import Blueprint, jsonify +from flask import Blueprint, jsonify, request, make_response +from app import db +from app.models.planet import Planet class Planet: def __init__(self, id, name, description, num_of_moons): @@ -7,13 +9,13 @@ def __init__(self, id, name, description, num_of_moons): self.description = description self.num_of_moons = num_of_moons -planets = [ - Planet(1, "Mercury", "First planet from the sun", 0), - Planet(2, "Venus", "Second planet from the sun", 0), - Planet(3, "Earth", "Third planet from the sun", 1), - Planet(4, "Mars", "Fourth planet from the sun", 2), - Planet(5, "Jupiter", "Fifth planet from the sun", 79) -] +# planets = [ +# Planet(1, "Mercury", "First planet from the sun", 0), +# Planet(2, "Venus", "Second planet from the sun", 0), +# Planet(3, "Earth", "Third planet from the sun", 1), +# Planet(4, "Mars", "Fourth planet from the sun", 2), +# Planet(5, "Jupiter", "Fifth planet from the sun", 79) +# ] planets_bp = Blueprint("planets_bp", __name__, url_prefix="/planets") @@ -25,21 +27,34 @@ def make_planet_dict(planet): "num_of_moons" : planet.num_of_moons } - -@planets_bp.route("", methods=["GET"]) +@planets_bp.route("", methods=["GET", "POST"]) def handle_planets(): - planets_response = [] - - for planet in planets: - current_planet = make_planet_dict(planet) - planets_response.append(current_planet) + if request.method == "GET": + planets_response = [] + planets = Planet.query.all() - return jsonify(planets_response) + for planet in planets: + current_planet = make_planet_dict(planet) + planets_response.append(current_planet) + + return jsonify(planets_response) + + else: + request_body = request.get_json() + new_planet = Planet( + name = request_body["name"], + description= request_body["description"], + num_of_moons=request_body["num_of_moons"] + ) + db.session.add(new_planet) + db.session.commit() + + return f"Planet successfully created {new_planet.name}", 201 @planets_bp.route("/", methods=["GET"]) def handle_one_planet(planet_id): planet_response = jsonify("Not a valid planet") - + for planet in planets: if planet.id == int(planet_id): planet_response = make_planet_dict(planet) 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/57a73e0d96bd_adds_planet_model.py b/migrations/versions/57a73e0d96bd_adds_planet_model.py new file mode 100644 index 000000000..46c4e135f --- /dev/null +++ b/migrations/versions/57a73e0d96bd_adds_planet_model.py @@ -0,0 +1,34 @@ +"""adds Planet model + +Revision ID: 57a73e0d96bd +Revises: +Create Date: 2021-10-22 13:44:18.980139 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '57a73e0d96bd' +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('num_of_moons', sa.Integer(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('planet') + # ### end Alembic commands ### From f9a4790987605a5ab065a9264cb35091a7a5d895 Mon Sep 17 00:00:00 2001 From: kristina Date: Fri, 22 Oct 2021 14:27:11 -0400 Subject: [PATCH 04/10] whitespace deleted and handle one planet refactored --- app/models/planet.py | 2 +- app/routes.py | 22 +++++----------------- 2 files changed, 6 insertions(+), 18 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index 2cc85c3eb..92fedc972 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -1,7 +1,7 @@ from app import db class Planet(db.Model): - id = db.Column(db.Integer, primary_key = True, autoincrement = True) + id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String) description = db.Column(db.String) num_of_moons = db.Column(db.Integer) diff --git a/app/routes.py b/app/routes.py index 8b30445d5..c842a1df4 100644 --- a/app/routes.py +++ b/app/routes.py @@ -2,21 +2,6 @@ from app import db from app.models.planet import Planet -class Planet: - def __init__(self, id, name, description, num_of_moons): - self.id = id - self.name = name - self.description = description - self.num_of_moons = num_of_moons - -# planets = [ -# Planet(1, "Mercury", "First planet from the sun", 0), -# Planet(2, "Venus", "Second planet from the sun", 0), -# Planet(3, "Earth", "Third planet from the sun", 1), -# Planet(4, "Mars", "Fourth planet from the sun", 2), -# Planet(5, "Jupiter", "Fifth planet from the sun", 79) -# ] - planets_bp = Blueprint("planets_bp", __name__, url_prefix="/planets") def make_planet_dict(planet): @@ -42,8 +27,8 @@ def handle_planets(): else: request_body = request.get_json() new_planet = Planet( - name = request_body["name"], - description= request_body["description"], + name=request_body["name"], + description=request_body["description"], num_of_moons=request_body["num_of_moons"] ) db.session.add(new_planet) @@ -53,6 +38,9 @@ def handle_planets(): @planets_bp.route("/", methods=["GET"]) def handle_one_planet(planet_id): + + planets = Planet.query.all() + planet_response = jsonify("Not a valid planet") for planet in planets: From b06decf79c373d931326b64ef4ebdd1da17034fe Mon Sep 17 00:00:00 2001 From: Rachael Date: Mon, 25 Oct 2021 16:48:06 -0400 Subject: [PATCH 05/10] Refactor handle_planet.py --- app/routes.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/routes.py b/app/routes.py index 5dcd231f6..f94a6a56c 100644 --- a/app/routes.py +++ b/app/routes.py @@ -31,8 +31,8 @@ def handle_planets(): planets_response = [] for planet in planets: - current_planet = make_planet_dict(planet) - planets_response.append(current_planet) + current_planet_dict = make_planet_dict(planet) + planets_response.append(current_planet_dict) return jsonify(planets_response) From 6b11bf1bf53f40311b63bebacd2da7481457e821 Mon Sep 17 00:00:00 2001 From: kristina Date: Tue, 26 Oct 2021 14:08:11 -0400 Subject: [PATCH 06/10] added param querying and substring search capability --- app/routes.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/app/routes.py b/app/routes.py index 5c89f43e7..707829058 100644 --- a/app/routes.py +++ b/app/routes.py @@ -15,14 +15,21 @@ def make_planet_dict(planet): @planets_bp.route("", methods=["GET", "POST"]) def handle_planets(): if request.method == "GET": + + planet_name_query = request.args.get("name") + if planet_name_query: + planets = Planet.query.filter(Planet.name.contains(planet_name_query)) + # we can search for a substring + else: + planets = Planet.query.all() + + planets_response = [] - planets = Planet.query.all() - for planet in planets: current_planet = make_planet_dict(planet) planets_response.append(current_planet) - return jsonify(planets_response) + return jsonify(planets_response), 200 else: request_body = request.get_json() From 7975d8f792a1f6810ecc7da20520360510b99205 Mon Sep 17 00:00:00 2001 From: Rachael Date: Wed, 27 Oct 2021 13:59:55 -0400 Subject: [PATCH 07/10] Add test folder and config file with two test fixtures and make .env file --- app/__init__.py | 11 +++++++++-- tests/__init__.py | 0 tests/conftest.py | 23 +++++++++++++++++++++++ tests/test_routes.py | 3 +++ 4 files changed, 35 insertions(+), 2 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 9844894ed..191773b38 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,6 +1,8 @@ from flask import Flask +from dotenv import load_dotenv from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate +import os db = SQLAlchemy() migrate = Migrate() @@ -8,8 +10,13 @@ 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" + 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") from app.models.planet import Planet db.init_app(app) 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..a7a2b3906 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,23 @@ +import pytest +from app import create_app +from app import db + +@pytest.fixture +def app(): + app = create_app({"TESTING":True}) + + # creating a test db + yielding to tests + with app.app_context(): + db.create_all() + yield app + + # dropping the db when finished (clean up) + with app.app_context(): + db.drop_all() + +@pytest.fixture +def client(app): + return app.test_client() + + + diff --git a/tests/test_routes.py b/tests/test_routes.py new file mode 100644 index 000000000..e097fe22e --- /dev/null +++ b/tests/test_routes.py @@ -0,0 +1,3 @@ +# list all planets + +# list one planet \ No newline at end of file From cfc01b5e7b4c1a8a9b758da67bb26a3e3e4ff1a6 Mon Sep 17 00:00:00 2001 From: kristina Date: Wed, 27 Oct 2021 14:20:56 -0400 Subject: [PATCH 08/10] tests added for getting all planets and getting planet by id --- app/__init__.py | 3 ++- tests/conftest.py | 9 +++++++++ tests/test_routes.py | 18 +++++++++++++++++- 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 191773b38..f682c0889 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,11 +1,12 @@ from flask import Flask -from dotenv import load_dotenv 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__) diff --git a/tests/conftest.py b/tests/conftest.py index a7a2b3906..d7d68c995 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,6 +1,7 @@ import pytest from app import create_app from app import db +from app.models.planet import Planet @pytest.fixture def app(): @@ -19,5 +20,13 @@ def app(): def client(app): return app.test_client() +@pytest.fixture +def two_saved_planets(app): + venus_planet = Planet(name="Venus", description="Yellow planet", num_of_moons=0) + dune_planet = Planet(name="Dune", description="Desert planet", num_of_moons=2) + + db.session.add_all([venus_planet, dune_planet]) + db.session.commit() + diff --git a/tests/test_routes.py b/tests/test_routes.py index e097fe22e..7df852840 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -1,3 +1,19 @@ # list all planets +def test_get_all_planets_with_no_records(client): + response = client.get("/planets") + response_body = response.get_json() -# list one planet \ No newline at end of file + assert response.status_code == 200 + assert response_body == [] +# list one planet +def test_get_planet_by_id(client, two_saved_planets): + response = client.get("/planets/1") + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == { + "id": 1, + "name": "Venus", + "description": "Yellow planet", + "num_of_moons": 0 + } \ No newline at end of file From 1690644fbbd1c54481b2e16d864766094d57e75a Mon Sep 17 00:00:00 2001 From: Rachael Date: Sun, 31 Oct 2021 17:31:59 -0400 Subject: [PATCH 09/10] Add gunicorn to requirements.txt and make Procfile --- Procfile | 1 + 1 file changed, 1 insertion(+) create mode 100644 Procfile diff --git a/Procfile b/Procfile new file mode 100644 index 000000000..62e430aca --- /dev/null +++ b/Procfile @@ -0,0 +1 @@ +web: gunicorn 'app:create_app()' \ No newline at end of file From 3d84cf702ab1fd37b5bc3ffb61b161c08ee07122 Mon Sep 17 00:00:00 2001 From: Rachael Date: Sun, 31 Oct 2021 17:34:27 -0400 Subject: [PATCH 10/10] Add gunicorn to requirements.txt --- requirements.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/requirements.txt b/requirements.txt index fd90fffa8..d2f045e58 100644 --- a/requirements.txt +++ b/requirements.txt @@ -6,6 +6,7 @@ click==7.1.2 Flask==1.1.2 Flask-Migrate==2.6.0 Flask-SQLAlchemy==2.4.4 +gunicorn==20.1.0 idna==2.10 itsdangerous==1.1.0 Jinja2==2.11.3