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

Nathalia/boards #7

Open
wants to merge 24 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
3b5cf0a
initial setup and add models
Jul 12, 2021
3e9d2fb
fixed error in db
Jul 12, 2021
2a9e7f5
fixed some errors and added get and post for boards
Peacegypsy Jul 13, 2021
1eaf1a4
added update and delete methods to boards
Peacegypsy Jul 13, 2021
c844903
fixed a bug
Peacegypsy Jul 13, 2021
2261980
Handling 404 error on Post missing title or owner
cervantesnathalia Jul 13, 2021
8cce624
new branch
Peacegypsy Jul 13, 2021
2535fad
"Adds function CARD,GET & POST for specific Board"
cervantesnathalia Jul 13, 2021
a645ab4
branch test
Jul 14, 2021
98e1e51
Merge pull request #1 from Peacegypsy/xtina-tester-branch
Peacegypsy Jul 14, 2021
e26ec06
Merge branch 'main' into Nathalia/boards
cervantesnathalia Jul 14, 2021
abb2b21
Merge pull request #2 from Peacegypsy/Nathalia/boards
cervantesnathalia Jul 14, 2021
1cdf7d9
small tweak
Peacegypsy Jul 14, 2021
dcd589a
pulled in changes
Peacegypsy Jul 14, 2021
974c9f0
added slackduck functionality and its quacking
Peacegypsy Jul 14, 2021
231d100
fixed cards returning on board-id
Peacegypsy Jul 14, 2021
cb734a9
Merge pull request #3 from Peacegypsy/xtina-slackbot
Peacegypsy Jul 14, 2021
a7906a6
Adds route DELETE card inside of a specific Board
cervantesnathalia Jul 14, 2021
b2210eb
Merge branch 'main' of https://github.com/Peacegypsy/back-end-inspira…
cervantesnathalia Jul 14, 2021
bf9086f
git Revert "Adds route DELETE card inside of a specific Board"
cervantesnathalia Jul 14, 2021
18e3aec
Adds a DELETE on Card function
cervantesnathalia Jul 14, 2021
2261fba
Merge branch 'Nathalia/boards' of https://github.com/Peacegypsy/back-…
cervantesnathalia Jul 14, 2021
e39ef8c
Merge pull request #4 from Peacegypsy/Nathalia/boards
cervantesnathalia Jul 14, 2021
213e2c2
Adds Delete Card
cervantesnathalia Jul 14, 2021
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
10 changes: 8 additions & 2 deletions app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,18 @@ def create_app():
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)

from .routes import hello_world_bp
app.register_blueprint(hello_world_bp)

from .routes import boards_bp
app.register_blueprint(boards_bp)

# Register Blueprints here
# from .routes import example_bp
# app.register_blueprint(example_bp)
Expand Down
Empty file added app/models.card.py
Empty file.
26 changes: 26 additions & 0 deletions app/models/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from dotenv import load_dotenv
import os

db = SQLAlchemy()
migrate = Migrate()
load_dotenv()


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")

db.init_app(app)
migrate.init_app(app, db)

# from app.models.planet import Planet
# from .routes import planets_bp
# app.register_blueprint(planets_bp)

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, autoincrement=True)
title = db.Column(db.String)
owner = db.Column(db.String)
cards = db.relationship('Card', backref='cards', lazy=True)
8 changes: 8 additions & 0 deletions app/models/card.py
Original file line number Diff line number Diff line change
@@ -1 +1,9 @@
from app import db


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_id = db.Column(db.Integer, db.ForeignKey(
"board.board_id"), nullable=True)
141 changes: 141 additions & 0 deletions app/routes.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,145 @@
from flask import Blueprint, request, jsonify, make_response
from app import db
from app.models.board import Board
from app.models.card import Card
import os
from dotenv import load_dotenv
import requests
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError

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


load_dotenv()


@hello_world_bp.route("/hello-world", methods=["GET"])
def hello_world():
my_beautiful_response_body = "Hello, World!"
return my_beautiful_response_body

def post_message_to_slack(text):
SLACK_TOKEN = os.environ.get('SLACKBOT_TOKEN')
client = WebClient(token=SLACK_TOKEN)
try:
response = client.chat_postMessage(
channel='C0286U213J5',
text=text
)
except SlackApiError as e:
assert e.response["error"]


@boards_bp.route("", methods=["GET", "POST"])
def handle_boards():
if request.method == "GET":
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)
elif request.method == "POST":
request_body = request.get_json()
title = request_body.get("title")
owner = request_body.get("owner")
new_board = Board(title=request_body["title"],
owner=request_body["owner"])
db.session.add(new_board)
db.session.commit()
slack_message = f"Some duck just added a new board!"
post_message_to_slack(slack_message)

return make_response(f"Board {new_board.title} successfully created", 201)


@boards_bp.route("/<board_id>", methods=["GET", "PUT", "DELETE"])
def handle_board(board_id):
board = Board.query.get_or_404(board_id)
if request.method == "GET":
cards = []
for card in board.cards:
single_card = {
"message": card.message,
}
cards.append(single_card)
return make_response({
"id": board.board_id,
"title": board.title,
"owner": board.owner,
"cards": cards
})
elif request.method == "PUT":
if board == None:
return make_response("Board does not exist", 404)
form_data = request.get_json()

board.title = form_data["title"]
board.owner = form_data["owner"]

db.session.commit()

return make_response(f"Board: {board.title} sucessfully updated.")

elif request.method == "DELETE":
if board == None:
return make_response("Board does not exist", 404)
db.session.delete(board)
db.session.commit()
return make_response(f"Board: {board.title} sucessfully deleted.")
# example_bp = Blueprint('example_bp', __name__)


@boards_bp.route("/<board_id>/cards", methods=["POST", "GET"])
def handle_cards(board_id):
board = Board.query.get(board_id)

if board is None:
return make_response("", 404)

if request.method == "GET":
cards = Board.query.get(board_id).cards
cards_response = []
for card in cards:
cards_response.append({
"message": card.message
})

return make_response(
{
"cards": cards_response
}, 200)
elif request.method == "POST":
request_body = request.get_json()
if 'message' not in request_body:
return {"details": "Invalid data"}, 400

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

db.session.add(new_card)
db.session.commit()
slack_message = f"Some duck just added a new card!"
post_message_to_slack(slack_message)

return {
"card": {
"id": new_card.card_id,
"message": new_card.message
}
}, 201

@boards_bp.route("/<board_id>/<card_id>", methods=["DELETE"])
def handle_card(board_id, card_id):
card = Card.query.get_or_404(card_id)

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

return make_response(
f"Card Message: {card.message} Card ID: {card.card_id} deleted successfully")
36 changes: 36 additions & 0 deletions logfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
2021-07-13 06:07:34.941 PDT [96833] LOG: starting PostgreSQL 13.3 on x86_64-apple-darwin20.4.0, compiled by Apple clang version 12.0.5 (clang-1205.0.22.9), 64-bit
2021-07-13 06:07:34.942 PDT [96833] LOG: listening on IPv4 address "127.0.0.1", port 5432
2021-07-13 06:07:34.942 PDT [96833] LOG: listening on IPv6 address "::1", port 5432
2021-07-13 06:07:34.943 PDT [96833] LOG: listening on Unix socket "/tmp/.s.PGSQL.5432"
2021-07-13 06:07:34.947 PDT [96834] LOG: database system was shut down at 2021-07-13 06:07:20 PDT
2021-07-13 06:07:34.949 PDT [96833] LOG: database system is ready to accept connections
2021-07-13 06:07:46.358 PDT [96866] FATAL: role "postgres" does not exist
2021-07-13 06:08:40.481 PDT [96996] FATAL: database "du" does not exist
2021-07-13 06:09:23.143 PDT [97350] FATAL: role "postgres" does not exist
2021-07-13 06:10:40.468 PDT [97924] FATAL: role "postgres" does not exist
2021-07-13 06:13:27.223 PDT [98323] FATAL: role "postgres" does not exist
2021-07-13 06:19:38.338 PDT [310] FATAL: role "postgres" does not exist
2021-07-13 06:23:44.026 PDT [1012] FATAL: role "postgres" does not exist
2021-07-13 06:23:54.376 PDT [1035] FATAL: database "Xtina206" does not exist
2021-07-13 06:28:43.565 PDT [1965] FATAL: role "postgres" does not exist
2021-07-13 06:32:11.170 PDT [2642] FATAL: role "xtina" is not permitted to log in
2021-07-13 06:32:22.481 PDT [2666] FATAL: database "Xtina206" does not exist
2021-07-13 06:33:39.135 PDT [2911] FATAL: role "postgres" does not exist
2021-07-13 06:33:50.071 PDT [2934] FATAL: database "Xtina206" does not exist
2021-07-13 06:33:59.221 PDT [2957] FATAL: database "Xtina206" does not exist
2021-07-13 06:34:16.502 PDT [3001] FATAL: role "inspiration_board_development" does not exist
2021-07-13 06:34:26.178 PDT [3025] FATAL: role "postgres" does not exist
2021-07-13 06:34:35.779 PDT [3049] FATAL: database "Xtina206" does not exist
2021-07-13 06:34:57.264 PDT [3095] FATAL: role "postgres" does not exist
2021-07-13 07:30:28.182 PDT [12165] LOG: unexpected EOF on client connection with an open transaction
2021-07-14 08:49:51.995 PDT [64205] LOG: unexpected EOF on client connection with an open transaction
2021-07-14 08:53:28.067 PDT [64292] LOG: unexpected EOF on client connection with an open transaction
2021-07-14 09:05:12.011 PDT [64978] LOG: unexpected EOF on client connection with an open transaction
2021-07-14 09:06:21.462 PDT [66682] LOG: unexpected EOF on client connection with an open transaction
2021-07-14 09:07:36.303 PDT [66847] LOG: unexpected EOF on client connection with an open transaction
2021-07-14 09:08:03.094 PDT [67041] LOG: unexpected EOF on client connection with an open transaction
2021-07-14 09:09:05.336 PDT [67110] LOG: unexpected EOF on client connection with an open transaction
2021-07-14 09:09:13.806 PDT [67265] LOG: unexpected EOF on client connection with an open transaction
2021-07-14 09:11:00.888 PDT [67474] LOG: unexpected EOF on client connection with an open transaction
2021-07-14 09:14:08.700 PDT [68281] LOG: unexpected EOF on client connection with an open transaction
2021-07-14 09:18:04.828 PDT [68607] LOG: unexpected EOF on client connection with an open transaction
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()
Loading