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

Adahs branch #58

Open
wants to merge 13 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
23 changes: 18 additions & 5 deletions app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,22 @@
migrate = Migrate()
load_dotenv()


def create_app(test_config=None):
app = Flask(__name__)
app.url_map.strict_slashes = False
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

if test_config is None:
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get(
"SQLALCHEMY_DATABASE_URI")
"SQLALCHEMY_DATABASE_URI"
)
else:
app.config["TESTING"] = True
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get(
"SQLALCHEMY_TEST_DATABASE_URI")
"SQLALCHEMY_TEST_DATABASE_URI"
)


# import models for Alembic Setup
from app.models.customer import Customer
from app.models.video import Video
Expand All @@ -31,6 +33,17 @@ def create_app(test_config=None):
db.init_app(app)
migrate.init_app(app, db)

#Register Blueprints Here
# Register Blueprints Here
from .customer_routes import customer_bp

app.register_blueprint(customer_bp)

from .video_routes import videos_bp

app.register_blueprint(videos_bp)

from .rental_routes import rental_bp

app.register_blueprint(rental_bp)

return app
return app
152 changes: 152 additions & 0 deletions app/customer_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
from app import db
from app.models.customer import Customer
from flask import Blueprint, json, jsonify, request
from app.models.video import Video
from app.models.rental import Rental
from datetime import datetime
import requests
import os

from tests.test_wave_01 import CUSTOMER_NAME

customer_bp = Blueprint("customers", __name__, url_prefix=("/customers"))


@customer_bp.route("", methods=["GET"])
def get_customer():
if request.method == "GET":
customers = Customer.query.all()
customer_response = []
for customer in customers:
customer_response.append(
{
"id": customer.id,
"name": customer.name,
"postal_code": customer.postal_code,
"phone": customer.phone,
}
)
Comment on lines +22 to +28
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this repeated code could be moved to your Customer Model as an instance method or moved to a helper function. It could look something like after the instance method is created

Suggested change
{
"id": customer.id,
"name": customer.name,
"postal_code": customer.postal_code,
"phone": customer.phone,
}
)
customer.to_customer_dict()
)

return jsonify(customer_response), 200


@customer_bp.route("", methods=["POST"])
def put_customer():
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i would rename this to something like post_customer() because this a post method

if request.method == "POST":
request_body = request.get_json()

if "name" not in request_body:
return jsonify({"details": "Request body must include name."}), 400

if "postal_code" not in request_body:
return jsonify({"details": "Request body must include postal_code."}), 400

if "phone" not in request_body:
return jsonify({"details": "Request body must include phone."}), 400

else:

new_customer = Customer(
name=request_body["name"],
phone=request_body["phone"],
postal_code=request_body["postal_code"],
)

db.session.add(new_customer)
db.session.commit()

return jsonify(new_customer.customer_information()), 201


@customer_bp.route("/<customer_id>", methods=["GET", "PUT"])
def gpd_customer(customer_id):
customer = Customer.query.get(customer_id)
if customer == None:
return (
jsonify({"message": f"Customer {customer_id} was not found"}),
404,
)

if request.method == "GET":

customer_response = {
"id": customer.id,
"name": customer.name,
"postal_code": customer.postal_code,
"phone": customer.phone,
}

return jsonify(customer_response), 200

if request.method == "PUT":
request_body = request.get_json()
if "name" not in request_body:
return jsonify(None), 400
if "postal_code" not in request_body:
return jsonify(None), 400
Comment on lines +82 to +85
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you could create a function called something like invalid_customer_info to handle the guard clauses here. You can use the same function in the Post method for customers

else:
form_data = request.get_json(customer_id)
customer.name = form_data["name"]
customer.phone = form_data["phone"]
customer.postal_code = form_data["postal_code"]

db.session.commit()

return jsonify(customer.customer_information()), 200


# @customer_bp.route("/customers/<customer_id>", methods=["DELETE"])
# def delete_single_customer(customer_id):
# print("hiya")
# try:
# customer = Customer.query.get(customer_id)
# except:
# return jsonify(message=f"Customer {customer_id} was not found"), 404

# db.session.delete(customer)
# db.session.commit()

# return jsonify(id=customer.id), 200
Comment on lines +97 to +108
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

when pushing the final code remove any unused code.

@customer_bp.route("/<customer_id>", methods=["DELETE"])
def delete_single_customer(customer_id):
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💃🏽

customer = Customer.query.get(customer_id)

if customer == None:
return jsonify(message=f"Customer {customer_id} was not found"), 404

db.session.delete(customer)
db.session.commit()

return jsonify(id=customer.id), 200


@customer_bp.route("/hello", methods=["GET"])
def get_hello():
return jsonify(None), 400


@customer_bp.route("/<customer_id>/rentals", methods=["GET"])
def get_customers_current_rentals(customer_id):
if int(customer_id) is False:
return jsonify(None), 400

customer = Customer.query.get(customer_id)

if customer == None:
return jsonify(message=f"Customer {customer_id} was not found"), 404

rental_list = Rental.query.filter_by(customer_id=customer.id, checked_out=True)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you already created a customer variable so you can use it here for line 137 like rental_list = customer.rentals and have a relationship in the customer model like rentals = db.relationship('Rental', back_populates='customer', lazy=True)


list_of_dicts = []

for rental in rental_list:

video = Video.query.get(rental.video_id)
list_of_dicts.append(
{
"release_date": video.release_date,
"title": video.title,
"due_date": rental.due_date,
}
)

return jsonify(list_of_dicts), 200
21 changes: 20 additions & 1 deletion app/models/customer.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,23 @@
from flask import current_app
from app import db
from datetime import date
from flask import Blueprint, jsonify, request


class Customer(db.Model):
id = db.Column(db.Integer, primary_key=True)
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String)
customer_registration = db.Column(db.String)
postal_code = db.Column(db.String)
phone = db.Column(db.String)
registered_at = db.Column(db.DateTime, default=date.today())
# videos = db.relationship("Video", secondary="rental", backref="customers")
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Like my previous comment I would suggest putting rentals = db.relationship('Rental', back_populates='customer', lazy=True) here


def customer_information(self):
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wait you already had an instance method!! There were other places you could've used it 👀

return {
"id": self.id,
"name": self.name,
"registered_at": self.customer_registration,
"postal_code": self.postal_code,
"phone": self.phone,
}
14 changes: 13 additions & 1 deletion app/models/rental.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,16 @@
from app import db
from datetime import timedelta, date
from datetime import datetime, timedelta


class Rental(db.Model):
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💃🏽

id = db.Column(db.Integer, primary_key=True)
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
customer_id = db.Column(db.Integer, db.ForeignKey("customer.id", ondelete="CASCADE"), nullable=False, )
video_id = db.Column(db.Integer, db.ForeignKey("video.id",ondelete="CASCADE"), nullable=False, )
due_date = db.Column(db.DateTime)
checked_out = db.Column(db.Boolean, default=False)
video = db.relationship("Video", backref="video_rentals") # added into the video class by having the relationship setup
customer = db.relationship("Customer", backref="customer_rentals") # add an attribute.


# composite Key?
15 changes: 14 additions & 1 deletion app/models/video.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,17 @@
from flask import jsonify, current_app
from app import db


class Video(db.Model):
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💃🏽

id = db.Column(db.Integer, primary_key=True)
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
title = db.Column(db.String)
release_date = db.Column(db.DateTime)
total_inventory = db.Column(db.Integer)

def video_information(self):
return {
"id": self.id,
"title": self.title,
"release_date": self.release_date,
"total_inventory": self.total_inventory,
}
103 changes: 103 additions & 0 deletions app/rental_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import re
from app import customer_routes, db
from app.models.customer import Customer
from app.models.rental import Rental
from app.models.video import Video
from datetime import date, datetime, timedelta
from flask import Blueprint, jsonify, request


rental_bp = Blueprint("rentals", __name__, url_prefix="/rentals")


@rental_bp.route("/check-out", methods=["POST"])
def rental_check_out():
request_body = request.get_json()

if "customer_id" not in request_body:
return jsonify(None), 400
if "video_id" not in request_body:
return jsonify("Could not perform checkout"), 400

customer = Customer.query.get(request_body["customer_id"])
video = Video.query.get(request_body["video_id"])

if hasattr(video, 'video_rentals') is False:
return jsonify(None), 404
if hasattr(customer, 'customer_rentals') is False:
return jsonify(None), 404
count_of_rentals = len(video.video_rentals)

video_avialable_inventory = video.total_inventory - count_of_rentals
Comment on lines +29 to +31
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

another suggestion would be to add video_checkout_count = db.Column(db.Integer, default=0 to you Customer model then add to the count and subtract from the inventory count. for videos

Suggested change
count_of_rentals = len(video.video_rentals)
video_avialable_inventory = video.total_inventory - count_of_rentals
customer.videos_checkout_count += 1
video.total_inventory -= 1


if video_avialable_inventory==0:
response_body={
"message":"Could not perform checkout"
}
return jsonify(response_body), 400

today = datetime.today()
due_date = today + timedelta(days=7)
Comment on lines +39 to +40
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

make one line like due_date = date.today() + timedelta(days=7)


new_rental = Rental(customer_id=customer.id, video_id=video.id, due_date=due_date, checked_out=True)


db.session.add(new_rental)
db.session.commit()

video_avialable_inventory -= 1
videos_customer_checked_out = Rental.query.filter_by(customer_id=customer.id, checked_out=True).count()

response_body = {
"customer_id": customer.id,
"video_id": video.id,
"due_date": due_date,
"videos_checked_out_count": videos_customer_checked_out,
"available_inventory": video_avialable_inventory,
}

return jsonify(response_body), 200


@rental_bp.route("/check-in", methods=["POST"])
def rental_check_in():
request_body = request.get_json()

if "customer_id" not in request_body:
return jsonify("Request body must include customer id and video id"), 400
if "video_id" not in request_body:
return jsonify("Request body must include customer id and video id"), 400

customer = Customer.query.get(request_body["customer_id"])
video = Video.query.get(request_body["video_id"])

if customer is None or video is None:
return jsonify(None), 404

rental = Rental.query.filter_by(customer_id=customer.id, video_id=video.id, checked_out=True).first()

if rental is None:
return jsonify(message="No outstanding rentals for customer 1 and video 1"), 400
if hasattr(video, 'video_rentals') is False:
return jsonify(None), 404
if hasattr(customer, 'customer_rentals') is False:
return jsonify(None), 404


count_of_rentals = len(video.video_rentals)

db.session.delete(rental)
db.session.commit()

videos_customer_checked_out = Rental.query.filter_by(customer_id=customer.id, checked_out=True).count()
video_avialable_inventory = video.total_inventory - count_of_rentals
Copy link

@tgoslee tgoslee Nov 23, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same suggestion from above you could add videos_checkout_count to your model then subtract from the count by doing customer.videos_checkout_count -= 1



response_body = {
"customer_id": customer.id,
"video_id": video.id,
"videos_checked_out_count": videos_customer_checked_out,
"available_inventory": video_avialable_inventory+1,
}

return jsonify(response_body), 200
Empty file removed app/routes.py
Empty file.
Loading