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

create a route to view all cards and add a n new card #4

Open
wants to merge 27 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
27cc71b
Completed Back-End Layer Setup
Barbara-Bennett Jun 23, 2023
24f1ffd
switching app.models.board to .card
anclark686 Jun 26, 2023
5d47c18
adding versions
anclark686 Jun 26, 2023
5c4cd06
Adding some scaffolding to avoid conflicts
anclark686 Jun 26, 2023
56ddd00
adding bp
anclark686 Jun 26, 2023
0ca9b8d
adding model imports
anclark686 Jun 26, 2023
221b0da
adding model imports2
anclark686 Jun 26, 2023
5276413
adding route helper
anclark686 Jun 26, 2023
9f4917e
removing my unfinished work
anclark686 Jun 26, 2023
a3f4bdd
adding routes to app
anclark686 Jun 26, 2023
9340c80
Merge pull request #1 from dorl9039/alycia
anclark686 Jun 27, 2023
d39c162
create get_all_boards route
dorl9039 Jun 27, 2023
4f53e31
adding add_like route
anclark686 Jun 28, 2023
ea7e22b
Merge pull request #2 from dorl9039/doris
dorl9039 Jun 28, 2023
8af1791
update create_app with test_config conditional
dorl9039 Jun 28, 2023
fb9a6a8
create delete card route
dorl9039 Jun 28, 2023
51184fb
create new board route
Barbara-Bennett Jun 28, 2023
49e45fe
Merge branch 'main' into barbara
Barbara-Bennett Jun 28, 2023
12264a4
changed create new board route
Barbara-Bennett Jun 28, 2023
26ed06c
Merge pull request #3 from dorl9039/barbara
Barbara-Bennett Jun 28, 2023
1788c45
Merge pull request #4 from dorl9039/alycia
anclark686 Jun 28, 2023
3c7c2ee
create delete card route
dorl9039 Jun 28, 2023
f9f5fe1
connect Board and Card models
dorl9039 Jun 28, 2023
1b83cbe
Merge branch 'main' into doris
dorl9039 Jun 29, 2023
ab34f93
Merge pull request #5 from dorl9039/doris
dorl9039 Jun 29, 2023
c51e735
create a route to view all cards and add a nnew card
DQLIU1995 Jun 30, 2023
92abaf1
delete print statement
DQLIU1995 Jun 30, 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
17 changes: 14 additions & 3 deletions app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,33 @@
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(
if test_config:
app.config["TESTING"] = True
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get(
"SQLALCHEMY_TEST_DATABASE_URI")
else:
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get(
"SQLALCHEMY_DATABASE_URI")

# 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 board_bp
app.register_blueprint(board_bp)

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

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


def to_dict(self):
board_data = {
"board_id": self.board_id,
"title": self.title,
"owner": self.owner
}
if self.cards:
board_data["cards"] = [card.to_dict() for card in self.cards]
return board_data

@classmethod
def from_dict(cls, board_data):
new_board = Board(
title=board_data["title"],
owner=board_data["owner"]
)
return new_board

29 changes: 29 additions & 0 deletions app/models/card.py
Original file line number Diff line number Diff line change
@@ -1 +1,30 @@
from app import db
from .board import Board
from app.routes.routes_helpers import validate_model

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


def to_dict(self):
card_data = {
"card_id": self.card_id,
"message": self.message,
"likes_count": self.likes_count
}
if self.board:
card_data["board_id"] = self.board_id
return card_data

@classmethod
def from_dict(cls, card_data):
new_card = Card(
message=card_data["message"],
likes_count=card_data["likes_count"],
board=validate_model(Board, card_data.get("board_id"))
)
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.
26 changes: 26 additions & 0 deletions app/routes/board_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from flask import Blueprint, request, jsonify, make_response, abort
from app import db
from app.models.board import Board
from .routes_helpers import validate_model

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

@board_bp.route("", methods=["GET"])
def get_all_boards():
boards = Board.query.all()
boards_response = [board.to_dict() for board in boards]
return make_response(jsonify(boards_response), 200)

@board_bp.route("", methods=["POST"])
def create_board():
request_body = request.get_json()
try:
new_board = Board.from_dict(request_body)
except KeyError:
abort(make_response(jsonify({"details": "Invalid data"}), 400))

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

return make_response(jsonify(new_board.to_dict()), 201)
48 changes: 48 additions & 0 deletions app/routes/card_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from flask import Blueprint, request, jsonify, make_response, abort
from app import db
from app.models.card import Card
from .routes_helpers import validate_model

# example_bp = Blueprint('example_bp', __name__)
card_bp = Blueprint("cards", __name__, url_prefix="/cards")


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

db.session.delete(card)
db.session.commit()
return make_response(jsonify({"details": f'Card {card.card_id} successfully deleted'}), 200)

# ADD LIKE TO CARD
@card_bp.route("/<id>/add_like", methods=["PATCH"])
def add_like(id):
card = validate_model(Card, id)

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

return make_response(jsonify({"card like count": card.likes_count}), 200)

# create a route to add new card for selected board
@card_bp.route("", methods=["POST"])
def create_card():
request_body = request.get_json()

try:
new_card = Card.from_dict(request_body)
except KeyError:
abort(make_response(jsonify({"details": "Invalid data"}), 400))

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

return make_response(jsonify(new_card.to_dict()), 201)

# create a route to view all cards for selected board
@card_bp.route("", methods=["GET"])
def get_all_cards():
cards = Card.query.all()
cards_response = [card.to_dict() for card in cards]
return make_response(jsonify(cards_response), 200)
15 changes: 15 additions & 0 deletions app/routes/routes_helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from flask import abort, make_response


def validate_model(cls, id):
try:
id = int(id)
except:
abort(make_response({"message": f"{id} is invalid"}, 400))

model = cls.query.get(id)

if not model:
abort(make_response({"message": f"{cls.__name__} with id {id} was not found."}, 404))

return model
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