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

Tiffany, Rachael, Shay, & Tiana :: Inspiration Board BE :: Maple #4

Open
wants to merge 19 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
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
22 changes: 16 additions & 6 deletions app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,32 @@
load_dotenv()


def create_app():
def create_app(test_config=None):
app = Flask(__name__)
app.url_map.strict_slashes = False
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_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 app.routes import boards_bp
app.register_blueprint(boards_bp)

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

CORS(app)
return app
1 change: 1 addition & 0 deletions app/models/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# TEST TO PUSH TO GITHUB
14 changes: 14 additions & 0 deletions app/models/board.py
Original file line number Diff line number Diff line change
@@ -1 +1,15 @@
from app import db
from sqlalchemy.orm import backref

class Board(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
owner_name = db.Column(db.String)
title = db.Column(db.String)

# RETURNS RESPONSE BODY
def get_board_response(self):
return {
"id": self.id,
"owner_name": self.owner_name,
"title": self.title,
}
16 changes: 16 additions & 0 deletions app/models/card.py
Original file line number Diff line number Diff line change
@@ -1 +1,17 @@
from app import db
from sqlalchemy.orm import backref

class Card(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
message = db.Column(db.String)
likes_count = db.Column(db.Integer)
board_id = db.Column(db.Integer, db.ForeignKey("board.id"), nullable=False)
boards = db.relationship("Board", backref=backref("boards", cascade="delete"))

def to_json(self):
return {
"id" : self.id,
"message" : self.message,
"likes_count" : self.likes_count,
"board_id" : self.board_id
}
147 changes: 146 additions & 1 deletion app/routes.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,149 @@
from flask import Blueprint, request, jsonify, make_response
from app.models.card import Card
from app import db
from app.models.board import Board

# example_bp = Blueprint('example_bp', __name__)

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

# BOARD ROUTES
@boards_bp.route("", methods=["POST", "GET"])
def handle_boards():
# POST REQUEST
if request.method == "POST":
board_request_body = request.get_json()

new_board = Board(
owner_name=board_request_body["owner_name"],
title=board_request_body["title"],
)

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

new_board_response = new_board.get_board_response()

return jsonify(new_board_response), 201

# GET REQUEST
elif request.method == "GET":
board_title_query = request.args.get("title")
board_name_query = request.args.get("owner_name")
if board_title_query or board_name_query:
boards = Board.query.filter(Board.title.contains(board_title_query))
boards = Board.query.filter(Board.owner_name.contains(board_name_query))
else:
boards = Board.query.all()

board_response = [board.get_board_response() for board in boards]

if board_response == []:
return jsonify(board_response), 200

return jsonify(board_response), 200

# GET, PUT, DELETE ONE BOARD AT A TIME
@boards_bp.route("/<board_id>", methods=["GET", "PUT", "DELETE"])
def handle_one_board(board_id):
if not board_id.isnumeric():
return jsonify(None), 400

board = Board.query.get(board_id)

if board is None:
return jsonify({"Message": f"Board {board_id} was not found"}), 404

if request.method == "GET":
return jsonify(board.get_board_response()), 200

elif request.method == "PUT":
board_update_request_body = request.get_json()

if "owner_name" not in board_update_request_body or "title" not in board_update_request_body:
return jsonify(None), 400

board.owner_name=board_update_request_body["owner_name"],
board.title=board_update_request_body["title"]

db.session.commit()

updated_board_response = board.get_board_response()

return jsonify(updated_board_response), 200

elif request.method == "DELETE":

db.session.delete(board)
db.session.commit()

board_delete_response = board.get_board_response()

return jsonify(board_delete_response), 200

# Get all cards by board id (some FE event handler should use this)
@boards_bp.route("/<board_id>/cards", methods=["GET"])
def cards_by_board(board_id):
cards = Card.query.filter_by(board_id=board_id)
cards_response = [card.to_json() for card in cards]
return jsonify(cards_response), 200

# Add a card to a particular board (some FE event handler should use this)
@boards_bp.route("/<board_id>/cards", methods=["POST"])
def add_card(board_id):
request_data = request.get_json()
if len(request_data['message']) > 40 or len(request_data['message']) == 0:
return make_response("Your message must be between 1 and 40 characters.", 400)

card = Card(
message = request_data['message'],
likes_count = 0,
board_id = board_id
)
db.session.add(card)
db.session.commit()

return card.to_json(), 200

# CARD ROUTES

# Get all cards
# Note: this is only for testing purposes in Postman; the FE will never call it.
@cards_bp.route("", methods=["GET"])
def cards():
cards = Card.query.all()
cards_response = [card.to_json() for card in cards]
return jsonify(cards_response), 200

# Get one card
# Note: this is also just for testing purposes in Postman; the FE will never call it.
@cards_bp.route("/<card_id>", methods=["GET"])
def card(card_id):
card = Card.query.get(card_id)
if not card:
return make_response("", 404)
return card.to_json(), 200

# Delete one card (some FE event handler should use this)
@cards_bp.route("/<card_id>", methods=["DELETE"])
def delete_card(card_id):
card = Card.query.get(card_id)
if not card:
return make_response("", 404)

db.session.delete(card)
db.session.commit()

return card.to_json(), 200

# Update a card's likes_count (some FE event handler should use this)
@cards_bp.route("/<card_id>/add_like", methods=["PUT"])
def increment_likes(card_id):
card = Card.query.get(card_id)
if card is None:
return make_response("", 400)

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

return card.to_json(), 200
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