Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lions - Mean Girls 2004 - Nancy, Ivy, Devin, Max #13

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,19 @@ def create_app():

# Import models here for Alembic setup
# from app.models.ExampleModel import ExampleModel
from app.models.board import Board
from app.models.card import Card

db.init_app(app)
migrate.init_app(app, db)

# Register Blueprints here
from .routes.cards_routes import card_bp
app.register_blueprint(card_bp)
# from .routes import example_bp
# app.register_blueprint(example_bp)
from .routes.boards_routes import board_bp
app.register_blueprint(board_bp)

CORS(app)
return app
16 changes: 16 additions & 0 deletions app/models/board.py
Original file line number Diff line number Diff line change
@@ -1 +1,17 @@
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", backref="board", lazy=True)

def create_board_dict(self):

new_dict = {
"board_id": self.board_id,
"title": self.title,
"owner": self.owner,
}

return new_dict
16 changes: 16 additions & 0 deletions app/models/card.py
Original file line number Diff line number Diff line change
@@ -1 +1,17 @@
from app import db

class Card(db.Model):
card_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
message = db.Column(db.VARCHAR(40))
likes_count = db.Column(db.Integer, default=0)
board_id = db.Column(db.Integer, db.ForeignKey('board.board_id'), nullable=True)

def create_dict(self):

new_dict = {
"card_id": self.card_id,
"message": self.message,
"likes_count": self.likes_count
}

return new_dict
4 changes: 0 additions & 4 deletions app/routes.py

This file was deleted.

Empty file added app/routes/__init__.py
Empty file.
87 changes: 87 additions & 0 deletions app/routes/boards_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
from flask import Blueprint, jsonify, request
from app import db
from app.models.board import Board
from app.models.card import Card
from .helper_functions import get_one_obj_or_abort
import os

board_bp = Blueprint("board_bp", __name__, url_prefix="/boards")

#----------------------------------POST------------------------------
@board_bp.route("",methods=["POST"])
def add_board():
request_body = request.get_json()

if "title" not in request_body or "owner" not in request_body:
return jsonify({"details": "invalid data"}), 400

new_board = Board(
title = request_body["title"],
owner = request_body["owner"],
)
db.session.add(new_board)
db.session.commit()

return jsonify({"board": f"{new_board.title} created"}), 201

#--------------------------------GET---------------------------------
@board_bp.route("", methods=["GET"])
def get_all_boards():

boards = Board.query.all()

response = [board.create_board_dict() for board in boards]

return jsonify(response), 200

@board_bp.route("/<board_id>", methods=["GET"])
def get_one_board(board_id):
board = get_one_obj_or_abort(Board, board_id)

return jsonify({"board": board.create_board_dict()}), 200

#------------------------GET CARDS-------------------------------

@board_bp.route("/<board_id>/cards", methods=["GET"])
def get_cards_from_board(board_id):
board = get_one_obj_or_abort(Board, board_id)

response = [card.create_dict() for card in board.cards]

board_dict = {
"board_id": board.board_id,
"title": board.title,
"owner": board.owner,
"cards": response
}

return jsonify(board_dict), 200

#------------------------POST CARDS--------------------------------

@board_bp.route("/<board_id>/cards", methods=["POST"])
def post_card_to_board(board_id):
board = get_one_obj_or_abort(Board, board_id)

request_body = request.get_json()

for card_id in request_body["card_ids"]:
card = get_one_obj_or_abort(Card, card_id)

card.board_id = board_id

db.session.add(card)
db.session.commit()

return jsonify({"Card with card id": request_body["card_ids"], "Linked to board id": board.board_id}), 200

#---------------------DELETE-------------------------------

@board_bp.route("/<board_id>", methods=["DELETE"])
def delete_one_board(board_id):
board = get_one_obj_or_abort(Board, board_id)

db.session.delete(board)
db.session.commit()

return jsonify({"details": f"Board id: {board_id} was deleted"}), 200
66 changes: 66 additions & 0 deletions app/routes/cards_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
from flask import Blueprint, jsonify, request, make_response
from app import db
from app.models.card import Card
from .helper_functions import get_one_obj_or_abort
import os

card_bp = Blueprint("card_bp", __name__, url_prefix="/cards")

#------------------------POST------------------------------

@card_bp.route("", methods=["POST"])
def add_card():
request_body = request.get_json()

if "message" not in request_body:
return jsonify({"details": "Must have a message"}), 400

if len(request_body["message"]) > 40:
return jsonify({"details": "Message must be 40 characters or less"}), 400

new_card = Card(
message = request_body["message"]
)

db.session.add(new_card)
db.session.commit()

print(new_card)
return jsonify({"message": new_card.create_dict()}), 201

#----------------------GET--------------------------------

@card_bp.route("", methods=["GET"])
def get_all_cards():

cards = Card.query.all()

response = [card.create_dict() for card in cards]

return jsonify(response), 200

@card_bp.route("/<card_id>", methods=["GET"])
def get_one_card(card_id):
card = get_one_obj_or_abort(Card, card_id)

return jsonify({"card": card.create_dict()}), 200

#---------------------DELETE-------------------------------

@card_bp.route("/<card_id>", methods=["DELETE"])
def delete_one_card(card_id):
card = get_one_obj_or_abort(Card, card_id)

db.session.delete(card)
db.session.commit()

return jsonify({"details": f"Card id: {card_id} was deleted"}), 200

#---------------------PATCH---------------------------------
@card_bp.route("/<card_id>", methods=["PATCH"])
def update_likes(card_id):
card = get_one_obj_or_abort(Card, card_id)
card.likes_count += 1

db.session.commit()
return jsonify({"liked": card.create_dict()})
16 changes: 16 additions & 0 deletions app/routes/helper_functions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from flask import jsonify, abort, make_response

def get_one_obj_or_abort(cls, id):
try:
id = int(id)
except ValueError:
response = f"ID must be an integer. '{id}' not valid"
abort(make_response(jsonify({"msg": response}), 400))

obj = cls.query.get(id)

if not obj:
response = f"{cls.__name__} with ID {id} not found"
abort(make_response(jsonify({"msg": response}), 404))

return obj
1 change: 1 addition & 0 deletions migrations/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Generic single-database configuration.
45 changes: 45 additions & 0 deletions migrations/alembic.ini
Original file line number Diff line number Diff line change
@@ -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
96 changes: 96 additions & 0 deletions migrations/env.py
Original file line number Diff line number Diff line change
@@ -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()
Loading