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

Rock - Brittany|Juliana|Leilani|Mai #12

Open
wants to merge 15 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
18 changes: 14 additions & 4 deletions app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,32 @@
load_dotenv()


def create_app():
def create_app(test_config=None):
app = Flask(__name__)
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get(
"SQLALCHEMY_DATABASE_URI")
app.url_map.strict_slashes = False

if test_config is None:
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")

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

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

# Register Blueprints here
# from .routes import example_bp
# app.register_blueprint(example_bp)
from .routes import boards_bp
app.register_blueprint(boards_bp)

CORS(app)
return app
23 changes: 23 additions & 0 deletions app/models/board.py
Original file line number Diff line number Diff line change
@@ -1 +1,24 @@
from app import db
from app.models.card import Card
class Board(db.Model):
board_id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String)
owner = db.Column(db.String)

cards = db.relationship("Card", lazy=True, cascade="all, delete")


def as_dict(self):
return {
"board_id": self.board_id,
"title": self.title,
"owner": self.owner,
}

def as_dict_with_cards(self):
return {
"board_id": self.board_id,
"title": self.title,
"owner": self.owner,
"cards": [card.as_dict() for card in self.cards]
}
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)
message = db.Column(db.String)
likes_count = db.Column(db.Integer, default=0)

board_id = db.Column(db.Integer, db.ForeignKey('board.board_id'))
#created helper function below for jsonify display

def as_dict(self):
return {
"card_id": self.card_id,
"message": self.message,
"likes_count": self.likes_count,
"board_id": self.board_id
}
166 changes: 166 additions & 0 deletions app/routes.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,170 @@
from flask import Blueprint, request, jsonify, make_response
from dotenv import load_dotenv

import os
import requests

from app import db
from app.models.card import Card
from app.models.board import Board


# added Bluerprint and one to many relationships between models

# example_bp = Blueprint('example_bp', __name__)
boards_bp = Blueprint("boards", __name__, url_prefix="/boards")
load_dotenv()

@boards_bp.route("", methods=["GET"])
def list_all_boards():
boards_response = [board.as_dict() for board in Board.query.all()]
return jsonify(boards_response)


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

if invalid_board_post_request_body(request_body):
return make_response({"details": "Missing required data"}, 400)

board = Board(title=request_body["title"], owner=request_body["owner"])

db.session.add(board)
db.session.commit()

return make_response({"id": board.board_id}, 201)


def invalid_board_post_request_body(request_body):
if ("title" not in request_body or "owner" not in request_body):
return True
return False


@boards_bp.route("/<int:board_id>", methods=["GET"])
def get_board_by_id(board_id):
board = Board.query.get_or_404(board_id)
return jsonify(board.as_dict_with_cards())


@boards_bp.route("/<int:board_id>", methods=["PUT"])
def update_board(board_id):
board = Board.query.get_or_404(board_id)

request_body = request.get_json()
if invalid_board_post_request_body(request_body):
return make_response({"details": "Missing required data"}, 400)

board.title = request_body["title"]
board.owner = request_body["owner"]

db.session.add(board)
db.session.commit()

return make_response(board.as_dict(), 200)


@boards_bp.route("/<int:board_id>", methods=["DELETE"])
def delete_board(board_id):
board = Board.query.get_or_404(board_id)

db.session.delete(board)
db.session.commit()
return make_response(
jsonify(
details=f"board \"{board.title}\" successfully deleted", id=board.board_id),
200)


# Handling CARDS


@boards_bp.route("/<int:board_id>/cards", methods=["GET"])
def get_rentals_by_board(board_id):
board = Board.query.get_or_404(board_id)

cards = [card.as_dict() for card in board.cards]

return make_response(jsonify(cards), 200)


@boards_bp.route("/<int:board_id>/cards", methods=["POST"])
def create_card(board_id):
request_body = request.get_json()
board = Board.query.get_or_404(board_id)

if invalid_card_post_request_body(request_body):
return make_response({"details": "Missing required data"}, 400)

card = Card(message=request_body["message"], board_id=board_id)

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

send_slack_card_notification(card, board)

return make_response({"id": card.card_id}, 201)


def invalid_card_post_request_body(request_body):

if ("message" not in request_body):
return True
return False


@boards_bp.route("/increase_likes/<int:card_id>", methods=["POST"])
def increase_likes(card_id):

card = Card.query.get_or_404(card_id)

card.likes_count += 1
db.session.add(card)
db.session.commit()

return make_response({"id": card.card_id}, 200)


@boards_bp.route("/decrease_likes/<int:card_id>", methods=["POST"])
def decrease_likes(card_id):

card = Card.query.get_or_404(card_id)

card.likes_count -= 1
db.session.add(card)
db.session.commit()

return make_response({"id": card.card_id}, 200)


@boards_bp.route("/delete_card/<int:card_id>", methods=["DELETE"])
def delete_card(card_id):
card = Card.query.get_or_404(card_id)

db.session.delete(card)
db.session.commit()
return make_response(
jsonify(
details=f"card \"{card.message}\" successfully deleted", id=card.card_id),
200)


def send_slack_card_notification(card, board):
"""
Sends a request to a slack bot to post the
to the ice-ice-baby channel
in the configured slack workspace
"""
SLACK_BOT_TOKEN = os.environ.get("SLACK_BOT_TOKEN")
text = f"📝 Someone just created a new card on the *<{board.title}>* board!! Take a look at http://ice-ice-inspo-board.herokuapp.com/ \n ```{card.message}``` \n "
url = f"https://slack.com/api/chat.postMessage?channel=ice-ice-baby&text={text}"

payload = ""

headers = {
'Authorization': f'Bearer {SLACK_BOT_TOKEN}'
}

response = requests.request("POST", url, headers=headers, data=payload)
return response
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