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

S18 Lions Team 9 - Milena, Laura, Yang, Carina #24

Open
wants to merge 25 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
1e10f11
initialized database and created model files
checarina Dec 23, 2022
15a946b
imported models to App
checarina Dec 23, 2022
6d6b236
created initial migrations
checarina Dec 24, 2022
672c72c
new board and card models
checarina Jan 3, 2023
e5249aa
created GET and POST routes for Board
checarina Jan 3, 2023
b6628b7
fixed routes module bug
checarina Jan 6, 2023
380de1d
added get one baord, delete board endpoints
checarina Jan 6, 2023
dd0af15
created GET and POST routes for cards
checarina Jan 6, 2023
b7e1d8c
added update and delete routes for Card
checarina Jan 17, 2023
1969ba1
added one-to-many Board-Card relationship
checarina Jan 17, 2023
f3d6f7e
modified routes to create and read cards for specific board
checarina Jan 17, 2023
bf7ddad
updated board and card routes to check for valid input
checarina Jan 17, 2023
9e99144
misc changes
checarina Jan 17, 2023
6bab134
update database add board_id and UPDATE heart data work
guaiguaiyang Jan 18, 2023
ab4cf2f
modified route to get all cards for one board
checarina Jan 18, 2023
b3175b4
pull down code
guaiguaiyang Jan 18, 2023
f3a9e30
Merge branch 'main' of https://github.com/checarina/back-end-inspirat…
guaiguaiyang Jan 18, 2023
7e4a888
moved route to create new card from card_routes to board_routes
checarina Jan 18, 2023
a0709f5
Merge branch 'main' of https://github.com/checarina/back-end-inspirat…
checarina Jan 18, 2023
cf69da6
pull down cheack
guaiguaiyang Jan 18, 2023
78d7b79
update delete card route
checarina Jan 18, 2023
01d27cc
delete check
guaiguaiyang Jan 18, 2023
f087427
check delete
guaiguaiyang Jan 18, 2023
6c15987
cleanup
checarina Jan 18, 2023
2f47eb8
fixed card id thingy
checarina Jan 19, 2023
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
7 changes: 7 additions & 0 deletions app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,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 import example_bp
# app.register_blueprint(example_bp)
from .routes.board_routes import boards_bp
app.register_blueprint(boards_bp)
from .routes.card_routes import cards_bp
app.register_blueprint(cards_bp)

CORS(app)
return app
7 changes: 7 additions & 0 deletions app/models/board.py
Original file line number Diff line number Diff line change
@@ -1 +1,8 @@
from app import db

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", back_populates = "board")
9 changes: 9 additions & 0 deletions app/models/card.py
Original file line number Diff line number Diff line change
@@ -1 +1,10 @@
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)

board_id = db.Column(db.Integer, db.ForeignKey("board.board_id"))
board = db.relationship("Board", back_populates = "cards")

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

This file was deleted.

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

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

# GET endpoint to get all boards
@boards_bp.route("", methods = ["GET"])
def get_all_boards():
boards = Board.query.all()
boards_response = []
for board in boards:
boards_response.append(
{
"board_id": board.board_id,
"title": board.title,
"owner": board.owner
}
)
return jsonify(boards_response)

#GET endpoint to get one board
@boards_bp.route("/<board_id>", methods = ["GET"])
def get_one_board(board_id):
board = Board.query.get(board_id)
return make_response(jsonify(
{
"board_id": board.board_id,
"title": board.title,
"owner": board.owner
}
), 200)

# #GET endpoint to get cards for one board
@boards_bp.route("/<board_id>/cards", methods = ["GET"])
def get_board_cards(board_id):
board = Board.query.get(board_id)
cards_response = []
for card in board.cards:
cards_response.append(
{"card_id": card.card_id,
"message": card.message})
return jsonify(cards_response)

# POST create a new board
@boards_bp.route("", methods = ["POST"])
def create_board():
request_body = request.get_json()
if "title" not in request_body or "owner" not in request_body:
return jsonify({"message": "Title and Owner must be specified."}, 400)
new_board = Board(
title = request_body["title"],
owner = request_body["owner"],
)

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

return make_response(jsonify({"board": new_board.title, "owner": new_board.owner}), 201)

# POST create new card
@boards_bp.route("/<board_id>/cards", methods = ["POST"])
def create_card(board_id):
# board = Board.query.get(board_id)
request_body = request.get_json()

if "message" not in request_body:
return jsonify({"message": "Message cannot be blank!"}, 400)
if len(request_body["message"]) > 40:
return jsonify({"message": "Maximum length 40 characters."}, 400)

new_card = Card(
board_id = board_id,
message = request_body["message"],
likes_count = 0
)

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

return make_response(jsonify({"card": new_card.message}), 201)

# DELETE route
@boards_bp.route("/<board_id>", methods = ["DELETE"])
def delete_board(board_id):
board = Board.query.get(board_id)
db.session.delete(board)
db.session.commit()

return make_response(jsonify({"msg": "board successfully deleted"}), 200)
50 changes: 50 additions & 0 deletions app/routes/card_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from flask import Blueprint, request, jsonify, make_response
from app import db
from app.models.card import Card
from app.models.board import Board

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

# GET all cards
@cards_bp.route("", methods = ["GET"])
def get_all_cards():
cards = Card.query.all()
cards_response = []
for card in cards:
cards_response.append(
{
"card_id": card.card_id,
"message": card.message,
"likes": card.likes_count,
"board_id": card.board_id
}
)
return jsonify(cards_response)

# UPDATE heart count on a card
@cards_bp.route("/<card_id>", methods = ["PUT"])
def update_likes(card_id):
card = Card.query.get(card_id)
request_body = request.get_json()
card.likes_count = request_body["likes_count"]

db.session.commit()

return make_response(f"Card #{card_id} successfully updated")

#Delete
@cards_bp.route("/<card_id>", methods = ["DELETE"])
def delete_card(card_id):
card = Card.query.get(card_id)
db.session.delete(card)
db.session.commit()
return make_response(f"Card #{card_id} successfully deleted", 200)

# Delete all cards
@cards_bp.route("", methods = ["DELETE"])
def delete_all_cards():
cards = Card.query.all()
for card in cards:
db.session.delete(card)
db.session.commit()
return make_response("All cards successfully deleted")
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"}
30 changes: 30 additions & 0 deletions migrations/versions/4c97697a1e3d_.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"""empty message

Revision ID: 4c97697a1e3d
Revises: b24701033da7
Create Date: 2023-01-17 14:13:12.321524

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '4c97697a1e3d'
down_revision = 'b24701033da7'
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('card', sa.Column('board_id', sa.Integer(), nullable=True))
op.create_foreign_key(None, 'card', 'board', ['board_id'], ['board_id'])
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, 'card', type_='foreignkey')
op.drop_column('card', 'board_id')
# ### end Alembic commands ###
Loading