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

Brooke, Lilly, Lety, Kayla Pine Back End #5

Open
wants to merge 9 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
9 changes: 9 additions & 0 deletions app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import os
from flask_cors import CORS


db = SQLAlchemy()
migrate = Migrate()
load_dotenv()
Expand All @@ -19,6 +20,8 @@ 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)
Expand All @@ -27,5 +30,11 @@ def create_app():
# from .routes import example_bp
# app.register_blueprint(example_bp)

from .routes import board_bp
app.register_blueprint(board_bp)

from .routes import card_bp
app.register_blueprint(card_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):
__tablename__ = 'board'
board_id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(255))
owner = db.Column(db.String(255))
cards = db.relationship('Card', backref='card')

def to_dict(self):
return {
'board_id': self.board_id,
'title': self.title,
'owner': self.owner
}


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

class Card(db.Model):
__tablename__ = "card"
card_id = db.Column(db.Integer, primary_key=True)
message = db.Column(db.String(40))
likes_count = db.Column(db.Integer)
board_id = db.Column(db.Integer, db.ForeignKey('board.board_id'))

def to_dict(self):
return {
'card_id': self.card_id,
'message': self.message,
'likes_count': self.likes_count
}
130 changes: 130 additions & 0 deletions app/routes.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,134 @@
from flask import Blueprint, request, jsonify, make_response
from app import db
from app.models.board import Board
from app.models.card import Card

# example_bp = Blueprint('example_bp', __name__)

board_bp = Blueprint("board", __name__, url_prefix="/boards")
card_bp = Blueprint("card", __name__, url_prefix="/cards")

# Helper function to validate the board request
def validate_board(request_body):
if "title" not in request_body or "owner" not in request_body:
return jsonify({"details": "Request body must include title and author"}), 400

# Board routes:
# Get all Boards
@board_bp.route("", methods=["GET"])
def get_all_boards():
boards = Board.query.all()
board_list = []
for board in boards:
board_list.append(board.to_dict())
return jsonify(board_list), 200

# Get single a single board
@board_bp.route("/<board_id>", methods=["GET"])
def get_single_board(board_id):
board = Board.query.get(board_id)
if board:
return board.to_dict(), 200
else:
return jsonify({"This board does not exist, make a board"}), 404

# Post a board
@board_bp.route("", methods=["POST"])
def create_a_board():
request_body = request.get_json()

validate_board(request_body)

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

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

return jsonify(new_board.to_dict()), 201

# Update a board
@board_bp.route("/<board_id>", methods=["PUT"])
def update_board(board_id):
board_id = int(board_id)
board = Board.query.get(board_id)
form_data = request.get_json()

if board:
board.title = form_data["title"]
board.owner = form_data["owner"]
db.session.commit()
return jsonify(board.to_dict()), 200
else:
return jsonify("Invalid data"), 404

# Delete a board
@board_bp.route("/<board_id>", methods=["DELETE"])
def delete_board(board_id):
board_id = int(board_id)
board = Board.query.get(board_id)

if board:
db.session.delete(board)
db.session.commit()
return jsonify("Board was succesfully deleted"), 200
else:
return jsonify("Board does not exist"), 404

# Card Routes:
# Get cards for board id
@board_bp.route("/<board_id>/cards", methods=["GET"])
def get_cards_for_board(board_id):
board_id = int(board_id)
board = Board.query.get(board_id)
if board:
cards = Card.query.filter_by(board_id=board_id).all()
card_list = []
for card in cards:
card_list.append(card.to_dict())
return jsonify(card_list), 200
else:
return jsonify("Card does not exist!"), 404

# Post a card to a board
@board_bp.route("/<board_id>/cards", methods=["POST"])
def create_card_for_board(board_id):
board_id = int(board_id)
board = Board.query.get(board_id)
if board:
form_data = request.get_json()
new_card = Card(message=form_data["message"],
likes_count=form_data["likes_count"],
board_id=board_id
)
db.session.add(new_card)
db.session.commit()
return jsonify(new_card.to_dict()), 201
else:
return jsonify("Board does not exist!"), 404

# Delete cards
@card_bp.route("/<card_id>", methods=["DELETE"])
def delete_card(card_id):
card_id = int(card_id)
card = Card.query.get(card_id)

if card:
db.session.delete(card)
db.session.commit()
return jsonify("Card was succesfully deleted"), 200
else:
return jsonify("Card does not exist"), 404

# Update a card with likes
@card_bp.route("/<card_id>/like", methods=["PUT"])
def like_card(card_id):
card_id = int(card_id)
card = Card.query.get(card_id)
if card:
card.likes_count += 1
db.session.commit()
return jsonify(card.to_dict()), 200
else:
return jsonify("Card does not exist"), 404
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()
24 changes: 24 additions & 0 deletions migrations/script.py.mako
Original file line number Diff line number Diff line change
@@ -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"}
Loading