diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..106425a33 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,7 +1,38 @@ from flask import Flask +from flask_sqlalchemy import SQLAlchemy +from flask_migrate import Migrate +from dotenv import load_dotenv +import os + +# postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system_development + +db =SQLAlchemy() +migrate = Migrate() +load_dotenv() def create_app(test_config=None): app = Flask(__name__) + #DB Config + 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 app.models.planet import Planet + from app.models.moon import Moon + + from app.routes.planet_routes import planets_bp + from app.routes.moon_routes import moons_bp + app.register_blueprint(planets_bp) + app.register_blueprint(moons_bp) + + # from app.models. import + 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/moon.py b/app/models/moon.py new file mode 100644 index 000000000..3d2059dd5 --- /dev/null +++ b/app/models/moon.py @@ -0,0 +1,29 @@ +from app import db +from flask import make_response + +class Moon(db.Model): + moon_id = db.Column(db.Integer, primary_key=True, autoincrement=True) + name = db.Column(db.String) + planets = db.relationship("Planet", back_populates="moon") + + def moon_to_dict(self): + return { + "moon_id": self.moon_id, + "name": self.name + } + def __str__(self): + return f'An object of type {self.__class__.__name__} with id {self.moon_id}.' + + @classmethod + def create_new_planet(cls, request_data): + if "name" not in request_data or request_data is None: + return make_response("Invalid Request. Missing required fields: name or request data", 400) + return cls( + name=request_data["name"].title() + ) + + def update(self, moon_to_dict): + for key, value in moon_to_dict.items(): + if key == "name": + value = value.title() + setattr(self,key,value) \ No newline at end of file diff --git a/app/models/planet.py b/app/models/planet.py new file mode 100644 index 000000000..d61315d3c --- /dev/null +++ b/app/models/planet.py @@ -0,0 +1,45 @@ +from app import db +from flask import make_response + +class Planet(db.Model): + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + name = db.Column(db.String) + description = db.Column(db.String) + color = db.Column(db.String) + moon_id = db.Column(db.Integer, db.ForeignKey('moon.moon_id')) + moon = db.relationship("Moon", back_populates="planets") + # __tablename__ = "planets" + + + def update(self, planet_to_dict): + for key, value in planet_to_dict.items(): + if key == "name": + value = value.title() + setattr(self,key,value) + + + def planet_to_dict(self): + return { + "id": self.id, + "name": self.name, + "description": self.description, + "color": self.color, + "moon_id": self.moon_id } + + def __str__(self): + return f'An object of type {self.__class__.__name__} with id {self.id}.' + + @classmethod + def create_new_planet(cls, request_data): + if "name" not in request_data or "description" not in request_data: + return make_response("Invalid Request. Missing required fields: name or description", 400) + return cls( + name=request_data["name"].title(), + description=request_data["description"], + color=request_data.get("color"), + moon_id=request_data.get("moon_id") + ) + + + + \ No newline at end of file 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/__init__.py b/app/routes/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/app/routes/moon_routes.py b/app/routes/moon_routes.py new file mode 100644 index 000000000..8a342a898 --- /dev/null +++ b/app/routes/moon_routes.py @@ -0,0 +1,45 @@ +from app import db +from app.models.moon import Moon +from app.models.planet import Planet +from app.routes.planet_routes import validate_model +from flask import Blueprint, jsonify, abort, make_response, request + +moons_bp = Blueprint("moons", __name__, url_prefix="/moons") + + +@moons_bp.route("", methods = ["GET"]) +def read_all_moons(): + moons_response = [] + query_params = request.args.to_dict() + + if query_params: + query_params = {k.lower(): v.title() for k, v in query_params.items()} + moons = Moon.query.filter_by(**query_params).all() + else: + moons = Moon.query.all() + + moons_response = [moon.moon_to_dict() for moon in moons] + return jsonify(moons_response) + +@moons_bp.route("", methods=["POST"]) +def create_moon(): + # Retrieve the request body + request_body = request.get_json() + + # Validate the request body + if not request_body: + return make_response(jsonify({"error": "Request body must be provided"}), 400) + if "name" not in request_body: + return make_response(jsonify({"error": "Name field is required"}), 400) + + # Create a new Moon instance + new_moon = Moon( + name=request_body["name"] + ) + + # Add the new Moon instance to the database session + db.session.add(new_moon) + db.session.commit() + + # Return a JSON response indicating success + return make_response(jsonify({"message": f"New moon '{new_moon.name}' created"}), 201) \ 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..843966337 --- /dev/null +++ b/app/routes/planet_routes.py @@ -0,0 +1,111 @@ +from app import db +from app.models.planet import Planet +from app.models.moon import Moon +from flask import Blueprint, jsonify, abort, make_response, request + +planets_bp = Blueprint("planets", __name__, url_prefix="/planets") + +@planets_bp.route("", methods = ["GET"]) +def read_all_planets(): + planets_response = [] + query_params = request.args.to_dict() + + if query_params: + query_params = {k.lower(): v.title() for k, v in query_params.items()} + planets = Planet.query.filter_by(**query_params).all() + else: + planets = Planet.query.all() + + planets_response = [planet.planet_to_dict() for planet in planets] + return jsonify(planets_response) + + +@planets_bp.route("", methods = ["POST"]) +def create_planets(): + request_body = request.get_json() + try: + new_planet = Planet.create_new_planet(request_body) + db.session.add(new_planet) + db.session.commit() + + message = f"Planet {new_planet.name} successfully created" + return make_response(jsonify(message), 201) + + except KeyError as e: + abort(make_response(f"Invalid request. Missing required value: {e}"), 400) + + +@planets_bp.route("/", methods=["GET"]) +def read_one_planet(id): + planet = validate_model(Planet, id) + planet = Planet.query.get(id) + return jsonify(planet.planet_to_dict()), 200 + +@planets_bp.route("/", methods=["PUT"]) +def update_planet(id): + planet = validate_model(Planet, id) + + planet.update(request.get_json()) + + db.session.commit() + message = f"Planet #{id} successfully updated" + return make_response(jsonify(message)) + +@planets_bp.route("/", methods=["DELETE"]) +def delete_planet(id): + planet= validate_model(Planet, id) + + db.session.delete(planet) + db.session.commit() + + message = f"Planet #{id} successfully deleted" + return make_response(jsonify(message), 200) +def validate_model(cls, id): + try: + id = int(id) + except: + message = f"{cls.__name__} {id} is invalid" + abort(make_response({"message": message}, 400)) + + model = cls.query.get(id) + + if not model: + message = f"{cls.__name__} {id} not found" + abort(make_response({"message": message}, 404)) + + return model + +@planets_bp.route("//moons", methods=["POST"]) +def create_moon(id): + planet = validate_model(Planet, id) + request_body = request.get_json() + new_moon = Moon( + name=request_body["name"] + ) + + db.session.add(new_moon) + db.session.commit() + add_moon_to_planet(new_moon.moon_id, planet) + + return make_response(jsonify(f"Moon {new_moon.name} successfully created"), 201) + +def add_moon_to_planet(moon_id, planet): + planet.moon_id = moon_id + db.session.commit() +@planets_bp.route("//moons", methods=["GET"]) +def read_moons(id): + planet = validate_model(Planet, id) + moons_response = [] + for id in str(planet.id): + moons_response.append( + { + "moon_id": int(id), + } + ) + return jsonify(moons_response) +# def handle_moon_from_planet(): + + + + + 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..252c88927 --- /dev/null +++ b/app/tests/conftest.py @@ -0,0 +1,49 @@ +import pytest +from app import create_app +from app import db +from flask.signals import request_finished +from app.models.planet import Planet + +# instance of our app that is listening for our test db +@pytest.fixture +def app(): + app = create_app({"TESTING": True}) + # helps with the accuracy of tests + # clears out temperary data + @request_finished.connect_via(app) + def expire_session(sender, response, **extra): + db.session.remove() + + # our database is clean,its empty of all data + with app.app_context(): + # generate a new clean, start to db + # an empty db that we can test on + db.create_all() + + # tells fixture to return an instance of app context + # sending it to test when test is called + yield app + + # once test is complete clears out any data that it created + # so we can work with clean database + with app.app_context(): + db.drop_all() + +@pytest.fixture +def client(app): + # app that references another fixture + # holds the reference to the test interface + return app.test_client() + +@pytest.fixture +def two_saved_planets(app): + # Arrange + ocean_planet = Planet(name="Ocean Planet", + description="Smells fishy", + color="Silver") + minion_planet = Planet(name="Mark", + description="Miniony", + color="Yellow") + db.session.add_all([ocean_planet, minion_planet]) + db.session.commit() + diff --git a/app/tests/test_routes.py b/app/tests/test_routes.py new file mode 100644 index 000000000..7fe694653 --- /dev/null +++ b/app/tests/test_routes.py @@ -0,0 +1,84 @@ + +# get all planets and return no records +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 == [] + +# get one planet by id +def test_get_planet_by_id(client, two_saved_planets): + # Act + response1 = client.get('/planets/1') + response2 = client.get('/planets/2') + response_body1 = response1.get_json() + response_body2 = response2.get_json() + + #Assert + assert response1.status_code == 200 + assert response_body1 == { + "id": 1, + "name": "Ocean Planet", + "description": "Smells fishy", + "color": "Silver" + } + assert response_body2 == { + "id": 2, + "name": "Mark", + "description": "Miniony", + "color": "Yellow" + } + +def test_create_one_planet(client): + # Act + response = client.post("/planets", json={ + "name": "New Planet", + "description": "Fresh out the box" + }) + response_body = response.get_json() + # alternative if the return statement does not use jsonify + # response_body = response.get_data(as_text=True) + + #Assert + assert response.status_code == 201 + assert response_body == "Planet New Planet successfully created" + +def test_planets_with_no_data_returns_404_status_code(client): + response = client.get("/planets/1") + response_body = response.get_json() + + assert response_body == {"message": "Planet 1 not found"} + assert response.status_code == 404 + +def test_update_planet_successfully(client,two_saved_planets): + planet_id = 1 + updated_planet_data = { + "name": "Updated planet name", + "description": "I'm updated", + "color": "Fusha" + } + response = client.put(f"planets/1", json=updated_planet_data) + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == f"Planet #{planet_id} successfully updated" +def test_delete_planet_successfully(client, two_saved_planets): + planet_id = 1 + response = client.delete(f"planets/{planet_id}") + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == f"Planet #{planet_id} successfully deleted" + + response = client.get(f"/planets/{planet_id}") + assert response.status_code == 404 + +def test_deleting_non_existing_planet_returns_planet_not_found(client): + response = client.delete(f"planets/1") + response_body = response.get_json() + + assert response.status_code == 404 + assert response_body == {"message": "Planet 1 not found"} \ No newline at end of file diff --git a/migrations/README b/migrations/README new file mode 100644 index 000000000..98e4f9c44 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 000000000..f8ed4801f --- /dev/null +++ b/migrations/alembic.ini @@ -0,0 +1,45 @@ +# A generic, single database configuration. + +[alembic] +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 000000000..8b3fb3353 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,96 @@ +from __future__ import with_statement + +import logging +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool +from flask import current_app + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) +logger = logging.getLogger('alembic.env') + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +config.set_main_option( + 'sqlalchemy.url', + str(current_app.extensions['migrate'].db.engine.url).replace('%', '%%')) +target_metadata = current_app.extensions['migrate'].db.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, target_metadata=target_metadata, literal_binds=True + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + # this callback is used to prevent an auto-migration from being generated + # when there are no changes to the schema + # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html + def process_revision_directives(context, revision, directives): + if getattr(config.cmd_opts, 'autogenerate', False): + script = directives[0] + if script.upgrade_ops.is_empty(): + directives[:] = [] + logger.info('No changes in schema detected.') + + connectable = engine_from_config( + config.get_section(config.config_ini_section), + prefix='sqlalchemy.', + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=target_metadata, + process_revision_directives=process_revision_directives, + **current_app.extensions['migrate'].configure_args + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 000000000..2c0156303 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,24 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} diff --git a/migrations/versions/a6fa2b4e7d4b_adds_a_planet_model.py b/migrations/versions/a6fa2b4e7d4b_adds_a_planet_model.py new file mode 100644 index 000000000..6fbff8c65 --- /dev/null +++ b/migrations/versions/a6fa2b4e7d4b_adds_a_planet_model.py @@ -0,0 +1,34 @@ +"""adds a planet model + +Revision ID: a6fa2b4e7d4b +Revises: +Create Date: 2023-04-25 18:01:36.589170 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'a6fa2b4e7d4b' +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('color', 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 ###