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

Ocelots - Larissa and Soumya #19

Open
wants to merge 68 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
Show all changes
68 commits
Select commit Hold shift + click to select a range
6665a56
Wave 0:Setup added migrations folder
smysh Jan 3, 2023
75fb009
Registered /customers blueprint
ctlaultdel Jan 4, 2023
9f10b69
Added customer class attributes and datatypes
ctlaultdel Jan 4, 2023
4f2d3d4
Updated migrations with new customer class columns and datatypes
ctlaultdel Jan 4, 2023
ee5ccc7
Added routes for customers blueprint
ctlaultdel Jan 4, 2023
7a0dfb3
Updated customer attributes and added class methods
ctlaultdel Jan 4, 2023
c56bda9
Added routes for displaying all customers, one customer by id, and po…
ctlaultdel Jan 4, 2023
2c78b55
Upgraded migrations to reflect changes in customer attributes
ctlaultdel Jan 4, 2023
d9b1bca
Added update_attr() method which allows a value of a customer instanc…
ctlaultdel Jan 5, 2023
15505c1
Added delete_a_customer route and modify_a_customer route
ctlaultdel Jan 5, 2023
7f6d6be
added compare_type=True to Migrations
ctlaultdel Jan 5, 2023
86c9e70
Got default datetime working for registered_at customer data
ctlaultdel Jan 5, 2023
7b92a0f
Refactored routes to make use of customer methods
ctlaultdel Jan 5, 2023
037e36f
Added return True boolean to customer.update_attr() if update successful
ctlaultdel Jan 5, 2023
c278adb
added video model and to_dict() and from_dict() methods.
smysh Jan 5, 2023
35d93a4
added video blueprint and registered it with the app.
smysh Jan 5, 2023
9a17221
Merge pull request #1 from ctlaultdel/LA-costumer-model
ctlaultdel Jan 5, 2023
7da4e5b
added routes to get and create videos.
smysh Jan 5, 2023
f8a9bed
Merge remote-tracking branch 'origin' into ss-videos-model
smysh Jan 5, 2023
5041c29
moved routes to separate routes folder. Refactored validate_customer_…
smysh Jan 5, 2023
020dece
fix an issue that was making some tests fail.
smysh Jan 5, 2023
5e365e6
Some more refactoring to create separate validate_request_attributes …
smysh Jan 6, 2023
95c0283
Merge pull request #2 from ctlaultdel/ss-videos-model
ctlaultdel Jan 6, 2023
9af0ef6
Wave 1 tests passing. Further refactored to combine validate_post_req…
smysh Jan 6, 2023
8b60f76
Merge pull request #3 from ctlaultdel/ss-videos-model
ctlaultdel Jan 7, 2023
8d9c65d
Merge pull request #4 from ada-ac2/main
ctlaultdel Jan 7, 2023
f04affb
imported classes and blueprint for rentals endpoint
ctlaultdel Jan 7, 2023
6fa6a57
added customers/customer_id/rentals endpoint
ctlaultdel Jan 7, 2023
774e714
Reinitialized migrations
ctlaultdel Jan 7, 2023
5021439
New module for rentals routes
ctlaultdel Jan 7, 2023
26e19a8
Set up all attributes for models
ctlaultdel Jan 7, 2023
67f05df
refactor
ctlaultdel Jan 7, 2023
46d9040
added clauses to_dict method to return more info about customer and v…
ctlaultdel Jan 7, 2023
f8ddbc0
added display_rentals_by_customer_id endpoint
ctlaultdel Jan 7, 2023
74f2bd9
added available inventory to video model.
smysh Jan 7, 2023
29f62dc
added route to checkout video using POST /rentals/checkout
smysh Jan 7, 2023
5d28269
added route for video check-in. Also added updates to video_check_out…
smysh Jan 7, 2023
e1a734c
added status to rental model.
smysh Jan 8, 2023
9f9f2d4
Wave 1 tests are passing with these fixes.
smysh Jan 8, 2023
4259c63
Wave 2 video checkout tests are passing with these changes.
smysh Jan 8, 2023
4f60d99
updated rental check_in to add more checks.
smysh Jan 8, 2023
df45839
added getting rentals by video_id.
smysh Jan 8, 2023
5664ef5
Made some fixes so Wave 2 all tests are passing.
smysh Jan 8, 2023
aea5f0c
Merge pull request #5 from ctlaultdel/ss-videos-model
smysh Jan 8, 2023
4225112
Merge branch 'main' into LA-wave2
ctlaultdel Jan 8, 2023
fcc26ba
Merge pull request #6 from ctlaultdel/LA-wave2
ctlaultdel Jan 8, 2023
b76799b
modified id to customer_id in response and included videos_checked_ou…
ctlaultdel Jan 8, 2023
0cf86e6
corrected key error problem in wave 1 and wave 2 tests'
ctlaultdel Jan 8, 2023
5733651
LA-wave-03-partial
ctlaultdel Jan 9, 2023
643624e
Fixed typo
ctlaultdel Jan 9, 2023
577623c
updated migrations.
smysh Jan 9, 2023
3a03c90
fixed issue where rentals was showing checked in videos also.
smysh Jan 9, 2023
82e861a
LA-sort-and-count-queries-working
ctlaultdel Jan 9, 2023
7e5be26
Merge branch 'main' of https://github.com/ctlaultdel/retro-video-stor…
smysh Jan 9, 2023
c0e359f
fixes after merge.
smysh Jan 9, 2023
719c105
LA-pagination-feature-working
ctlaultdel Jan 9, 2023
9661d76
Merge branch 'main' of https://github.com/ctlaultdel/retro-video-stor…
smysh Jan 9, 2023
353fb08
bug fixing for merges.
smysh Jan 9, 2023
496aa80
added customer id to response in get rentals.
smysh Jan 9, 2023
27e5bb5
comment out optional Wav4 tests.
smysh Jan 9, 2023
6dceb47
validate request args count and page_num are int type.
smysh Jan 9, 2023
237305f
bug fix for customer query.
smysh Jan 9, 2023
5234714
Merge pull request #7 from ctlaultdel/ss-videos-model
ctlaultdel Jan 9, 2023
d7477d7
Co-authored-by: Larissa Ault <ctlaultdel@users.noreply.github.com>
smysh Jan 9, 2023
59ffd97
Merge pull request #8 from ctlaultdel/ss-videos-model
ctlaultdel Jan 9, 2023
ae23326
Added requirements and Procfile for heroku deployment
ctlaultdel Jan 9, 2023
ce4084d
Refroze the dependencies while in activated venv
ctlaultdel Jan 9, 2023
842ccdd
Deleted extra line
ctlaultdel Jan 10, 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
Prev Previous commit
Next Next commit
LA-wave-03-partial
  • Loading branch information
ctlaultdel committed Jan 9, 2023
commit 5733651f3e8aa8e154dddcc988e83245d4d18e27
24 changes: 9 additions & 15 deletions app/models/customer.py
Original file line number Diff line number Diff line change
@@ -29,22 +29,9 @@ def check_out_videos(self, n):

def check_in_videos(self, n):
self.n_rented_videos -= n

# def update_attr(self, attr, val):
# """
# Updates an attr given a *modifiable attr and value.
# * modifiable attrs: name, postal_code, phone
# """
# if attr == "name" and val.isalpha():
# self.name = val
# elif attr == "postal_code" and not val.isalpha():
# self.postal_code = val
# elif attr == "phone" and not val.isalpha():
# self.phone = val

# return False

def create_from_dict(dict):
@classmethod
def create_from_dict(cls, dict):
"""
Creates customer instance from dict values.
"""
@@ -53,3 +40,10 @@ def create_from_dict(dict):
postal_code=dict["postal_code"],
phone=dict["phone"]
)

@classmethod
def get_all_attrs(cls):
"""
Returns list of attributes for Customer class
"""
return ["name", "postal_code", "phone", "registered_at"]
43 changes: 12 additions & 31 deletions app/models/rental.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from app import db
import datetime as dt
from .video import Video
from .customer import Customer

class Rental(db.Model):
__tablename__ = "rentals"
@@ -14,11 +16,12 @@ class Rental(db.Model):

def to_dict(self):
"""
Returns dictionary of rental data and customer data if customer
Returns dictionary of rental data and *customer/video data if exists
"""
rental_dict = {
"due_date": self.due_date,
"n_video_copies": self.n_video_copies,
"id": self.id,
"due_date": self.due_date,
"n_video_copies": self.n_video_copies,
}
if self.customer:
customer_dict = self.customer.to_dict()
@@ -38,31 +41,9 @@ def from_dict(cls, rental_data):
)
return new_rental

# def check_out_video(self, n):
# """
# Updates video available inventory when customer checks out video(s)
# """
# # decrement the video inventory
# self.video.calculate_available_inventory()
# # increment the customer's number of rented videos
# self.customer.check_out_videos(n)

# def check_in_video(self):
# """
# Updates video available inventory when customer checks out video(s)
# """
# # decrement the video inventory
# self.video.calculate_available_inventory()
# # increment the customer's number of rented videos
# self.customer.check_out_videos()

# def check_in_video(self, n):
# """
# Updates videos checked out count and video available inventory
# :params:
# - n: number of videos to check in
# """
# self.num_duplicates_video -= n
# self.video.calculate_available_inventory()


@classmethod
def get_all_attrs(cls):
"""
Returns list of attributes for Rental class
"""
return ["name", "postal_code", "registered_at", "title", "release_date"]
102 changes: 102 additions & 0 deletions app/models/validation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
from flask import make_response, abort, request
from app.models.rental import Rental


# ~~~~~~ validation checkers and processing functions ~~~~~~
def validate_model(cls, model_id):

Choose a reason for hiding this comment

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

Really nice job refactoring here and organizing this code so nicely!

"""
Checks if model id is correct dtype (int) and if exists in db.
:params:
- model_id
:returns:
- response_msg (dict), status_code (int)
"""
# check if model id is integer dtype
try:
model_id = int(model_id)
except:
abort(make_response({"message": f"{model_id} should be an integer dtype"}, 400))
# fetch model by id
model = cls.query.get(model_id)
if not model:
return abort(make_response({"message": f"{cls.__name__} {model_id} was not found"}, 404))
else:
return model

def validate_request(request, reqs):
"""
Validates that http requests satisfy all requirements for PUT methods
:params:
- request (from client)
:returns:
- request_body (if requirements met)
"""

# collect request
request_body = request.get_json()
# check if all requirements in request
set_request_keys = set(request_body.keys())
set_reqs= set(reqs)
if not set_request_keys == set_reqs:
missing_key = "".join(set_reqs-set_request_keys)
return abort(make_response({
"details": f"Request body must include {missing_key}."
}, 400))
return request_body

def validate_and_process_query_params(cls, queries):
"""
Parse query parameters from HTTP request and separate into separate dictionaries
based on SQLAlchemy query method
:params:
- cls (class)
- queries (dict)
:returns:
- sort (dict): query params for order_by sorting method (ascending)
- count (dict): selected number of results for limit method
- page_num (dict): page
"""
attrs = cls.get_all_attrs()
sort = {}
count = {}
page_num = {}
for kwarg in queries:
# check for sort method query param
if kwarg == "sort":
# if sort string is not a model attribute
if queries[kwarg] not in attrs:
abort(make_response({
"message": f"{queries[kwarg]} is not a valid attribute to sort by"
}, 400))
else:
# add sort string to sort kwarg dict
sort[kwarg] = queries[kwarg]
# check for limit method query param
elif kwarg == "count":
# add count to count kwarg dict
count[kwarg] = queries[kwarg]
# check for page count method query param
elif kwarg == "page_num":
page_num[kwarg] == queries[kwarg]
else:
# query param is not a valid query method
abort(make_response(
{"message" : f"{kwarg} is an invalid query"}, 400
))
return sort, count, page_num

def create_model_query(models_query, cls, sort, count, page_num):
pass
# if sort:
# # sort asc by given attribute e.g. sort=name
# clause = getattr(cls, sort["sort"])
# model_query = models_query.order_by(clause.asc())
# # else:
# # models = models.order_by(cls.id.asc())
# if count:
# # limit selection of customers to view
# models_query = models_query.limit(count["count"])
# if page_num:
# # check documentation for this!!!
# pass
# return models_query
32 changes: 18 additions & 14 deletions app/models/video.py
Original file line number Diff line number Diff line change
@@ -12,19 +12,17 @@ class Video(db.Model):
rentals = db.relationship("Rental", back_populates="video")

def to_dict(self):
video_as_dict = {
"id": self.id,
"title": self.title,
"release_date": self.release_date,
"total_inventory": self.total_inventory,
"available_inventory": self.available_inventory,
}
# video_as_dict["video_id"] = self.id
# video_as_dict["title"] = self.title
# video_as_dict["release_date"] = self.release_date
# video_as_dict["total_inventory"] = self.total_inventory
# video_as_dict["available_inventory"] = self.available_inventory
return video_as_dict
"""
Returns dictionary of video data
"""
video_dict = {
"id": self.id,
"title": self.title,
"release_date": self.release_date,
"total_inventory": self.total_inventory,
"available_inventory": self.available_inventory,
}
return video_dict

def calculate_available_inventory(self):
"""
@@ -40,5 +38,11 @@ def from_dict(cls, video_data):
total_inventory=video_data["total_inventory"]
)
return new_video


@classmethod
def get_all_attrs(cls):
"""
Returns list of attributes for Video class
"""
return ["title", "release_date"]

88 changes: 34 additions & 54 deletions app/routes/customer_routes.py
Original file line number Diff line number Diff line change
@@ -1,59 +1,32 @@
from app import db
from flask import Blueprint, jsonify, make_response, abort, request
from flask import Blueprint, jsonify, make_response, request
from ..models.customer import Customer


# ~~~~~~ validation checkers ~~~~~~
def validate_model(cls, model_id):
"""
Checks if model id is correct dtype (int) and if exists in db.
:params:
- model_id
:returns:
- response_msg (dict), status_code (int)
"""
# check if model id is integer dtype
try:
model_id = int(model_id)
except:
abort(make_response({"message": f"{model_id} should be an integer dtype"}, 400))
# fetch model by id
model = cls.query.get(model_id)
if not model:
return abort(make_response({"message": f"{cls.__name__} {model_id} was not found"}, 404))
else:
return model

def validate_request(request, reqs):
"""
Validates that http requests satisfy all requirements for PUT methods
:params:
- request (from client)
:returns:
- request_body (if requirements met)
"""

# collect request
request_body = request.get_json()
# check if all requirements in request
set_request_keys = set(request_body.keys())
set_reqs= set(reqs)
if not set_request_keys == set_reqs:
missing_key = "".join(set_reqs-set_request_keys)
return abort(make_response({
"details": f"Request body must include {missing_key}."
}, 400))
return request_body
from ..models.video import Video
from ..models.rental import Rental
from app.models.validation import validate_model, validate_request, validate_and_process_query_params, create_model_query

# ~~~~~~ initialize customers blueprint ~~~~~~
customers_bp = Blueprint("customers", __name__, url_prefix="/customers")

Choose a reason for hiding this comment

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

Really nice job refactoring routes to individual files!


# ~~~~~~ customers endpoints ~~~~~~
@customers_bp.route("", methods=["GET"])
def display_all_customers():
# query all customers
customers = Customer.query.all()
# initialize response list
def display_all_customers():
request_query = request.args.to_dict()
# collect & process query params from http request
sort, count, page_num = validate_and_process_query_params(Customer, request_query)
# collect customers
customer_query = Customer.query
# default is sorted by ascending customer id
customers = customer_query.order_by(Customer.id.asc())
# check for additional query params
if sort:
# sort asc by given attribute e.g. sort=name
clause = getattr(Customer, sort["sort"])
customers = customer_query.order_by(clause.asc())
if count:
# limit selection of customers to view
customers = customer_query.limit(count["count"])
# fill http response list
response = []
for customer in customers:
response.append(customer.to_dict())
@@ -99,11 +72,18 @@ def delete_a_customer(customer_id):
@customers_bp.route("/<customer_id>/rentals", methods=["GET"])
def display_customer_rentals(customer_id):
customer = validate_model(Customer, customer_id)
# collect & process query params from http request
request_query = request.args.to_dict()
sort, count, page_num = validate_and_process_query_params(Rental, request_query)
# collect rentals by customer id
rental_query = Rental.query.filter_by(customer_id = customer.id)
# default is sorted by asc rental id
rentals = rental_query.order_by(Rental.id.asc())
if count:
# limit selection of customers to view
rentals = rental_query.limit(count["count"])
# fill http response list
rentals_response = []
for rental in customer.rentals:
rentals_response.append({
"release_date": rental.video.release_date,
"title": rental.video.title,
"due_date": rental.due_date
})
for rental in rentals:
rentals_response.append(rental.to_dict())
return make_response(jsonify(rentals_response), 200)
5 changes: 2 additions & 3 deletions app/routes/rentals_routes.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
from app import db
from flask import Blueprint, jsonify, make_response, abort, request
from flask import Blueprint, jsonify, make_response, request
from ..models.rental import Rental
from ..models.customer import Customer
from ..models.video import Video
from ..routes.customer_routes import validate_model
from ..routes.customer_routes import validate_request
from app.models.validation import validate_model, validate_request

# ~~~~~~ initialize rentals blueprint ~~~~~~
rentals_bp = Blueprint("rentals", __name__, url_prefix="/rentals")
Loading