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

Sharks inspir-adies - Kassidy B., Gricelda M., Lauren K., Camilla #30

Open
wants to merge 12 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
14 changes: 11 additions & 3 deletions app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,23 @@ def create_app():
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get(
"SQLALCHEMY_DATABASE_URI")

# might not need?
app.config['CORS_HEADERS'] = 'Content-Type'
# 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 import example_bp
# app.register_blueprint(example_bp)

from app.routes.board_routes import boards_bp
app.register_blueprint(boards_bp)

from app.routes.card_routes import cards_bp
app.register_blueprint(cards_bp)

CORS(app)
return app
34 changes: 34 additions & 0 deletions app/models/board.py
Original file line number Diff line number Diff line change
@@ -1 +1,35 @@
from app import db
from flask import make_response, abort, request
from .card import Card

class Board(db.Model):
board_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
title= db.Column(db.String, nullable=False)
owner = db.Column(db.String, nullable=False)
cards = db.relationship("Card", back_populates = "board", lazy = True)

def to_json(self):

return {"boardId" : self.board_id,
"title" : self.title,
"owner": self.owner}

def link_card_to_board(self, request_body):

new_card = Card.from_json(request_body)
if new_card not in self.cards:
self.cards.append(new_card)

return new_card

@classmethod
def from_json(cls, request_body):

if "title" not in request_body or "owner" not in request_body:
abort(make_response({"details": "Invalid data"}, 400))

new_board = cls(
title=request_body["title"],
owner=request_body["owner"])

return new_board
36 changes: 36 additions & 0 deletions app/models/card.py
Original file line number Diff line number Diff line change
@@ -1 +1,37 @@
from app import db
from flask import make_response, abort

class Card (db.Model):
card_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
message= db.Column(db.String, nullable=False)
likes_count = db.Column(db.Integer, nullable=False)
board_id = db.Column(db.Integer, db.ForeignKey('board.board_id'), nullable=True)
board = db.relationship("Board", back_populates="cards")


def to_json(self):
return {"cardId" : self.card_id,
"message" : self.message,
"likesCount": self.likes_count,
"boardId": self.board_id}

def update_card(self, update_body):

# self.card_id = update_body["cardId"]
# self.message = update_body["message"]
self.likes_count = update_body["likesCount"]
# self.board_id = update_body["boardId"]

@classmethod
def from_json(cls, request_body):

if len(request_body["message"]) > 40:
abort(make_response({"details": "Message is too long"}, 400))

new_card = cls(
message=request_body["message"],
likes_count = request_body["likesCount"],
board_id = request_body["boardId"],
)

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

This file was deleted.

Empty file added app/routes/__init__.py
Empty file.
76 changes: 76 additions & 0 deletions app/routes/board_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
from flask import Blueprint, request, jsonify, make_response
from app import db
from app.models.board import Board
from .helpers import validate_model_instance, send_slack_new_card_message
from app.models.card import Card

# example_bp = Blueprint('example_bp', __name__)

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

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

new_board = Board.from_json(request_body)

db.session.add(new_board)
db.session.commit()

return jsonify(new_board.to_json()), 201

#GET all boards
@boards_bp.route("", methods=["GET"])
def read_board():
Boards = Board.query.all()

boards_response = [board.to_json() for board in Boards]

return jsonify(boards_response), 200

#GET one board
@boards_bp.route("/<board_id>", methods=["GET"])
def get_one_board(board_id):
board = validate_model_instance(Board, board_id, "board")
return jsonify(board.to_json()), 200

#DELETE A BOARD-> optional
@boards_bp.route("/<board_id>", methods=["DELETE"])
def delete_board(board_id):
board = validate_model_instance(Board, board_id, "board")
db.session.delete(board)
db.session.commit()

return jsonify({"details":f'Board {board_id} "{board.title}" successfully deleted'} ), 200

#POST /boards/<board_id>/cards
#we expect-> HTTP request body ({message, likesCount, boardId})
@boards_bp.route("/<board_id>/cards", methods=["POST"])
def add_card_to_board(board_id):
board = validate_model_instance(Board, board_id, "board")

request_body = request.get_json()

new_card = board.link_card_to_board(request_body)

db.session.add(new_card)
db.session.commit()
send_slack_new_card_message(new_card)
#change return?
return jsonify(new_card.to_json()), 200

#GET /boards/<board_id>/cards
@boards_bp.route("/<board_id>/cards", methods=["GET"])
def read_cards_of_board(board_id):

board = validate_model_instance(Board, board_id, "board")
board_cards = [card.to_json() for card in board.cards]

return jsonify({"boardId": board.board_id,
"title": board.title,
"owner": board.owner,
"cards": board_cards}), 200



32 changes: 32 additions & 0 deletions app/routes/card_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from flask import Blueprint, request, jsonify, make_response
from app import db
from app.models.card import Card
from .helpers import validate_model_instance

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


# DELETE /cards/<card_id>
@cards_bp.route("/<card_id>", methods=["DELETE"])
def delete_card(card_id):
card = validate_model_instance(Card, card_id, "card")
db.session.delete(card)
db.session.commit()

return jsonify({"details":f'Card {card_id} "{card.message}" successfully deleted'} ), 200

# PUT /cards/<card_id>/like
# request body from front-end-> whole object of attributes
# ? change syntax
@cards_bp.route("/<card_id>/like", methods=["PUT"])
def update_one_card(card_id):
card = validate_model_instance(Card, card_id, "card")
request_body = request.get_json()

card.update_card(request_body)

db.session.commit()

return jsonify(card.to_json()), 200


27 changes: 27 additions & 0 deletions app/routes/helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from flask import abort, make_response
import requests
import os

def validate_model_instance(cls, model_id, class_name_string):
try:
model_id = int(model_id)
except:
abort(make_response({"message":f"{class_name_string} {model_id} invalid"}, 400))

model = cls.query.get(model_id)
if not model:
return abort(make_response({"message":f"{class_name_string} {model_id} not found"}, 404))

return model

def send_slack_new_card_message(new_card):

PATH = "https://slack.com/api/chat.postMessage"

BEARER_TOKEN = os.environ.get(
"AUTH_TOKEN_SLACK")

query_params = {"channel" : "inspir-adies", "text": f"Someone just created the card with the message '{new_card.message}'" }
headers = {"authorization" : BEARER_TOKEN}

response_body = requests.get(PATH, params=query_params, headers=headers)
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