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

Maple C16 Karishma Johnson, Juliana Ruiz, Jesse, Grace(Jiajia Wang) #3

Open
wants to merge 26 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
6273968
created Board and Card model
jessepope Dec 17, 2021
77af698
make route files for board and card
karishmacarterjohnson Dec 17, 2021
aeb3a45
set up routes and register
karishmacarterjohnson Dec 17, 2021
1ba0c2d
remove comments
karishmacarterjohnson Dec 17, 2021
85d9fa9
template of routes to be defined
karishmacarterjohnson Dec 18, 2021
6254eb3
add template for updating likes endpoint
karishmacarterjohnson Dec 20, 2021
7dbf5a0
configure app for testing
karishmacarterjohnson Dec 20, 2021
dd38b31
some tests on card routes
karishmacarterjohnson Dec 20, 2021
1e0eda2
updated end points
jessepope Dec 20, 2021
2e67ce1
added board and card tests
jessepope Dec 20, 2021
bba094e
updated tests for failed posts
jessepope Dec 20, 2021
9f20961
defined get_specific_board end point
jessepope Dec 21, 2021
4185642
added autoincrement and default value
jessepope Dec 21, 2021
7ceab4a
fixed bracket notations for tests and added a ficture for multiple ca…
jessepope Dec 21, 2021
55e2829
defined card endpoints; all tests pass
karishmacarterjohnson Dec 21, 2021
a4c47e3
removed unused packages
jessepope Dec 22, 2021
981c7b5
updated routes for post board
karishmacarterjohnson Dec 23, 2021
bd04171
updated get board's cards route to also contain id
karishmacarterjohnson Dec 29, 2021
b19fc43
post card uses board id
karishmacarterjohnson Dec 29, 2021
1745d67
get request for boards also sends id with title
karishmacarterjohnson Dec 29, 2021
d284556
added board id into card POST route
jessepope Dec 29, 2021
da4f4a1
revert to last working v
karishmacarterjohnson Dec 29, 2021
840d683
Merge branch 'main' of https://github.com/jessepope/back-end-inspirat…
karishmacarterjohnson Dec 29, 2021
6eca306
updated github to match heroku
karishmacarterjohnson Dec 29, 2021
1162afa
updated post endpoint for card to give back id, likes, and message
karishmacarterjohnson Jan 1, 2022
3039983
removed CORS
karishmacarterjohnson Jan 3, 2022
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
27 changes: 17 additions & 10 deletions app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,36 @@
from flask_migrate import Migrate
from dotenv import load_dotenv
import os
from flask_cors import CORS
# from flask_cors import CORS

db = SQLAlchemy()
migrate = Migrate()
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")
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")

# 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 .board_routes import boards_bp
from .card_routes import cards_bp
app.register_blueprint(boards_bp)
app.register_blueprint(cards_bp)

CORS(app)

# CORS(app)
return app
53 changes: 53 additions & 0 deletions app/board_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
from app import db
from app.models.board import Board
from flask import Blueprint, request, jsonify


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

@boards_bp.route("", methods=["GET"])
def handle_boards():
all_boards = Board.query.all()
board_titles = [[board.title, board.board_id] for board in all_boards]
return jsonify(board_titles), 200

@boards_bp.route("", methods=["POST"])
def post_board():
request_body = request.get_json()
try:
new_board = Board(title = request_body["title"], owner = request_body["owner"])
except:
return jsonify("unsuccessful post"), 400
db.session.add(new_board)
db.session.commit()
return jsonify(request_body["title"]), 201

@boards_bp.route("/<id>", methods=["GET"])
def get_board_cards(id):
board = Board.query.get(id)
if board is None:
return jsonify(""), 404
cards = []

for card in board.cards:
cards.append({
"id": card.card_id,
"message": card.message,
"likes_count": card.likes_count
})
board_info = {
"title": board.title,
"owner": board.owner,
"cards": cards,
"id": int(id)
}
return jsonify(board_info), 200

@boards_bp.route("/<id>", methods=["DELETE"])
def delete_board(id):
board = Board.query.get(id)
if board is None:
return jsonify(""), 404
db.session.delete(board)
db.session.commit()
return jsonify(f"successfully deleted {board.title}"), 200
53 changes: 53 additions & 0 deletions app/card_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
from app import db
from app.models.card import Card
from flask import Blueprint, request, jsonify
from app.models.board import Board


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

@cards_bp.route("", methods=["GET"])
def handle_cards():
cards = Card.query.all()
card_info = []
for card in cards:
card_info.append({
"id": card.card_id,
"message": card.message,
"likes_count": card.likes_count
})
return jsonify(card_info), 200

@cards_bp.route("/<boardid>", methods=["POST"])
def post_card(boardid):
request_body = request.get_json()
try:
card = Card(message = request_body["message"])
except:
return jsonify("unsuccessful post"), 400
board = Board.query.get(boardid)
if board is None:
return jsonify(""), 404
db.session.add(card)
board.cards.append(card)
db.session.commit()
card = Card.query.order_by(Card.card_id.desc()).first()
return jsonify({"id": card.card_id, "likes_count": card.likes_count, "message": card.message}), 201

@cards_bp.route("/<id>/like", methods=["PUT"])
def like_card(id):
card = Card.query.get(id)
if card is None:
return jsonify(""), 404
card.likes_count += 1
db.session.commit()
return jsonify("successful update"), 200

@cards_bp.route("/<id>", methods=["DELETE"])
def delete_card(id):
card = Card.query.get(id)
if card is None:
return jsonify(""), 404
db.session.delete(card)
db.session.commit()
return jsonify(f"successfully deleted {card.message}"), 200
9 changes: 9 additions & 0 deletions app/models/board.py
Original file line number Diff line number Diff line change
@@ -1 +1,10 @@
from app import db
from flask import current_app

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", backref="board", lazy=True)


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

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, default=0)
board_id = db.Column(db.Integer, db.ForeignKey("board.board_id"), nullable=True)
4 changes: 0 additions & 4 deletions app/routes.py

This file was 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"}
42 changes: 42 additions & 0 deletions migrations/versions/71040b795106_adds_board_and_card_models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"""adds Board and Card models

Revision ID: 71040b795106
Revises:
Create Date: 2021-12-17 15:29:05.219383

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '71040b795106'
down_revision = None
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('board',
sa.Column('board_id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(), nullable=True),
sa.Column('owner', sa.String(), nullable=True),
sa.PrimaryKeyConstraint('board_id')
)
op.create_table('card',
sa.Column('card_id', sa.Integer(), nullable=False),
sa.Column('message', sa.String(), nullable=True),
sa.Column('likes_count', sa.Integer(), nullable=True),
sa.Column('board_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['board_id'], ['board.board_id'], ),
sa.PrimaryKeyConstraint('card_id')
)
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('card')
op.drop_table('board')
# ### end Alembic commands ###
Loading