diff --git a/app/__init__.py b/app/__init__.py index 1c821436..693beb0b 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -13,9 +13,10 @@ def create_app(): app = Flask(__name__) app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False - + CORS(app) + app.config["CORS_HEADERS"] = "Content-Type" app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( - "SQLALCHEMY_DATABASE_URI") + "RENDER_DATABASE_URI") # Import models here for Alembic setup # from app.models.ExampleModel import ExampleModel @@ -25,7 +26,18 @@ def create_app(): # Register Blueprints here # from .routes import example_bp + from app.routes.board_routes import board_bp + from app.routes.card_routes import card_bp + from app.routes.user_routes import user_bp + + app.register_blueprint(board_bp) + app.register_blueprint(card_bp) + app.register_blueprint(user_bp) + # app.register_blueprint(example_bp) - CORS(app) + from app.models.card import Card + from app.models.board import Board + from app.models.user import User + return app diff --git a/app/models/board.py b/app/models/board.py index 147eb748..9ac0af21 100644 --- a/app/models/board.py +++ b/app/models/board.py @@ -1 +1,24 @@ from app import db + +class Board(db.Model): + board_id = db.Column(db.Integer, primary_key=True, autoincrement=True) + title = db.Column(db.String) + owner = db.Column(db.String) + cards = db.relationship("Card", back_populates="board") + + @classmethod + # data to give that will be organized into a dict + def from_dict(cls, board_data): + new_board = Board( + title=board_data["title"], + owner=board_data["owner"] + ) + return new_board + + # turn response into dict, using this on an object + def to_dict(self): + return { + "board_id": self.board_id, + "title": self.title, + "owner": self.owner + } \ No newline at end of file diff --git a/app/models/card.py b/app/models/card.py index 147eb748..868deb62 100644 --- a/app/models/card.py +++ b/app/models/card.py @@ -1 +1,27 @@ from app import db + +class Card(db.Model): + card_id = db.Column(db.Integer, primary_key=True, autoincrement=True) + message = db.Column(db.String) + liked_count = db.Column(db.Integer) + board = db.relationship("Board", back_populates="cards") + board_fk = db.Column(db.Integer, db.ForeignKey('board.board_id')) + + + @classmethod + def from_dict(cls, card_data): + new_card = Card( + message = card_data["message"], + liked_count = card_data["liked_count"] + ) + + return new_card + + + def to_dict(self): + return { + "card_id": self.card_id, + "message": self.message, + "liked_count": self.liked_count, + "board_id": self.board_fk + } \ No newline at end of file diff --git a/app/models/user.py b/app/models/user.py new file mode 100644 index 00000000..c51195ff --- /dev/null +++ b/app/models/user.py @@ -0,0 +1,22 @@ +from app import db + +class User(db.Model): + user_id = db.Column(db.Integer, primary_key=True, autoincrement=True) + username = db.Column(db.String, unique=True, nullable=False) + password = db.Column(db.String, nullable=False) + first_name = db.Column(db.String, nullable=False) + last_name = db.Column(db.String, nullable=False) + + def __init__(self, username, password, first_name, last_name): + self.username = username + self.password = password + self.first_name = first_name + self.last_name = last_name + + def to_dict(self): + return { + "user_id": self.user_id, + "username": self.username, + "first_name": self.first_name, + "last_name": self.last_name + } diff --git a/app/routes.py b/app/routes.py deleted file mode 100644 index 480b8c4b..00000000 --- a/app/routes.py +++ /dev/null @@ -1,4 +0,0 @@ -from flask import Blueprint, request, jsonify, make_response -from app import db - -# example_bp = Blueprint('example_bp', __name__) diff --git a/app/routes/board_routes.py b/app/routes/board_routes.py new file mode 100644 index 00000000..d6154be8 --- /dev/null +++ b/app/routes/board_routes.py @@ -0,0 +1,70 @@ +from flask import Blueprint, request, jsonify, make_response, abort +from app import db +from app.models.board import Board + +board_bp =Blueprint("boards", __name__, url_prefix="/boards" ) + +def validate_model(cls, model_id): + try: + model_id = int(model_id) + except: + abort(make_response({"message": f"{model_id} invalid type ({type(model_id)})"}, 400)) + + model = cls.query.get(model_id) + + if not model: + abort(make_response({"message":f"{model_id} invalid"}, 400)) + + return model + + +# CREATE new board +@board_bp.route("", methods=["POST"]) +def create_new_board(): + request_body = request.get_json() + + # pass in request_body + new_board = Board.from_dict(request_body) + + db.session.add(new_board) + db.session.commit() + + return jsonify(new_board.to_dict()), 201 + + +# READ all boards +@board_bp.route("", methods=["GET"]) +def read_all_boards(): + boards_response = [] + + board_title_query = request.args.get("title") + board_owner_query = request.args.get("owner") + + if board_title_query: + boards = Board.query.filter_by(title=board_title_query) + elif board_owner_query: + boards = Board.query.filter_by(owner=board_owner_query) + else: + boards = Board.query.all() + + for board in boards: + boards_response.append(board.to_dict()) + return jsonify(boards_response) + + +# READ a specific board +@board_bp.route("/", methods=["GET"]) +def read_one_board(board_id): + board = validate_model(Board, board_id) + + return board.to_dict(), 200 + +# DELETE one board +@board_bp.route("/", methods=["DELETE"]) +def delete_one_board(board_id): + board = validate_model(Board, board_id) + + db.session.delete(board) + db.session.commit() + + return make_response(board.to_dict()) \ No newline at end of file diff --git a/app/routes/card_routes.py b/app/routes/card_routes.py new file mode 100644 index 00000000..a351deec --- /dev/null +++ b/app/routes/card_routes.py @@ -0,0 +1,81 @@ +from flask import Blueprint, request, jsonify, make_response, abort +from app import db +from app.models.card import Card +from app.models.board import Board +from app.routes.board_routes import board_bp + + +card_bp = Blueprint("cards", __name__, url_prefix="/cards") +### Validate model ### +def validate_model(cls, model_id): + try: + model_id = int(model_id) + except: + abort(make_response({"message": f"{model_id} is not a valid type ({type(model_id)})"})) + + model = cls.query.get(model_id) + + if not model: + abort(make_response({"message":f"{cls.__name__} {model_id} does not exist"}, 404)) + + return model + + +### Post a new card under a board ### +@board_bp.route("//cards", methods = ["POST"]) +def create_card_by_board_id(board_id): + board = validate_model(Board, board_id) + + request_body = request.get_json() + + new_card = Card( + message=request_body["message"], + liked_count=0, + board=board + ) + + db.session.add(new_card) + db.session.commit() + + return jsonify(new_card.to_dict()), 201 + # we want response to be new_card object with id, message, board, like count + +### Get all cards from a board ### +@board_bp.route("//cards", methods=["GET"]) +def get_all_cards_with_board_id(board_id): + board = validate_model(Board, board_id) + + card_response = [] + + for card in board.cards: + card_response.append(card.to_dict()) + + return jsonify(card_response),200 + + +### Update liked_count by card ### +@card_bp.route('/', methods=['PATCH']) +def update_liked_count(card_id): + card = validate_model(Card, card_id) + + if not card.liked_count: + card.liked_count = 0 + + card.liked_count = card.liked_count + 1 + + db.session.commit() + + return card.to_dict(), 200 + + +### Delete card ### +@card_bp.route("/", methods=["DELETE"]) +def delete_card(card_id): + card = validate_model(Card, card_id) + + db.session.delete(card) + db.session.commit() + + return make_response(f"Card #{card_id} successfully deleted") + + diff --git a/app/routes/user_routes.py b/app/routes/user_routes.py new file mode 100644 index 00000000..e0b8a316 --- /dev/null +++ b/app/routes/user_routes.py @@ -0,0 +1,45 @@ +from flask import Blueprint, request, jsonify, make_response +from app import db +from app.models.user import User + +user_bp = Blueprint("user", __name__, url_prefix="/user") + +@user_bp.route("/login", methods=["POST"]) +def login_user(): + data = request.get_json() + username = data.get("username") + password = data.get("password") + + if not username or not password: + return make_response(jsonify({"message": "Username and password are required."}), 400) + + user = User.query.filter_by(username=username).first() + + if not user or user.password != password: + return make_response(jsonify({"message": "Invalid username or password."}), 401) + + return jsonify({"message": "Login successful.", "user": user.to_dict()}), 200 + + +@user_bp.route("/register", methods=["POST"]) +def register_user(): + data = request.get_json() + username = data.get("username") + password = data.get("password") + first_name = data.get("firstName") + last_name = data.get("lastName") + + if not username or not password or not first_name or not last_name: + return make_response(jsonify({"message": "Username, password, first name, and last name are required."}), 400) + + existing_user = User.query.filter_by(username=username).first() + if existing_user: + return make_response(jsonify({"message": "Username already taken."}), 409) + + new_user = User(username=username, password=password, first_name=first_name, last_name=last_name) + db.session.add(new_user) + db.session.commit() + + return new_user.to_dict(), 201 + + diff --git a/migrations/README b/migrations/README new file mode 100644 index 00000000..98e4f9c4 --- /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 00000000..f8ed4801 --- /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 00000000..8b3fb335 --- /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 00000000..2c015630 --- /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/046b9e416046_.py b/migrations/versions/046b9e416046_.py new file mode 100644 index 00000000..2d7d3b99 --- /dev/null +++ b/migrations/versions/046b9e416046_.py @@ -0,0 +1,36 @@ +"""empty message + +Revision ID: 046b9e416046 +Revises: a380272d886e +Create Date: 2023-07-20 13:36:11.406732 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '046b9e416046' +down_revision = 'a380272d886e' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('user', + sa.Column('user_id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('username', sa.String(), nullable=False), + sa.Column('password', sa.String(), nullable=False), + sa.Column('first_name', sa.String(), nullable=False), + sa.Column('last_name', sa.String(), nullable=False), + sa.PrimaryKeyConstraint('user_id'), + sa.UniqueConstraint('username') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('user') + # ### end Alembic commands ### diff --git a/migrations/versions/a380272d886e_.py b/migrations/versions/a380272d886e_.py new file mode 100644 index 00000000..669c2ae2 --- /dev/null +++ b/migrations/versions/a380272d886e_.py @@ -0,0 +1,42 @@ +"""empty message + +Revision ID: a380272d886e +Revises: +Create Date: 2023-06-27 11:54:50.682456 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'a380272d886e' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('board', + sa.Column('board_id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('title', sa.String(), nullable=True), + sa.Column('owner', sa.String(), nullable=True), + sa.PrimaryKeyConstraint('board_id') + ) + op.create_table('card', + sa.Column('card_id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('message', sa.String(), nullable=True), + sa.Column('liked_count', sa.Integer(), nullable=True), + sa.Column('board_fk', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['board_fk'], ['board.board_id'], ), + sa.PrimaryKeyConstraint('card_id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('card') + op.drop_table('board') + # ### end Alembic commands ### diff --git a/requirements.txt b/requirements.txt index 76f1f000..3b321ee0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,15 +1,22 @@ alembic==1.5.4 -attrs==21.2.0 +attrs==20.3.0 autopep8==1.5.5 +big-O-calculator==0.0.9.8.4 +blinker==1.4 certifi==2020.12.5 chardet==4.0.0 +charset-normalizer==2.0.12 click==7.1.2 +coverage==7.2.5 +exceptiongroup==1.1.1 Flask==1.1.2 -Flask-Cors==3.0.10 +Flask-Cors==4.0.0 Flask-Migrate==2.6.0 Flask-SQLAlchemy==2.4.4 +greenlet==1.1.3 gunicorn==20.1.0 idna==2.10 +importlib-metadata==4.11.3 iniconfig==1.1.1 itsdangerous==1.1.0 Jinja2==2.11.3 @@ -22,6 +29,7 @@ py==1.11.0 pycodestyle==2.6.0 pyparsing==2.4.7 pytest==7.1.1 +pytest-cov==2.12.1 python-dateutil==2.8.1 python-dotenv==0.15.0 python-editor==1.0.4 @@ -29,5 +37,8 @@ requests==2.25.1 six==1.15.0 SQLAlchemy==1.3.23 toml==0.10.2 -urllib3==1.26.4 +tomli==2.0.1 +urllib3==1.26.5 Werkzeug==1.0.1 +wonderwords==2.2.0 +zipp==3.7.0