diff --git a/Procfile b/Procfile new file mode 100644 index 000000000..62e430aca --- /dev/null +++ b/Procfile @@ -0,0 +1 @@ +web: gunicorn 'app:create_app()' \ No newline at end of file diff --git a/ada-project-docs/wave_06.md b/ada-project-docs/wave_06.md index 5fc6bbcc6..fc4019beb 100644 --- a/ada-project-docs/wave_06.md +++ b/ada-project-docs/wave_06.md @@ -60,7 +60,7 @@ When I send a `POST` request to `/goals/1/tasks` with this request body: } ``` -Then the three `Task`s belong to the `Goal` and it gets updated in the database, and we get back a `200 OK` with the following response body: +Then the three `Task`s belong to the `Goal`, and it gets updated in the database, and we get back a `200 OK` with the following response body: ```json { diff --git a/app/__init__.py b/app/__init__.py index 2764c4cc8..cac5d268b 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -4,12 +4,10 @@ import os from dotenv import load_dotenv - db = SQLAlchemy() migrate = Migrate() load_dotenv() - def create_app(test_config=None): app = Flask(__name__) app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False @@ -29,6 +27,10 @@ def create_app(test_config=None): db.init_app(app) migrate.init_app(app, db) - # Register Blueprints here + from .routes import tasks_bp + app.register_blueprint(tasks_bp) + + from .routes import goals_bp + app.register_blueprint(goals_bp) return app diff --git a/app/models/goal.py b/app/models/goal.py index 8cad278f8..de75eeebc 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -1,6 +1,18 @@ from flask import current_app from app import db - +from datetime import datetime +from flask import jsonify class Goal(db.Model): - goal_id = db.Column(db.Integer, primary_key=True) + goal_id = db.Column(db.Integer, autoincrement = True, primary_key=True) + title = db.Column(db.String, nullable = False) + tasks = db.relationship("Task", back_populates="goal") + + def get_id(self): + return self.goal_id + def make_dict_response(self, response_code): + response_body = jsonify({"goal" : { + "id": self.get_id(), + "title": self.title, + }}), response_code + return response_body \ No newline at end of file diff --git a/app/models/task.py b/app/models/task.py index 39c89cd16..4c50b2ca3 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,6 +1,36 @@ from flask import current_app from app import db +from datetime import datetime +from flask import jsonify class Task(db.Model): - task_id = db.Column(db.Integer, primary_key=True) + task_id = db.Column(db.Integer, autoincrement = True, primary_key=True) + title = db.Column(db.String, nullable = False) + description = db.Column(db.String, nullable = False) + completed_at = db.Column(db.DateTime, nullable = True) + + goal_id = db.Column(db.Integer, db.ForeignKey('goal.goal_id')) + goal = db.relationship("Goal", back_populates="tasks") + + def is_complete(self): + return bool(self.completed_at) + def get_id(self): + return self.task_id + + def make_dict_response(self, response_code): + # try: response_body = jsonify({"task" : { + # "id": self.get_id(), + # "goal_id": self.goal_id, + # "title": self.title, + # "description": self.description, + # "is_complete": self.is_complete(), + # }}) + # except AttributeError: + response_body = jsonify({"task" : { + "id": self.get_id(), + "title": self.title, + "description": self.description, + "is_complete": self.is_complete(), + }}), response_code + return response_body \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..143278e68 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,221 @@ -from flask import Blueprint +from app import db +from app.models.task import Task +from app.models.goal import Goal +from flask import Blueprint, jsonify, make_response, request +from sqlalchemy import asc, desc +from datetime import datetime, timezone +import requests +import os +SLACK_POST_MESSAGE_URL = 'https://slack.com/api/chat.postMessage' +SLACK_POST_MESSAGE_CHANNEL = '#task-list' +SLACK_BOT_TOKEN = os.environ.get('SLACK_TOKEN') +SLACK_BOT_USERNAME = 'Waebot' + +tasks_bp = Blueprint("tasks", __name__, url_prefix="/tasks") +goals_bp = Blueprint("goals", __name__, url_prefix="/goals") + +def make_input_valid(number): + try: + int(number) + except: + return make_response(f"{number} is not an int!", 400) + +def is_parameter_valid(parameter_id, mdl=Task): + if make_input_valid(parameter_id) is not None: + return make_input_valid(parameter_id) + elif mdl.query.get(parameter_id) is None: + return make_response(f"{parameter_id} is not a valid id!", 404) + +def model_select(url): + if "goals" in url: + mdl = Goal + else: + mdl = Task + return mdl + +@goals_bp.route("",methods=["POST"]) +@tasks_bp.route("", methods=["POST"]) +def post_tasks(): + request_body = request.get_json() + mdl = model_select(request.url) + if mdl == Task: + try: new_obj = Task(title=request_body["title"], + description=request_body["description"], + completed_at=request_body["completed_at"]) + except KeyError: return ({"details":"Invalid data"},400) + if mdl == Goal: + try: new_obj = Goal(title=request_body["title"]) + except KeyError: return ({"details":"Invalid data"},400) + db.session.add(new_obj) + db.session.commit() + response_body = mdl.make_dict_response(new_obj, 201) + return response_body + +@goals_bp.route("/tasks", methods=["POST"]) +def create_tasks_with_goals(goal_id): + invalid_param = is_parameter_valid(goal_id, Goal) + if invalid_param: + return make_response(invalid_param) + goal = Goal.query.get(goal_id) + + request_body = request.get_json() + task_ids_list = [] + try: + for task_id in request_body["task_ids"]: + task = Task.query.get(task_id) + task.goal = goal + task_ids_list.append(task.task_id) + db.session.add(task) + except KeyError: return ({"details":"Invalid data"},400) + db.session.commit() + response_body = { + "id":int(goal_id), + "task_ids": task_ids_list + } + return response_body + +@goals_bp.route("//tasks", methods=["GET"]) +def read_goal_tasks(goal_id): + invalid_param = is_parameter_valid(goal_id, Goal) + if invalid_param: + return invalid_param + goal = Goal.query.get(goal_id) + goal_tasks_response = [] + + for task in goal.tasks: + goal_tasks_response.append( + { + "id": task.task_id, + "goal_id": task.goal_id, + "title": task.title, + "description": task.description, + "is_complete": task.is_complete(), + }) + + return (jsonify({"id": int(goal_id), "title": goal.title, "tasks": goal_tasks_response}), 200) + +@goals_bp.route("/",methods=["PUT"]) +@tasks_bp.route("/", methods=["PUT"]) +def put_tasks(task_id=None, goal_id=None): + if task_id: + obj_id = task_id + if goal_id: + obj_id = goal_id + mdl = model_select(request.url) + invalid_param = is_parameter_valid(obj_id, mdl) + if invalid_param: + return make_response(invalid_param) + model = mdl.query.get(obj_id) + form_data = request.get_json() + if form_data.get("title"): + model.title = form_data["title"] + if form_data.get("description"): + model.description = form_data["description"] + if form_data.get("completed_at"): + model.completed_at = form_data["completed_at"] + db.session.commit() + response_body = mdl.make_dict_response(model, 200) + return response_body + +@tasks_bp.route("//mark_complete", methods=["PATCH"]) +def mark_parameter_complete(task_id): + invalid_param = is_parameter_valid(task_id, Task) + if invalid_param: + return make_response(invalid_param) + text = "Someone just completed the task My Beautiful Task" + + response = requests.post(SLACK_POST_MESSAGE_URL, { + 'token': SLACK_BOT_TOKEN, + 'channel': SLACK_POST_MESSAGE_CHANNEL, + 'text': text, + 'username': SLACK_BOT_USERNAME,}) + + task = Task.query.get(task_id) + task.completed_at = datetime.now(timezone.utc) + db.session.commit() + print(response.text) + return task.make_dict_response(200) + +@tasks_bp.route("//mark_incomplete", methods=["PATCH"]) +def mark_parameter_incomplete(task_id): + invalid_param = is_parameter_valid(task_id, Task) + if invalid_param: + return make_response(invalid_param) + task = Task.query.get(task_id) + task.completed_at = None + db.session.commit() + return task.make_dict_response(200) + +@goals_bp.route("",methods=["GET"]) +@tasks_bp.route("",methods=["GET"]) +def get_all_tasks_or_goals(): + mdl = model_select(request.url) + sort_query = request.args.get("sort") + if sort_query: + if "asc" in sort_query: + models = mdl.query.order_by(mdl.title).all() + if "desc" in sort_query: + models = mdl.query.order_by(mdl.title.desc()).all() + else: + models = mdl.query.all() + models_response = [] + + for mdl in models: + try: + models_response.append({ + "id": mdl.get_id(), + "title": mdl.title, + "description": mdl.description, + "is_complete": mdl.is_complete(), + }) + except AttributeError: + models_response.append({ + "id": mdl.get_id(), + "title": mdl.title, + }) + return (jsonify(models_response), 200) + +@goals_bp.route("/", methods=["GET"]) +@tasks_bp.route("/", methods=["GET"]) +def get_one_task_or_goal(task_id=None, goal_id=None): + if task_id: + invalid_param = is_parameter_valid(task_id, Task) + if invalid_param: + return make_response(invalid_param) + obj = Task.query.get(task_id) + if obj.goal_id: + return {"task":{ + "id": obj.task_id, + "goal_id": obj.goal_id, + "title": obj.title, + "description": obj.description, + "is_complete": obj.is_complete(), + }} + + if goal_id: + invalid_param = is_parameter_valid(goal_id, Goal) + if invalid_param: + return invalid_param + obj = Goal.query.get(goal_id) + return obj.make_dict_response(200) + +@goals_bp.route("/",methods=["DELETE"]) +@tasks_bp.route("/", methods=["DELETE"]) +def delete_task(task_id=None, goal_id=None): + if task_id: + obj_id = task_id + obj_str = "Task" + if goal_id: + obj_id = goal_id + obj_str = "Goal" + mdl = model_select(request.url) + invalid_param = is_parameter_valid(obj_id, mdl) + if invalid_param: + return invalid_param + obj = mdl.query.get(obj_id) + db.session.delete(obj) + db.session.commit() + + response_body = ({'details' : f'{obj_str} {obj.get_id()} "{obj.title}" successfully deleted'}) + return make_response(response_body, 200) \ No newline at end of file diff --git a/migrations.old/README b/migrations.old/README new file mode 100644 index 000000000..98e4f9c44 --- /dev/null +++ b/migrations.old/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/migrations.old/alembic.ini b/migrations.old/alembic.ini new file mode 100644 index 000000000..f8ed4801f --- /dev/null +++ b/migrations.old/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.old/env.py b/migrations.old/env.py new file mode 100644 index 000000000..8b3fb3353 --- /dev/null +++ b/migrations.old/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.old/script.py.mako b/migrations.old/script.py.mako new file mode 100644 index 000000000..2c0156303 --- /dev/null +++ b/migrations.old/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.old/versions/0a813afaf2f3_.py b/migrations.old/versions/0a813afaf2f3_.py new file mode 100644 index 000000000..85c544706 --- /dev/null +++ b/migrations.old/versions/0a813afaf2f3_.py @@ -0,0 +1,30 @@ +"""empty message + +Revision ID: 0a813afaf2f3 +Revises: 4a065e3df323 +Create Date: 2021-11-07 16:01:43.064205 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '0a813afaf2f3' +down_revision = '4a065e3df323' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('task', sa.Column('goal_id', sa.Integer(), nullable=True)) + op.create_foreign_key(None, 'task', 'goal', ['goal_id'], ['goal_id']) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_constraint(None, 'task', type_='foreignkey') + op.drop_column('task', 'goal_id') + # ### end Alembic commands ### diff --git a/migrations.old/versions/2f64eb692c6f_.py b/migrations.old/versions/2f64eb692c6f_.py new file mode 100644 index 000000000..2b3bd1677 --- /dev/null +++ b/migrations.old/versions/2f64eb692c6f_.py @@ -0,0 +1,39 @@ +"""empty message + +Revision ID: 2f64eb692c6f +Revises: +Create Date: 2021-10-29 10:26:45.443908 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '2f64eb692c6f' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('goal', + sa.Column('goal_id', sa.Integer(), nullable=False), + sa.PrimaryKeyConstraint('goal_id') + ) + op.create_table('task', + sa.Column('task_id', sa.Integer(), nullable=False), + sa.Column('title', sa.String(), nullable=True), + sa.Column('description', sa.String(), nullable=True), + sa.Column('completed_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('task_id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('task') + op.drop_table('goal') + # ### end Alembic commands ### diff --git a/migrations.old/versions/3fba307a87ce_.py b/migrations.old/versions/3fba307a87ce_.py new file mode 100644 index 000000000..737766689 --- /dev/null +++ b/migrations.old/versions/3fba307a87ce_.py @@ -0,0 +1,38 @@ +"""empty message + +Revision ID: 3fba307a87ce +Revises: 2f64eb692c6f +Create Date: 2021-11-03 21:29:58.777573 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '3fba307a87ce' +down_revision = '2f64eb692c6f' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.alter_column('task', 'description', + existing_type=sa.VARCHAR(), + nullable=False) + op.alter_column('task', 'title', + existing_type=sa.VARCHAR(), + nullable=False) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.alter_column('task', 'title', + existing_type=sa.VARCHAR(), + nullable=True) + op.alter_column('task', 'description', + existing_type=sa.VARCHAR(), + nullable=True) + # ### end Alembic commands ### diff --git a/migrations.old/versions/4a065e3df323_.py b/migrations.old/versions/4a065e3df323_.py new file mode 100644 index 000000000..917bb8675 --- /dev/null +++ b/migrations.old/versions/4a065e3df323_.py @@ -0,0 +1,34 @@ +"""empty message + +Revision ID: 4a065e3df323 +Revises: fb31a6d48b69 +Create Date: 2021-11-07 16:00:58.935816 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '4a065e3df323' +down_revision = 'fb31a6d48b69' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('goal', sa.Column('goal_id', sa.Integer(), autoincrement=True, nullable=False)) + op.drop_column('goal', 'identification') + op.add_column('task', sa.Column('task_id', sa.Integer(), autoincrement=True, nullable=False)) + op.drop_column('task', 'identification') + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('task', sa.Column('identification', sa.INTEGER(), autoincrement=False, nullable=False)) + op.drop_column('task', 'task_id') + op.add_column('goal', sa.Column('identification', sa.INTEGER(), autoincrement=False, nullable=False)) + op.drop_column('goal', 'goal_id') + # ### end Alembic commands ### diff --git a/migrations.old/versions/fb31a6d48b69_.py b/migrations.old/versions/fb31a6d48b69_.py new file mode 100644 index 000000000..29c7e47e5 --- /dev/null +++ b/migrations.old/versions/fb31a6d48b69_.py @@ -0,0 +1,36 @@ +"""empty message + +Revision ID: fb31a6d48b69 +Revises: 3fba307a87ce +Create Date: 2021-11-04 12:09:28.045500 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'fb31a6d48b69' +down_revision = '3fba307a87ce' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('goal', sa.Column('identification', sa.Integer(), nullable=False)) + op.add_column('goal', sa.Column('title', sa.String(), nullable=False)) + op.drop_column('goal', 'goal_id') + op.add_column('task', sa.Column('identification', sa.Integer(), autoincrement=True, nullable=False)) + op.drop_column('task', 'task_id') + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('task', sa.Column('task_id', sa.INTEGER(), autoincrement=True, nullable=False)) + op.drop_column('task', 'identification') + op.add_column('goal', sa.Column('goal_id', sa.INTEGER(), autoincrement=True, nullable=False)) + op.drop_column('goal', 'title') + op.drop_column('goal', 'identification') + # ### end Alembic commands ### 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/85692897656f_recreates_databases.py b/migrations/versions/85692897656f_recreates_databases.py new file mode 100644 index 000000000..22bd03c63 --- /dev/null +++ b/migrations/versions/85692897656f_recreates_databases.py @@ -0,0 +1,42 @@ +"""recreates databases + +Revision ID: 85692897656f +Revises: +Create Date: 2021-11-07 16:14:17.848351 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '85692897656f' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('goal', + sa.Column('goal_id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('title', sa.String(), nullable=False), + sa.PrimaryKeyConstraint('goal_id') + ) + op.create_table('task', + sa.Column('task_id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('title', sa.String(), nullable=False), + sa.Column('description', sa.String(), nullable=False), + sa.Column('completed_at', sa.DateTime(), nullable=True), + sa.Column('goal_id', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['goal_id'], ['goal.goal_id'], ), + sa.PrimaryKeyConstraint('task_id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('task') + op.drop_table('goal') + # ### end Alembic commands ### diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index 6ba60c6fa..a7b325d17 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -1,4 +1,5 @@ import pytest +from app.models.goal import Goal def test_get_goals_no_saved_goals(client): # Act @@ -9,8 +10,8 @@ def test_get_goals_no_saved_goals(client): assert response.status_code == 200 assert response_body == [] - def test_get_goals_one_saved_goal(client, one_goal): + # Act response = client.get("/goals") response_body = response.get_json() @@ -41,17 +42,15 @@ def test_get_goal(client, one_goal): } } -@pytest.mark.skip(reason="test to be completed by student") def test_get_goal_not_found(client): - pass # Act response = client.get("/goals/1") response_body = response.get_json() # Assert # ---- Complete Test ---- - # assertion 1 goes here - # assertion 2 goes here + assert response.status_code == 404 + assert response_body == None # ---- Complete Test ---- def test_create_goal(client): @@ -71,30 +70,33 @@ def test_create_goal(client): } } -@pytest.mark.skip(reason="test to be completed by student") def test_update_goal(client, one_goal): - pass # Act - # ---- Complete Act Here ---- + response = client.put("/goals/1", json={ + "title": "That'll never happen" + }) + response_body = response.get_json() # Assert # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # assertion 3 goes here + assert response.status_code == 200 + assert response_body == {"goal" : { + "id": 1, + "title": "That'll never happen", + }}, 200 + assert len(response_body) == 1 # ---- Complete Assertions Here ---- -@pytest.mark.skip(reason="test to be completed by student") def test_update_goal_not_found(client): - pass # Act - # ---- Complete Act Here ---- + response = client.put("/goals/1", json={ + "title": "Updated Goal Title", + }) + response_body = response.get_json() # Assert - # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # ---- Complete Assertions Here ---- + assert response.status_code == 404 + assert response_body == None def test_delete_goal(client, one_goal): @@ -113,18 +115,16 @@ def test_delete_goal(client, one_goal): response = client.get("/goals/1") assert response.status_code == 404 -@pytest.mark.skip(reason="test to be completed by student") +#@pytest.mark.skip(reason="test to be completed by student") def test_delete_goal_not_found(client): - pass - # Act - # ---- Complete Act Here ---- + response = client.delete("/goals/1") + response_body = response.get_json() # Assert - # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # ---- Complete Assertions Here ---- + assert response.status_code == 404 + assert response_body == None + assert Goal.query.all() == [] def test_create_goal_missing_title(client):