From e5e4a0c866f079ba8b2347529c862e64f22bc0bb Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Tue, 3 Jan 2023 13:40:02 -0800 Subject: [PATCH 01/31] Set up envoirnment and DB for first wave --- migrations/README | 1 + migrations/alembic.ini | 45 ++++++++++++++++++ migrations/env.py | 96 +++++++++++++++++++++++++++++++++++++++ migrations/script.py.mako | 24 ++++++++++ 4 files changed, 166 insertions(+) create mode 100644 migrations/README create mode 100644 migrations/alembic.ini create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako diff --git a/migrations/README b/migrations/README new file mode 100644 index 000000000..98e4f9c44 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 000000000..f8ed4801f --- /dev/null +++ b/migrations/alembic.ini @@ -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 diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 000000000..8b3fb3353 --- /dev/null +++ b/migrations/env.py @@ -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() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 000000000..2c0156303 --- /dev/null +++ b/migrations/script.py.mako @@ -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"} From 15e74ab9f3d50841c5a523ae82be14b27ce63db4 Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Tue, 3 Jan 2023 17:17:42 -0800 Subject: [PATCH 02/31] Updated to seperate routes Co-authored-by: HienXuanPham --- app/{routes.py => routes/customer_routes.py} | 0 app/routes/rental_routes.py | 0 app/routes/video_routes.py | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename app/{routes.py => routes/customer_routes.py} (100%) create mode 100644 app/routes/rental_routes.py create mode 100644 app/routes/video_routes.py diff --git a/app/routes.py b/app/routes/customer_routes.py similarity index 100% rename from app/routes.py rename to app/routes/customer_routes.py diff --git a/app/routes/rental_routes.py b/app/routes/rental_routes.py new file mode 100644 index 000000000..e69de29bb diff --git a/app/routes/video_routes.py b/app/routes/video_routes.py new file mode 100644 index 000000000..e69de29bb From 8c993d0b3505687208149a5c5640c6788d81992c Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Tue, 3 Jan 2023 17:48:53 -0800 Subject: [PATCH 03/31] First models complete. Co-authored-by: HienXuanPham --- app/models/customer.py | 11 ++++++- app/models/video.py | 5 ++- migrations/versions/7860939254e9_.py | 49 ++++++++++++++++++++++++++++ 3 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 migrations/versions/7860939254e9_.py diff --git a/app/models/customer.py b/app/models/customer.py index 54d10b49a..9ab51e844 100644 --- a/app/models/customer.py +++ b/app/models/customer.py @@ -1,4 +1,13 @@ from app import db +import datetime 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) + postal_code = db.Column(db.String) + phone_number = db.Column(db.String) + register_at = db.Column(db.DateTime, default=datetime.datetime.now()) + videos_checked_out_count = db.Column(db.Integer) + + + diff --git a/app/models/video.py b/app/models/video.py index db3bf3aeb..78413d957 100644 --- a/app/models/video.py +++ b/app/models/video.py @@ -1,4 +1,7 @@ from app import db class Video(db.Model): - 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.Date) + total_inventory = db.Column(db.Integer) \ No newline at end of file diff --git a/migrations/versions/7860939254e9_.py b/migrations/versions/7860939254e9_.py new file mode 100644 index 000000000..7f5e8cfab --- /dev/null +++ b/migrations/versions/7860939254e9_.py @@ -0,0 +1,49 @@ +"""empty message + +Revision ID: 7860939254e9 +Revises: +Create Date: 2023-01-03 17:47:24.091085 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '7860939254e9' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('customer', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('name', sa.String(), nullable=True), + sa.Column('postal_code', sa.String(), nullable=True), + sa.Column('phone_number', sa.String(), nullable=True), + sa.Column('register_at', sa.DateTime(), nullable=True), + sa.Column('videos_checked_out_count', sa.Integer(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('rental', + sa.Column('id', sa.Integer(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('video', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('title', sa.String(), nullable=True), + sa.Column('release_date', sa.Date(), nullable=True), + sa.Column('total_inventory', sa.Integer(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('video') + op.drop_table('rental') + op.drop_table('customer') + # ### end Alembic commands ### From cac07470f5c46a4f5e05ea29ac112457f5465586 Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Tue, 3 Jan 2023 18:09:50 -0800 Subject: [PATCH 04/31] Made dictionary methods for models! --- app/models/customer.py | 18 ++++++++++++++++++ app/models/video.py | 18 +++++++++++++++++- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/app/models/customer.py b/app/models/customer.py index 9ab51e844..e4daf5cbb 100644 --- a/app/models/customer.py +++ b/app/models/customer.py @@ -9,5 +9,23 @@ class Customer(db.Model): register_at = db.Column(db.DateTime, default=datetime.datetime.now()) videos_checked_out_count = db.Column(db.Integer) + def to_dict(self): + customer_dict = {} + customer_dict["id"] = self.id + customer_dict["name"] = self.name + customer_dict["postal_code"]=self.postal_code + customer_dict["phone_number"] = self.phone_number + + return customer_dict + @classmethod + def from_dict(cls,customer_data): + new_customer = Customer( + name=customer_data["name"], + postal_code=customer_data["postal_code"], + phone_number=customer_data["phone_number"], + register_at=customer_data["register_at"], + videos_checked_out_count=customer_data["videos_checked_out_count"] + ) + return new_customer \ No newline at end of file diff --git a/app/models/video.py b/app/models/video.py index 78413d957..b6a111f35 100644 --- a/app/models/video.py +++ b/app/models/video.py @@ -4,4 +4,20 @@ class Video(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) title=db.Column(db.String) release_date = db.Column(db.Date) - total_inventory = db.Column(db.Integer) \ No newline at end of file + total_inventory = db.Column(db.Integer) + + def to_dict(self): + video_dict = {} + video_dict["id"] = self.id + video_dict["title"] = self.title + video_dict["release_date"] = self.release_date + video_dict["total_inventory"] = self.total_inventory + + return video_dict + + @classmethod + def from_dict(cls,video_data): + new_video = Video(title=video_data["title"], release_date=video_data["release_date"], + total_inventory=video_data["total_inventory"]) + + return new_video \ No newline at end of file From 3443973366d64e16db21b1071b06fafcc1cb044b Mon Sep 17 00:00:00 2001 From: Xuan Hien Pham Date: Wed, 4 Jan 2023 16:05:33 -0500 Subject: [PATCH 05/31] CRUD for video --- app/__init__.py | 2 ++ app/models/video.py | 9 ++++-- app/routes/video_routes.py | 61 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 69 insertions(+), 3 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 4ab3975b8..0e679be22 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -32,5 +32,7 @@ def create_app(test_config=None): migrate.init_app(app, db) #Register Blueprints Here + from app.routes.video_routes import videos_bp + app.register_blueprint(videos_bp) return app \ No newline at end of file diff --git a/app/models/video.py b/app/models/video.py index b6a111f35..cdc976531 100644 --- a/app/models/video.py +++ b/app/models/video.py @@ -16,8 +16,11 @@ def to_dict(self): return video_dict @classmethod - def from_dict(cls,video_data): - new_video = Video(title=video_data["title"], release_date=video_data["release_date"], - total_inventory=video_data["total_inventory"]) + def from_dict(cls, video_data): + new_video = Video( + title=video_data["title"], + release_date=video_data["release_date"], + total_inventory=video_data["total_inventory"] + ) return new_video \ No newline at end of file diff --git a/app/routes/video_routes.py b/app/routes/video_routes.py index e69de29bb..0056fb71b 100644 --- a/app/routes/video_routes.py +++ b/app/routes/video_routes.py @@ -0,0 +1,61 @@ +from app import db +from app.models.video import Video +from flask import Blueprint, jsonify, abort, make_response, request + +videos_bp = Blueprint("videos_bp", __name__, url_prefix="/videos") + +def validate_model(cls, model_id): + try: + model_id = int(model_id) + except: + abort(make_response({"message":f"{cls.__name__} {model_id} invalid"}, 400)) + + model = cls.query.get(model_id) + + if not model: + abort(make_response({"message":f"{cls.__name__} {model_id} was not found"}, 404)) + + return model + +@videos_bp.route("", methods=["GET"]) +def get_all_video(): + videos = Video.query.all() + videos_response = [] + for video in videos: + videos_response.append(video.to_dict()) + return jsonify(videos_response) + +@videos_bp.route("/", methods=["GET"]) +def get_one_video_by_id(video_id): + video = validate_model(Video, video_id) + return video.to_dict() + +@videos_bp.route("", methods=["POST"]) +def create_a_video(): + request_body = request.get_json() + + new_video = Video.from_dict(request_body) + db.session.add(new_video) + db.session.commit() + + return make_response(new_video.to_dict(), 201) + +# try: +# new_moon = Moon.from_dict(request_body) +# new_moon["planet"] = planet +# except KeyError as key_error: +# abort(make_response({"message": f"Bad request: {key_error.args[0]} attribute is missing"}, 400)) + +@videos_bp.route("/", methods=["PUT"]) +def update_a_video(video_id): + video = validate_model(Video, video_id) + request_body = request.get_json() + + video.title = request_body["title"] + video.release_date = request_body["release_date"] + video.total_inventory = request_body["total_inventory"] + + db.session.add(video) + db.session.commit() + + return make_response(video.to_dict(), 200) \ No newline at end of file From 1e54c818c9f1321af12520a0ce2e9ccaa31fec15 Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Wed, 4 Jan 2023 13:25:35 -0800 Subject: [PATCH 06/31] working on customer --- app/__init__.py | 5 ++++- app/models/customer.py | 6 ++---- app/routes/customer_routes.py | 26 ++++++++++++++++++++++++++ 3 files changed, 32 insertions(+), 5 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 4ab3975b8..cf4ab6436 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -31,6 +31,9 @@ def create_app(test_config=None): db.init_app(app) migrate.init_app(app, db) - #Register Blueprints Here + #Register Blueprints Here + from app.routes.customer_routes import customers_bp + app.register_blueprint(customers_bp) + return app \ No newline at end of file diff --git a/app/models/customer.py b/app/models/customer.py index e4daf5cbb..fa3007376 100644 --- a/app/models/customer.py +++ b/app/models/customer.py @@ -14,7 +14,7 @@ def to_dict(self): customer_dict["id"] = self.id customer_dict["name"] = self.name customer_dict["postal_code"]=self.postal_code - customer_dict["phone_number"] = self.phone_number + customer_dict["phone"] = self.phone_number return customer_dict @@ -24,8 +24,6 @@ def from_dict(cls,customer_data): new_customer = Customer( name=customer_data["name"], postal_code=customer_data["postal_code"], - phone_number=customer_data["phone_number"], - register_at=customer_data["register_at"], - videos_checked_out_count=customer_data["videos_checked_out_count"] + phone_number=customer_data["phone"], ) return new_customer \ No newline at end of file diff --git a/app/routes/customer_routes.py b/app/routes/customer_routes.py index e69de29bb..dda59fd56 100644 --- a/app/routes/customer_routes.py +++ b/app/routes/customer_routes.py @@ -0,0 +1,26 @@ +from app import db +from app.models.customer import Customer +from flask import Blueprint, jsonify, abort, make_response, request + +customers_bp = Blueprint("customers_bp", __name__, url_prefix="/customers") + +def validate_model(cls, model_id): + try: + model_id = int(model_id) + except: + abort(make_response({"message": f"{cls.__name__} {model_id} invalid"}, 400)) + model = cls.query.get(model_id) + + if not model: + abort(make_response({"message": f"{cls.__name__} {model_id} not found"}, 404)) + return model + +@customers_bp.route("", methods=["POST"]) +def create_customer(): + request_body = request.get_json() + new_customer = Customer.from_dict(request_body) + + db.session.add(new_customer) + db.session.commit() + + return make_response(jsonify(f"New Customer {new_customer.name} successfully created"), 201) \ No newline at end of file From 4ffae4706e7c1866d1cf5dcab90704d36678925d Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Wed, 4 Jan 2023 14:10:25 -0800 Subject: [PATCH 07/31] Post and get complete --- app/__init__.py | 5 +---- app/models/customer.py | 6 +++--- app/routes/customer_routes.py | 24 +++++++++++++++++++++--- app/routes/video_routes.py | 2 +- 4 files changed, 26 insertions(+), 11 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 12a82d0dd..65c45f9f2 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -31,13 +31,10 @@ def create_app(test_config=None): db.init_app(app) migrate.init_app(app, db) -<<<<<<< HEAD #Register Blueprints Here -======= - #Register Blueprints Here + from app.routes.video_routes import videos_bp app.register_blueprint(videos_bp) ->>>>>>> 3443973366d64e16db21b1071b06fafcc1cb044b from app.routes.customer_routes import customers_bp app.register_blueprint(customers_bp) diff --git a/app/models/customer.py b/app/models/customer.py index fa3007376..77cb08398 100644 --- a/app/models/customer.py +++ b/app/models/customer.py @@ -5,7 +5,7 @@ class Customer(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String) postal_code = db.Column(db.String) - phone_number = db.Column(db.String) + phone = db.Column(db.String) register_at = db.Column(db.DateTime, default=datetime.datetime.now()) videos_checked_out_count = db.Column(db.Integer) @@ -14,7 +14,7 @@ def to_dict(self): customer_dict["id"] = self.id customer_dict["name"] = self.name customer_dict["postal_code"]=self.postal_code - customer_dict["phone"] = self.phone_number + customer_dict["phone"] = self.phone return customer_dict @@ -24,6 +24,6 @@ def from_dict(cls,customer_data): new_customer = Customer( name=customer_data["name"], postal_code=customer_data["postal_code"], - phone_number=customer_data["phone"], + phone=customer_data["phone"], ) return new_customer \ No newline at end of file diff --git a/app/routes/customer_routes.py b/app/routes/customer_routes.py index dda59fd56..fe688681d 100644 --- a/app/routes/customer_routes.py +++ b/app/routes/customer_routes.py @@ -12,15 +12,33 @@ def validate_model(cls, model_id): model = cls.query.get(model_id) if not model: - abort(make_response({"message": f"{cls.__name__} {model_id} not found"}, 404)) + abort(make_response({"message": f"{cls.__name__} {model_id} was not found"}, 404)) return model @customers_bp.route("", methods=["POST"]) def create_customer(): request_body = request.get_json() - new_customer = Customer.from_dict(request_body) + try: + + new_customer = Customer.from_dict(request_body) + except KeyError as key_error: + abort(make_response({"details":f"Request body must include {key_error.args[0]}."}, 400)) db.session.add(new_customer) db.session.commit() + return make_response(new_customer.to_dict(), 201) + +#queries customers appends dictionaries, jysonifys list. +@customers_bp.route("", methods=["GET"]) +def get_all_customers(): + customers = Customer.query.all() + customer_response = [] + for customer in customers: + customer_response.append(customer.to_dict()) + return jsonify(customer_response) - return make_response(jsonify(f"New Customer {new_customer.name} successfully created"), 201) \ No newline at end of file +#get customer by id +@customers_bp.route("/", methods=["GET"]) +def get_one_customer(customer_id): + customer = validate_model(Customer, customer_id) + return customer.to_dict() diff --git a/app/routes/video_routes.py b/app/routes/video_routes.py index 0056fb71b..42ef52129 100644 --- a/app/routes/video_routes.py +++ b/app/routes/video_routes.py @@ -33,7 +33,7 @@ def get_one_video_by_id(video_id): @videos_bp.route("", methods=["POST"]) def create_a_video(): request_body = request.get_json() - + new_video = Video.from_dict(request_body) db.session.add(new_video) db.session.commit() From 30850f701aa917ed1e72e23992e4a858b3ce13e2 Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Wed, 4 Jan 2023 14:24:38 -0800 Subject: [PATCH 08/31] customer deleted completed --- app/models/customer.py | 1 + app/routes/customer_routes.py | 10 ++++++++++ 2 files changed, 11 insertions(+) diff --git a/app/models/customer.py b/app/models/customer.py index 77cb08398..296c8ac4d 100644 --- a/app/models/customer.py +++ b/app/models/customer.py @@ -13,6 +13,7 @@ def to_dict(self): customer_dict = {} customer_dict["id"] = self.id customer_dict["name"] = self.name + customer_dict["registered_at"]: self.register_at customer_dict["postal_code"]=self.postal_code customer_dict["phone"] = self.phone diff --git a/app/routes/customer_routes.py b/app/routes/customer_routes.py index fe688681d..9290de57e 100644 --- a/app/routes/customer_routes.py +++ b/app/routes/customer_routes.py @@ -42,3 +42,13 @@ def get_all_customers(): def get_one_customer(customer_id): customer = validate_model(Customer, customer_id) return customer.to_dict() + +#route to delete +@customers_bp.route("/", methods=["DELETE"]) +def delete_customer(customer_id): + customer = validate_model(Customer, customer_id) + + db.session.delete(customer) + db.session.commit() + + return make_response(jsonify(customer.to_dict()), 200) \ No newline at end of file From d08fca4a3e27872ed1651524011ff4abe7655aca Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Wed, 4 Jan 2023 14:36:29 -0800 Subject: [PATCH 09/31] Finished put method! --- app/routes/customer_routes.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/app/routes/customer_routes.py b/app/routes/customer_routes.py index 9290de57e..42515048b 100644 --- a/app/routes/customer_routes.py +++ b/app/routes/customer_routes.py @@ -51,4 +51,23 @@ def delete_customer(customer_id): db.session.delete(customer) db.session.commit() - return make_response(jsonify(customer.to_dict()), 200) \ No newline at end of file + return make_response(jsonify(customer.to_dict()), 200) + +#update route +@customers_bp.route("/", methods=["PUT"]) +def update_customer(customer_id): + customer=validate_model(Customer, customer_id) + + request_body = request.get_json() + try: + + customer.name=request_body["name"] + customer.phone=request_body["phone"] + customer.postal_code=request_body["postal_code"] + except KeyError as key_error: + abort(make_response({"details":f"Request body must include {key_error.args[0]}."}, 400)) + + db.session.add(customer) + db.session.commit() + + return make_response(customer.to_dict(), 200) \ No newline at end of file From 362213252a1e8c91349eaf8d5e8d9bf8c1486d30 Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Wed, 4 Jan 2023 18:07:23 -0800 Subject: [PATCH 10/31] Updated database and added Video Model. Co-authored-by: HienXuanPham --- app/models/customer.py | 5 +-- app/models/rental.py | 17 +++++++++- app/models/video.py | 1 + migrations/versions/d54be5047f73_.py | 51 ++++++++++++++++++++++++++++ 4 files changed, 71 insertions(+), 3 deletions(-) create mode 100644 migrations/versions/d54be5047f73_.py diff --git a/app/models/customer.py b/app/models/customer.py index 296c8ac4d..96a10fd89 100644 --- a/app/models/customer.py +++ b/app/models/customer.py @@ -6,14 +6,15 @@ class Customer(db.Model): name = db.Column(db.String) postal_code = db.Column(db.String) phone = db.Column(db.String) - register_at = db.Column(db.DateTime, default=datetime.datetime.now()) + registered_at = db.Column(db.DateTime, default=datetime.datetime.now()) videos_checked_out_count = db.Column(db.Integer) + rentals = db.relationship("Video", secondary="rentals", backref="customers") def to_dict(self): customer_dict = {} customer_dict["id"] = self.id customer_dict["name"] = self.name - customer_dict["registered_at"]: self.register_at + customer_dict["registered_at"]: self.registered_at customer_dict["postal_code"]=self.postal_code customer_dict["phone"] = self.phone diff --git a/app/models/rental.py b/app/models/rental.py index 11009e593..e9341931c 100644 --- a/app/models/rental.py +++ b/app/models/rental.py @@ -1,4 +1,19 @@ from app import db +import datetime +import enum + class Rental(db.Model): - id = db.Column(db.Integer, primary_key=True) \ No newline at end of file + + class RentalStatus(enum.Enum): + IN="Checked_in" + OUT="Checked_out" + + + __tablename__ = "rentals" + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + video_id = db.Column(db.Integer, db.ForeignKey('video.id'), primary_key=True,nullable=False) + customer_id = db.Column(db.Integer, db.ForeignKey('customer.id'), primary_key=True,nullable=False) + status = db.Column(db.Enum(RentalStatus)) + checkout_date = db.Column(db.DateTime, default=datetime.datetime.now()) + due_date = db.Column(db.DateTime, default=(datetime.date.today()+datetime.timedelta(days=7))) diff --git a/app/models/video.py b/app/models/video.py index cdc976531..c98952ca2 100644 --- a/app/models/video.py +++ b/app/models/video.py @@ -5,6 +5,7 @@ class Video(db.Model): title=db.Column(db.String) release_date = db.Column(db.Date) total_inventory = db.Column(db.Integer) + customers = db.relationship("Customer", secondary="rentals", backref="videos") def to_dict(self): video_dict = {} diff --git a/migrations/versions/d54be5047f73_.py b/migrations/versions/d54be5047f73_.py new file mode 100644 index 000000000..cbb5a86bb --- /dev/null +++ b/migrations/versions/d54be5047f73_.py @@ -0,0 +1,51 @@ +"""empty message + +Revision ID: d54be5047f73 +Revises: 7860939254e9 +Create Date: 2023-01-04 18:02:03.656443 + +""" +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +# revision identifiers, used by Alembic. +revision = 'd54be5047f73' +down_revision = '7860939254e9' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('rentals', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('video_id', sa.Integer(), nullable=False), + sa.Column('customer_id', sa.Integer(), nullable=False), + sa.Column('status', sa.Enum('IN', 'OUT', name='rentalstatus'), nullable=True), + sa.Column('checkout_date', sa.DateTime(), nullable=True), + sa.Column('due_date', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['customer_id'], ['customer.id'], ), + sa.ForeignKeyConstraint(['video_id'], ['video.id'], ), + sa.PrimaryKeyConstraint('id', 'video_id', 'customer_id') + ) + op.drop_table('rental') + op.add_column('customer', sa.Column('phone', sa.String(), nullable=True)) + op.add_column('customer', sa.Column('registered_at', sa.DateTime(), nullable=True)) + op.drop_column('customer', 'register_at') + op.drop_column('customer', 'phone_number') + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('customer', sa.Column('phone_number', sa.VARCHAR(), autoincrement=False, nullable=True)) + op.add_column('customer', sa.Column('register_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True)) + op.drop_column('customer', 'registered_at') + op.drop_column('customer', 'phone') + op.create_table('rental', + sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), + sa.PrimaryKeyConstraint('id', name='rental_pkey') + ) + op.drop_table('rentals') + # ### end Alembic commands ### From 08ab095dcb0d77043034a23ecc56929583c4c0b5 Mon Sep 17 00:00:00 2001 From: Xuan Hien Pham Date: Thu, 5 Jan 2023 10:57:21 -0500 Subject: [PATCH 11/31] modify video_routes to pass all tests in test_wave_01 --- app/models/customer.py | 2 +- app/models/video.py | 1 + app/routes/video_routes.py | 33 ++++++++++++++++++++------------- 3 files changed, 22 insertions(+), 14 deletions(-) diff --git a/app/models/customer.py b/app/models/customer.py index 96a10fd89..648a881f4 100644 --- a/app/models/customer.py +++ b/app/models/customer.py @@ -8,7 +8,7 @@ class Customer(db.Model): phone = db.Column(db.String) registered_at = db.Column(db.DateTime, default=datetime.datetime.now()) videos_checked_out_count = db.Column(db.Integer) - rentals = db.relationship("Video", secondary="rentals", backref="customers") + #rentals = db.relationship("Video", secondary="rentals", backref="customers") def to_dict(self): customer_dict = {} diff --git a/app/models/video.py b/app/models/video.py index c98952ca2..def71a7ff 100644 --- a/app/models/video.py +++ b/app/models/video.py @@ -6,6 +6,7 @@ class Video(db.Model): release_date = db.Column(db.Date) total_inventory = db.Column(db.Integer) customers = db.relationship("Customer", secondary="rentals", backref="videos") + def to_dict(self): video_dict = {} diff --git a/app/routes/video_routes.py b/app/routes/video_routes.py index 42ef52129..d7c3c0ad0 100644 --- a/app/routes/video_routes.py +++ b/app/routes/video_routes.py @@ -33,29 +33,36 @@ def get_one_video_by_id(video_id): @videos_bp.route("", methods=["POST"]) def create_a_video(): request_body = request.get_json() - - new_video = Video.from_dict(request_body) + try: + new_video = Video.from_dict(request_body) + except KeyError as key_error: + abort(make_response({"details":f"Request body must include {key_error.args[0]}."}, 400)) db.session.add(new_video) db.session.commit() return make_response(new_video.to_dict(), 201) -# try: -# new_moon = Moon.from_dict(request_body) -# new_moon["planet"] = planet -# except KeyError as key_error: -# abort(make_response({"message": f"Bad request: {key_error.args[0]} attribute is missing"}, 400)) - @videos_bp.route("/", methods=["PUT"]) def update_a_video(video_id): video = validate_model(Video, video_id) request_body = request.get_json() + try: + video.title = request_body["title"] + video.release_date = request_body["release_date"] + video.total_inventory = request_body["total_inventory"] + except KeyError as key_error: + abort(make_response({"details":f"Request body must include {key_error.args[0]}."}, 400)) + + db.session.add(video) + db.session.commit() - video.title = request_body["title"] - video.release_date = request_body["release_date"] - video.total_inventory = request_body["total_inventory"] + return make_response(video.to_dict(), 200) - db.session.add(video) +@videos_bp.route("/", methods=["DELETE"]) +def delete_a_video(video_id): + video = validate_model(Video, video_id) + + db.session.delete(video) db.session.commit() - return make_response(video.to_dict(), 200) \ No newline at end of file + return make_response(jsonify(video.to_dict()), 200) \ No newline at end of file From 1d76b94fb5f8394cad6c25ea4238db9f2a852e06 Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Thu, 5 Jan 2023 09:29:52 -0800 Subject: [PATCH 12/31] Tweaked rentals and started rental Routes. Co-authored-by: HienXuanPham --- app/__init__.py | 4 ++++ app/models/customer.py | 4 ++-- app/models/rental.py | 7 ++++--- app/models/video.py | 2 +- app/routes/customer_routes.py | 12 +----------- app/routes/rental_routes.py | 23 +++++++++++++++++++++++ 6 files changed, 35 insertions(+), 17 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 65c45f9f2..fe8b90e5e 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -38,5 +38,9 @@ def create_app(test_config=None): from app.routes.customer_routes import customers_bp app.register_blueprint(customers_bp) + + from app.routes.rental_routes import rentals_bp + app.register_blueprint(rentals_bp) + return app \ No newline at end of file diff --git a/app/models/customer.py b/app/models/customer.py index 648a881f4..94155c658 100644 --- a/app/models/customer.py +++ b/app/models/customer.py @@ -7,8 +7,8 @@ class Customer(db.Model): postal_code = db.Column(db.String) phone = db.Column(db.String) registered_at = db.Column(db.DateTime, default=datetime.datetime.now()) - videos_checked_out_count = db.Column(db.Integer) - #rentals = db.relationship("Video", secondary="rentals", backref="customers") + videos_checked_out_count = db.Column(db.Integer, default=0) + videos = db.relationship("Video", secondary="rentals", backref="customers") def to_dict(self): customer_dict = {} diff --git a/app/models/rental.py b/app/models/rental.py index e9341931c..5b7ddefbe 100644 --- a/app/models/rental.py +++ b/app/models/rental.py @@ -1,19 +1,20 @@ from app import db import datetime import enum +from sqlalchemy import Enum class Rental(db.Model): class RentalStatus(enum.Enum): - IN="Checked_in" - OUT="Checked_out" + CHECKIN="checked_in" + CHECKOUT="checked_out" __tablename__ = "rentals" id = db.Column(db.Integer, primary_key=True, autoincrement=True) video_id = db.Column(db.Integer, db.ForeignKey('video.id'), primary_key=True,nullable=False) customer_id = db.Column(db.Integer, db.ForeignKey('customer.id'), primary_key=True,nullable=False) - status = db.Column(db.Enum(RentalStatus)) + status = db.Column(db.Enum(RentalStatus), default=RentalStatus.CHECKOUT) checkout_date = db.Column(db.DateTime, default=datetime.datetime.now()) due_date = db.Column(db.DateTime, default=(datetime.date.today()+datetime.timedelta(days=7))) diff --git a/app/models/video.py b/app/models/video.py index def71a7ff..e69c6bcb3 100644 --- a/app/models/video.py +++ b/app/models/video.py @@ -5,7 +5,7 @@ class Video(db.Model): title=db.Column(db.String) release_date = db.Column(db.Date) total_inventory = db.Column(db.Integer) - customers = db.relationship("Customer", secondary="rentals", backref="videos") + #customers = db.relationship("Customer", secondary="rentals", backref="videos") def to_dict(self): diff --git a/app/routes/customer_routes.py b/app/routes/customer_routes.py index 42515048b..72f34cfb9 100644 --- a/app/routes/customer_routes.py +++ b/app/routes/customer_routes.py @@ -1,20 +1,10 @@ from app import db +from app.routes.video_routes import validate_model from app.models.customer import Customer from flask import Blueprint, jsonify, abort, make_response, request customers_bp = Blueprint("customers_bp", __name__, url_prefix="/customers") -def validate_model(cls, model_id): - try: - model_id = int(model_id) - except: - abort(make_response({"message": f"{cls.__name__} {model_id} invalid"}, 400)) - model = cls.query.get(model_id) - - if not model: - abort(make_response({"message": f"{cls.__name__} {model_id} was not found"}, 404)) - return model - @customers_bp.route("", methods=["POST"]) def create_customer(): request_body = request.get_json() diff --git a/app/routes/rental_routes.py b/app/routes/rental_routes.py index e69de29bb..a0587efbc 100644 --- a/app/routes/rental_routes.py +++ b/app/routes/rental_routes.py @@ -0,0 +1,23 @@ +from app import db +from app.models.rental import Rental +from app.models.video import Video +from app.models.customer import Customer +from app.routes.video_routes import validate_model +from flask import Blueprint, jsonify, abort, make_response, request + +rentals_bp = Blueprint("rentals_bp", __name__, url_prefix="/rentals") + +@rentals_bp.route("/check-out", methods=["POST"]) +def video_checkout(): + request_body=request.get_json() + customer = validate_model(Customer, request_body["customer_id"]) + video = validate_model(Video, request_body["video_id"]) + #put into rental model as to_dictionary + new_rental=Rental( + customer_id = customer.id, + video_id = video.id + ) + db.session.add(new_rental) + db.session.commit() + + return make_response(jsonify(new_rental), 200) \ No newline at end of file From 6462e4619828cb38fd6ebc5dfd1f10601b50b46f Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Thu, 5 Jan 2023 10:07:23 -0800 Subject: [PATCH 13/31] passed first 3 rental tests! --- app/models/rental.py | 19 +++++++++++++++++++ app/routes/rental_routes.py | 26 ++++++++++++++++++++------ 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/app/models/rental.py b/app/models/rental.py index 5b7ddefbe..92947f5aa 100644 --- a/app/models/rental.py +++ b/app/models/rental.py @@ -18,3 +18,22 @@ class RentalStatus(enum.Enum): status = db.Column(db.Enum(RentalStatus), default=RentalStatus.CHECKOUT) checkout_date = db.Column(db.DateTime, default=datetime.datetime.now()) due_date = db.Column(db.DateTime, default=(datetime.date.today()+datetime.timedelta(days=7))) + + def to_dict(self): + rental_dict = {} + rental_dict["id"] = self.id + rental_dict["customer_id"] = self.customer_id + rental_dict["video_id"] = self.video_id + rental_dict["checkout_date"] = self.checkout_date + rental_dict["due_date"] = self.due_date + + return rental_dict + + @classmethod + def from_dict(cls, rental_data): + new_rental = Rental( + customer_id=rental_data["customer_id"], + video_id=rental_data["video_id"] + ) + + return new_rental diff --git a/app/routes/rental_routes.py b/app/routes/rental_routes.py index a0587efbc..8b492d706 100644 --- a/app/routes/rental_routes.py +++ b/app/routes/rental_routes.py @@ -5,19 +5,33 @@ from app.routes.video_routes import validate_model from flask import Blueprint, jsonify, abort, make_response, request + rentals_bp = Blueprint("rentals_bp", __name__, url_prefix="/rentals") +def rental_response(rental,customer,video): + rental_response={} + rental_response["video_id"]=video.id + rental_response["customer_id"]=customer.id + rental_response["videos_checked_out_count"]=customer.videos_checked_out_count + rental_response["available_inventory"] = video.total_inventory + return rental_response + + @rentals_bp.route("/check-out", methods=["POST"]) def video_checkout(): request_body=request.get_json() customer = validate_model(Customer, request_body["customer_id"]) video = validate_model(Video, request_body["video_id"]) + video.total_inventory -=1 + customer.videos_checked_out_count +=1 #put into rental model as to_dictionary - new_rental=Rental( - customer_id = customer.id, - video_id = video.id - ) - db.session.add(new_rental) + try: + new_rental=Rental.from_dict(request_body) + + except KeyError as key_error: + abort(make_response({"details":f"Request body must include {key_error.args[0]}."}, 400)) + db.session.add_all([new_rental, customer, video]) + db.session.commit() - return make_response(jsonify(new_rental), 200) \ No newline at end of file + return make_response(rental_response(new_rental,customer,video), 200) \ No newline at end of file From 75476aa81acc188a94f91167b019a8910768001d Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Thu, 5 Jan 2023 10:14:32 -0800 Subject: [PATCH 14/31] bacref > back_populates --- app/models/customer.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/models/customer.py b/app/models/customer.py index 94155c658..5bfdfc939 100644 --- a/app/models/customer.py +++ b/app/models/customer.py @@ -8,7 +8,7 @@ class Customer(db.Model): phone = db.Column(db.String) registered_at = db.Column(db.DateTime, default=datetime.datetime.now()) videos_checked_out_count = db.Column(db.Integer, default=0) - videos = db.relationship("Video", secondary="rentals", backref="customers") + videos = db.relationship("Video", secondary="rentals", back_populates="customers") def to_dict(self): customer_dict = {} From 109796cf62935c281bfa40d740a5cd6042dea688 Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Thu, 5 Jan 2023 10:18:01 -0800 Subject: [PATCH 15/31] videos back_populate upgrade. --- app/models/video.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/models/video.py b/app/models/video.py index e69c6bcb3..9122720cf 100644 --- a/app/models/video.py +++ b/app/models/video.py @@ -5,7 +5,7 @@ class Video(db.Model): title=db.Column(db.String) release_date = db.Column(db.Date) total_inventory = db.Column(db.Integer) - #customers = db.relationship("Customer", secondary="rentals", backref="videos") + customers = db.relationship("Customer", secondary="rentals", back_populates="videos") def to_dict(self): From 01a8a85877711a1317ded4ede69da1b9a95d9ebc Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Thu, 5 Jan 2023 10:26:02 -0800 Subject: [PATCH 16/31] passed all checkout tests. --- app/routes/rental_routes.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/app/routes/rental_routes.py b/app/routes/rental_routes.py index 8b492d706..21b9e2c5e 100644 --- a/app/routes/rental_routes.py +++ b/app/routes/rental_routes.py @@ -20,13 +20,15 @@ def rental_response(rental,customer,video): @rentals_bp.route("/check-out", methods=["POST"]) def video_checkout(): request_body=request.get_json() - customer = validate_model(Customer, request_body["customer_id"]) - video = validate_model(Video, request_body["video_id"]) - video.total_inventory -=1 - customer.videos_checked_out_count +=1 #put into rental model as to_dictionary try: + customer = validate_model(Customer, request_body["customer_id"]) + video = validate_model(Video, request_body["video_id"]) + if video.total_inventory == 0: + abort(make_response({"message":"Could not perform checkout"}, 400)) new_rental=Rental.from_dict(request_body) + video.total_inventory -=1 + customer.videos_checked_out_count +=1 except KeyError as key_error: abort(make_response({"details":f"Request body must include {key_error.args[0]}."}, 400)) From 12840e712787d41c23e59a7741faa3870c4181e0 Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Thu, 5 Jan 2023 11:14:52 -0800 Subject: [PATCH 17/31] dynamic calculation of available inventory added. --- app/routes/rental_routes.py | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/app/routes/rental_routes.py b/app/routes/rental_routes.py index 21b9e2c5e..384b535ed 100644 --- a/app/routes/rental_routes.py +++ b/app/routes/rental_routes.py @@ -8,12 +8,19 @@ rentals_bp = Blueprint("rentals_bp", __name__, url_prefix="/rentals") +#calculate avail inventory +def availabl_inventory(video): + vids_out = db.session.query(Rental).filter_by( + video_id=video.id, + status=Rental.RentalStatus.CHECKOUT) + return video.total_inventory-len([1 for vid in vids_out]) +#response helper function def rental_response(rental,customer,video): rental_response={} rental_response["video_id"]=video.id rental_response["customer_id"]=customer.id rental_response["videos_checked_out_count"]=customer.videos_checked_out_count - rental_response["available_inventory"] = video.total_inventory + rental_response["available_inventory"] = availabl_inventory(video) #here we need to subtract all rentals associated with video return rental_response @@ -27,7 +34,6 @@ def video_checkout(): if video.total_inventory == 0: abort(make_response({"message":"Could not perform checkout"}, 400)) new_rental=Rental.from_dict(request_body) - video.total_inventory -=1 customer.videos_checked_out_count +=1 except KeyError as key_error: @@ -36,4 +42,8 @@ def video_checkout(): db.session.commit() - return make_response(rental_response(new_rental,customer,video), 200) \ No newline at end of file + return make_response(rental_response(new_rental,customer,video), 200) + +@rentals_bp.route("/check_in", methods=["PUT"]) +def checkin_video(): + request_body = request.get_json() From 879db46962e38fab343722e56b513e253221624a Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Thu, 5 Jan 2023 12:09:25 -0800 Subject: [PATCH 18/31] rentals passes all checkin methods! --- app/models/rental.py | 1 + app/routes/rental_routes.py | 45 ++++++++++++++++++++++++++++++------- 2 files changed, 38 insertions(+), 8 deletions(-) diff --git a/app/models/rental.py b/app/models/rental.py index 92947f5aa..2f585c8bb 100644 --- a/app/models/rental.py +++ b/app/models/rental.py @@ -25,6 +25,7 @@ def to_dict(self): rental_dict["customer_id"] = self.customer_id rental_dict["video_id"] = self.video_id rental_dict["checkout_date"] = self.checkout_date + rental_dict["status"] = self.status rental_dict["due_date"] = self.due_date return rental_dict diff --git a/app/routes/rental_routes.py b/app/routes/rental_routes.py index 384b535ed..a94b4675b 100644 --- a/app/routes/rental_routes.py +++ b/app/routes/rental_routes.py @@ -5,15 +5,24 @@ from app.routes.video_routes import validate_model from flask import Blueprint, jsonify, abort, make_response, request - rentals_bp = Blueprint("rentals_bp", __name__, url_prefix="/rentals") +#helper query function: +def query_rentals(filters): + query_results = db.session.query(Rental).filter_by(**filters).all() + return query_results + +#extract results +def extract_query(query_results): + response = [] + for object in query_results: + response.append(object.to_dict()) + return response #calculate avail inventory def availabl_inventory(video): - vids_out = db.session.query(Rental).filter_by( - video_id=video.id, - status=Rental.RentalStatus.CHECKOUT) - return video.total_inventory-len([1 for vid in vids_out]) + vids_out = query_rentals({"video_id":video.id, "status":Rental.RentalStatus.CHECKOUT}) + return video.total_inventory-len(vids_out) + #response helper function def rental_response(rental,customer,video): rental_response={} @@ -23,6 +32,7 @@ def rental_response(rental,customer,video): rental_response["available_inventory"] = availabl_inventory(video) #here we need to subtract all rentals associated with video return rental_response +#should make a query method that can take in video_id,customer_id and status @rentals_bp.route("/check-out", methods=["POST"]) def video_checkout(): @@ -31,19 +41,38 @@ def video_checkout(): try: customer = validate_model(Customer, request_body["customer_id"]) video = validate_model(Video, request_body["video_id"]) - if video.total_inventory == 0: + if availabl_inventory(video)==0: abort(make_response({"message":"Could not perform checkout"}, 400)) new_rental=Rental.from_dict(request_body) customer.videos_checked_out_count +=1 except KeyError as key_error: abort(make_response({"details":f"Request body must include {key_error.args[0]}."}, 400)) - db.session.add_all([new_rental, customer, video]) + + db.session.add_all([new_rental, customer]) db.session.commit() return make_response(rental_response(new_rental,customer,video), 200) -@rentals_bp.route("/check_in", methods=["PUT"]) +@rentals_bp.route("/check-in", methods=["POST"]) def checkin_video(): request_body = request.get_json() + + try: + customer = validate_model(Customer, request_body["customer_id"]) + video = validate_model(Video, request_body["video_id"]) + rental_query = query_rentals({"video_id": video.id, "customer_id":customer.id, "status": Rental.RentalStatus.CHECKOUT}) + if not rental_query: + abort(make_response({"message":"No outstanding rentals for customer 1 and video 1"}, 400)) + rental=rental_query[0] + rental.status=Rental.RentalStatus.CHECKIN + customer.videos_checked_out_count -=1 + except KeyError as key_error: + abort(make_response({"details":f"Request body must include {key_error.args[0]}."}, 400)) + + db.session.add_all([rental, customer]) + + db.session.commit() + + return make_response(rental_response(rental,customer,video), 200) From f9d491c559c1754c6e31c1cfd72b21af85643d53 Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Thu, 5 Jan 2023 12:45:42 -0800 Subject: [PATCH 19/31] finished rentals by video --- app/routes/customer_routes.py | 16 +++++++++++++++- app/routes/rental_routes.py | 15 ++++++++++++++- app/routes/video_routes.py | 18 +++++++++++++++++- 3 files changed, 46 insertions(+), 3 deletions(-) diff --git a/app/routes/customer_routes.py b/app/routes/customer_routes.py index 72f34cfb9..7c7487ad0 100644 --- a/app/routes/customer_routes.py +++ b/app/routes/customer_routes.py @@ -1,8 +1,22 @@ from app import db -from app.routes.video_routes import validate_model from app.models.customer import Customer +from app.models.video import Video +from app.routes.rental_routes import query_rentals from flask import Blueprint, jsonify, abort, make_response, request +def validate_model(cls, model_id): + try: + model_id = int(model_id) + except: + abort(make_response({"message":f"{cls.__name__} {model_id} invalid"}, 400)) + + model = cls.query.get(model_id) + + if not model: + abort(make_response({"message":f"{cls.__name__} {model_id} was not found"}, 404)) + + return model + customers_bp = Blueprint("customers_bp", __name__, url_prefix="/customers") @customers_bp.route("", methods=["POST"]) diff --git a/app/routes/rental_routes.py b/app/routes/rental_routes.py index a94b4675b..7d6e83ea6 100644 --- a/app/routes/rental_routes.py +++ b/app/routes/rental_routes.py @@ -2,11 +2,23 @@ from app.models.rental import Rental from app.models.video import Video from app.models.customer import Customer -from app.routes.video_routes import validate_model from flask import Blueprint, jsonify, abort, make_response, request rentals_bp = Blueprint("rentals_bp", __name__, url_prefix="/rentals") +def validate_model(cls, model_id): + try: + model_id = int(model_id) + except: + abort(make_response({"message":f"{cls.__name__} {model_id} invalid"}, 400)) + + model = cls.query.get(model_id) + + if not model: + abort(make_response({"message":f"{cls.__name__} {model_id} was not found"}, 404)) + + return model + #helper query function: def query_rentals(filters): query_results = db.session.query(Rental).filter_by(**filters).all() @@ -76,3 +88,4 @@ def checkin_video(): db.session.commit() return make_response(rental_response(rental,customer,video), 200) + diff --git a/app/routes/video_routes.py b/app/routes/video_routes.py index d7c3c0ad0..cfd328f27 100644 --- a/app/routes/video_routes.py +++ b/app/routes/video_routes.py @@ -1,7 +1,11 @@ from app import db from app.models.video import Video +from app.models.rental import Rental +from app.models.customer import Customer +from app.routes.rental_routes import query_rentals from flask import Blueprint, jsonify, abort, make_response, request + videos_bp = Blueprint("videos_bp", __name__, url_prefix="/videos") def validate_model(cls, model_id): @@ -65,4 +69,16 @@ def delete_a_video(video_id): db.session.delete(video) db.session.commit() - return make_response(jsonify(video.to_dict()), 200) \ No newline at end of file + return make_response(jsonify(video.to_dict()), 200) + +@videos_bp.route("//rentals", methods=["GET"]) +def get_rentals_by_video(video_id): + video = validate_model(Video, video_id) + query = query_rentals({"video_id":video.id, "status": Rental.RentalStatus.CHECKOUT}) + response = [] + for rental in query: + customer = validate_model(Customer, rental.customer_id) + rental_info = customer.to_dict() + rental_info["due_date"] = rental.due_date + response.append(rental_info) + return jsonify(response) From 2b45c785ae68dae26b33d4e1ff77d517ad43ef89 Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Thu, 5 Jan 2023 12:50:15 -0800 Subject: [PATCH 20/31] Wave 2 complete --- app/routes/customer_routes.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/app/routes/customer_routes.py b/app/routes/customer_routes.py index 7c7487ad0..d72772fc4 100644 --- a/app/routes/customer_routes.py +++ b/app/routes/customer_routes.py @@ -1,6 +1,7 @@ from app import db from app.models.customer import Customer from app.models.video import Video +from app.models.rental import Rental from app.routes.rental_routes import query_rentals from flask import Blueprint, jsonify, abort, make_response, request @@ -74,4 +75,16 @@ def update_customer(customer_id): db.session.add(customer) db.session.commit() - return make_response(customer.to_dict(), 200) \ No newline at end of file + return make_response(customer.to_dict(), 200) + +@customers_bp.route("//rentals", methods=["GET"]) +def get_rentals_by_video(customer_id): + customer = validate_model(Customer, customer_id) + query = query_rentals({"video_id":Customer.id, "status": Rental.RentalStatus.CHECKOUT}) + response = [] + for rental in query: + video = validate_model(Video, rental.video_id) + rental_info = video.to_dict() + rental_info["due_date"] = rental.due_date + response.append(rental_info) + return jsonify(response) \ No newline at end of file From fc894c53d431dfb00a87d04aa7c3ccaa653333e3 Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Thu, 5 Jan 2023 21:20:25 -0800 Subject: [PATCH 21/31] working through wave 3 Co-authored-by: HienXuanPham --- app/routes/video_routes.py | 67 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 65 insertions(+), 2 deletions(-) diff --git a/app/routes/video_routes.py b/app/routes/video_routes.py index cfd328f27..fb7b27fae 100644 --- a/app/routes/video_routes.py +++ b/app/routes/video_routes.py @@ -5,6 +5,68 @@ from app.routes.rental_routes import query_rentals from flask import Blueprint, jsonify, abort, make_response, request +def custom_query(cls, approvedsortinig, filters=None): + #list of accepted sort paramas + valid_sort=set(approvedsortinig) + custom_querys=None + + #getting sort and pagnation args, with defults and types + sort=request.args.get('sort', 'id') + page = request.args.get('page',1,type=int) + + count=request.args.get('per_page',100, type=int) + if request.args.get('count'): + count=request.args.get('count',100, type=int) + + if request.args.get('page_num'): + page=request.args.get('page_num',1, type=int) + + #making id if not valid. + if sort not in valid_sort: sort= 'id' + #checking to see if class is the orderby attricute + order_cls=cls + + if not hasattr(cls,sort): + find_att=[Customer,Video,Rental] + for object in find_att: + if hasattr(object,sort): + order_cls=object + + + + #are there filters? + if request.args.get('filter'): + filters=request.args.getlist('filter') + if filters: + join_id=None + join_class=None + if filters.get("customer_id"): + join_class=Video + join_id=join_class.__name__.lower() + "_id" + elif filters.get("video_id"): + join_class=Customer + join_id=join_class.__name__.lower() + "_id" + + if join_class: + custom_querys=db.session.query(cls).filter_by(**filters).join(join_class,join_class.id==getattr( + cls,join_id), full=True).order_by( + getattr(order_cls,sort)).paginate(page=page,per_page=count,error_out=False) + + else: + custom_querys=db.session.query(cls).filter_by(**filters).order_by( + getattr(order_cls,sort)).paginate(page,count,False) + + elif order_cls !=cls: + custom_querys=db.sessoin.query(cls).join(join_class,join_class.id==getattr( + cls,join_id), full=True).order_by( + getattr(order_cls,sort)).paginate(page,count,False) + else: + custom_querys=cls.query.order_by(getattr( + order_cls,sort)).paginate(page,count,False) + + query=custom_querys.items + return query + videos_bp = Blueprint("videos_bp", __name__, url_prefix="/videos") @@ -74,11 +136,12 @@ def delete_a_video(video_id): @videos_bp.route("//rentals", methods=["GET"]) def get_rentals_by_video(video_id): video = validate_model(Video, video_id) - query = query_rentals({"video_id":video.id, "status": Rental.RentalStatus.CHECKOUT}) + query = custom_query(Rental,['id','name','postal_code', 'registered_at'],{"video_id":video.id, "status": Rental.RentalStatus.CHECKOUT}) + response = [] for rental in query: customer = validate_model(Customer, rental.customer_id) - rental_info = customer.to_dict() + rental_info = customer.to_dict() rental_info["due_date"] = rental.due_date response.append(rental_info) return jsonify(response) From 73105b064fc445e469ac7bf7bad24dd0181fa217 Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Thu, 5 Jan 2023 21:20:38 -0800 Subject: [PATCH 22/31] trying to do current tests. --- ada-project-docs/wave_03.md | 1 - app/routes/customer_routes.py | 77 ++++++++++++++++++++++++++++++++--- app/routes/rental_routes.py | 1 + tests/conftest.py | 6 +-- tests/test_wave_03.py | 5 +-- 5 files changed, 77 insertions(+), 13 deletions(-) diff --git a/ada-project-docs/wave_03.md b/ada-project-docs/wave_03.md index 5873f12c4..c381a4b53 100644 --- a/ada-project-docs/wave_03.md +++ b/ada-project-docs/wave_03.md @@ -25,7 +25,6 @@ Things to note: - Customers can be sorted by `name`, `registered_at` and `postal_code` - Videos can be sorted by `title` and `release_date` - If the client requests both sorting and pagination, pagination should be relative to the sorted order -- Check out the [paginate method](https://flask-sqlalchemy.palletsprojects.com/en/2.x/api/#flask_sqlalchemy.BaseQuery.paginate) - The paginate method reteurns a [Pagination object](https://flask-sqlalchemy.palletsprojects.com/en/2.x/api/#flask_sqlalchemy.Pagination) - To access records from a Pagination object, consider using the `items` attribute - See [this article from DigitalOcean](https://www.digitalocean.com/community/tutorials/how-to-query-tables-and-paginate-data-in-flask-sqlalchemy) for a more detailed look at paginating data using SQLAlchemy diff --git a/app/routes/customer_routes.py b/app/routes/customer_routes.py index d72772fc4..93f8e1bc5 100644 --- a/app/routes/customer_routes.py +++ b/app/routes/customer_routes.py @@ -5,6 +5,68 @@ from app.routes.rental_routes import query_rentals from flask import Blueprint, jsonify, abort, make_response, request +def custom_query(cls, approvedsortinig, filters=None): + #list of accepted sort paramas + valid_sort=(approvedsortinig) + custom_querys=None + + #getting sort and pagnation args, with defults and types + sort=request.args.get('sort', 'id') + page = request.args.get('page_num', 1, type=int) + count=None + if request.args.get("count"): + count=request.args.get("count", 100, type=int) + else: + count=request.args.get('per_page', 100, type=int) + + #making id if not valid. + if sort not in valid_sort: sort= 'id' + #checking to see if class is the orderby attricute + order_cls=cls + + if not hasattr(cls,sort): + find_att=[Customer,Video,Rental] + for object in find_att: + if hasattr(object,sort): + order_cls=object + + + + #are there filters? + if request.args.get('filter'): + filters=request.args.getlist('filter') + if filters: + join_id=None + join_class=None + if filters.get("customer_id"): + join_class=Video + join_id=join_class.__name__.lower() + "_id" + elif filters.get("video_id"): + join_class=Customer + join_id=join_class.__name__.lower() + "_id" + + if join_class: + + custom=db.session.query(cls).filter_by(**filters).join(join_class,join_class.id==getattr( + cls,join_id), full=True).order_by( + getattr(order_cls,sort)) + custom_querys=custom.paginate(page,count,False) + else: + custom_querys=db.session.query(cls).filter_by(**filters).order_by( + getattr(order_cls,sort)).paginate(page,count,False) + + elif order_cls !=cls: + custom_querys=db.sessoin.query(cls).join(join_class,join_class.id==getattr( + cls,join_id), full=True).order_by( + getattr(order_cls,sort)).paginate(page,count,False) + else: + custom_querys=cls.query.order_by(getattr( + order_cls,sort)).paginate(page,count,False) + + query=custom_querys.items + return query + + def validate_model(cls, model_id): try: model_id = int(model_id) @@ -34,9 +96,10 @@ def create_customer(): return make_response(new_customer.to_dict(), 201) #queries customers appends dictionaries, jysonifys list. -@customers_bp.route("", methods=["GET"]) -def get_all_customers(): - customers = Customer.query.all() + +@customers_bp.route('', methods=["GET"]) +def get_all_customer(): + customers=custom_query(Customer,['id','name','registered_at','postal_code']) customer_response = [] for customer in customers: customer_response.append(customer.to_dict()) @@ -80,11 +143,13 @@ def update_customer(customer_id): @customers_bp.route("//rentals", methods=["GET"]) def get_rentals_by_video(customer_id): customer = validate_model(Customer, customer_id) - query = query_rentals({"video_id":Customer.id, "status": Rental.RentalStatus.CHECKOUT}) - response = [] + query = custom_query(Rental,['id','title','release_date'],{"customer_id":customer.id, "status": Rental.RentalStatus.CHECKOUT}) + response=[] for rental in query: video = validate_model(Video, rental.video_id) rental_info = video.to_dict() rental_info["due_date"] = rental.due_date response.append(rental_info) - return jsonify(response) \ No newline at end of file + return jsonify(response) + + #@customers_bp \ No newline at end of file diff --git a/app/routes/rental_routes.py b/app/routes/rental_routes.py index 7d6e83ea6..7b5abb2de 100644 --- a/app/routes/rental_routes.py +++ b/app/routes/rental_routes.py @@ -30,6 +30,7 @@ def extract_query(query_results): for object in query_results: response.append(object.to_dict()) return response + #calculate avail inventory def availabl_inventory(video): vids_out = query_rentals({"video_id":video.id, "status":Rental.RentalStatus.CHECKOUT}) diff --git a/tests/conftest.py b/tests/conftest.py index 1b985181c..7bda8ad2f 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -138,21 +138,21 @@ def one_returned_video(app, client, one_customer, second_video): }) @pytest.fixture -def customer_one_video_three(app, client, one_customer, three_copies_video): +def customer_one_video_three(app, client, one_customer, third_video): response = client.post("/rentals/check-out", json={ "customer_id": 1, "video_id": 1 }) @pytest.fixture -def customer_two_video_three(app, client, second_customer, three_copies_video): +def customer_two_video_three(app, client, second_customer, third_video): response = client.post("/rentals/check-out", json={ "customer_id": 2, "video_id": 1 }) @pytest.fixture -def customer_three_video_three(app, client, third_customer, three_copies_video): +def customer_three_video_three(app, client, third_customer, third_video): response = client.post("/rentals/check-out", json={ "customer_id": 3, "video_id": 1 diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index e26ec450c..b0c2d15c0 100644 --- a/tests/test_wave_03.py +++ b/tests/test_wave_03.py @@ -745,8 +745,6 @@ def test_get_renters_invalid_p_param(client, customer_one_video_three, customer_ assert response_body[1]["postal_code"] == CUSTOMER_2_POSTAL_CODE - - def test_get_customers_rental_history(client, one_checked_out_video, one_returned_video): # Act response = client.get("/customers/1/history") @@ -775,4 +773,5 @@ def test_get_customer_no_rental_history(client, one_checked_out_video): #Assert assert response.status_code == 200 assert len(response_body) == 0 - assert response_body == [] \ No newline at end of file + assert response_body == [] + From 53fa5b67a677ac89c003b6f234fc22b059cc0a44 Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Thu, 5 Jan 2023 21:36:33 -0800 Subject: [PATCH 23/31] continuing ot try and debug. --- app/routes/video_routes.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/app/routes/video_routes.py b/app/routes/video_routes.py index fb7b27fae..c75436472 100644 --- a/app/routes/video_routes.py +++ b/app/routes/video_routes.py @@ -12,14 +12,17 @@ def custom_query(cls, approvedsortinig, filters=None): #getting sort and pagnation args, with defults and types sort=request.args.get('sort', 'id') - page = request.args.get('page',1,type=int) + if request.args.get("page"): + page=request.args.get("page", 1, type=int) + elif request.args.get('page_num'): + page=request.args.get('page_num', 100, type=int) + else: page=1 + if request.args.get("count"): + count=request.args.get("count", 100, type=int) + elif request.args.get('per_page'): + count=request.args.get('per_page', 100, type=int) + else: count=100 - count=request.args.get('per_page',100, type=int) - if request.args.get('count'): - count=request.args.get('count',100, type=int) - - if request.args.get('page_num'): - page=request.args.get('page_num',1, type=int) #making id if not valid. if sort not in valid_sort: sort= 'id' @@ -49,7 +52,7 @@ def custom_query(cls, approvedsortinig, filters=None): if join_class: custom_querys=db.session.query(cls).filter_by(**filters).join(join_class,join_class.id==getattr( - cls,join_id), full=True).order_by( + cls,join_id)).order_by( getattr(order_cls,sort)).paginate(page=page,per_page=count,error_out=False) else: From b406f875182f9610cd07c141b19c33d8b41fe482 Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Fri, 6 Jan 2023 05:56:11 -0800 Subject: [PATCH 24/31] cleaned up --- app/routes/customer_routes.py | 20 ++++++-------------- app/routes/video_routes.py | 18 +++++------------- 2 files changed, 11 insertions(+), 27 deletions(-) diff --git a/app/routes/customer_routes.py b/app/routes/customer_routes.py index 93f8e1bc5..fe59b2a9c 100644 --- a/app/routes/customer_routes.py +++ b/app/routes/customer_routes.py @@ -35,7 +35,7 @@ def custom_query(cls, approvedsortinig, filters=None): #are there filters? if request.args.get('filter'): filters=request.args.getlist('filter') - if filters: + if cls is Rental: join_id=None join_class=None if filters.get("customer_id"): @@ -45,20 +45,11 @@ def custom_query(cls, approvedsortinig, filters=None): join_class=Customer join_id=join_class.__name__.lower() + "_id" - if join_class: - custom=db.session.query(cls).filter_by(**filters).join(join_class,join_class.id==getattr( - cls,join_id), full=True).order_by( - getattr(order_cls,sort)) - custom_querys=custom.paginate(page,count,False) - else: - custom_querys=db.session.query(cls).filter_by(**filters).order_by( - getattr(order_cls,sort)).paginate(page,count,False) - - elif order_cls !=cls: - custom_querys=db.sessoin.query(cls).join(join_class,join_class.id==getattr( - cls,join_id), full=True).order_by( - getattr(order_cls,sort)).paginate(page,count,False) + custom=db.session.query(cls).filter_by(**filters).join(join_class,join_class.id==getattr( + cls,join_id), full=True).order_by( + getattr(order_cls,sort)) + custom_querys=custom.paginate(page,count,False) else: custom_querys=cls.query.order_by(getattr( order_cls,sort)).paginate(page,count,False) @@ -144,6 +135,7 @@ def update_customer(customer_id): def get_rentals_by_video(customer_id): customer = validate_model(Customer, customer_id) query = custom_query(Rental,['id','title','release_date'],{"customer_id":customer.id, "status": Rental.RentalStatus.CHECKOUT}) + response=[] for rental in query: video = validate_model(Video, rental.video_id) diff --git a/app/routes/video_routes.py b/app/routes/video_routes.py index c75436472..2b65a7eaa 100644 --- a/app/routes/video_routes.py +++ b/app/routes/video_routes.py @@ -40,7 +40,7 @@ def custom_query(cls, approvedsortinig, filters=None): #are there filters? if request.args.get('filter'): filters=request.args.getlist('filter') - if filters: + if cls is Rental: join_id=None join_class=None if filters.get("customer_id"): @@ -50,19 +50,11 @@ def custom_query(cls, approvedsortinig, filters=None): join_class=Customer join_id=join_class.__name__.lower() + "_id" - if join_class: - custom_querys=db.session.query(cls).filter_by(**filters).join(join_class,join_class.id==getattr( - cls,join_id)).order_by( - getattr(order_cls,sort)).paginate(page=page,per_page=count,error_out=False) - - else: - custom_querys=db.session.query(cls).filter_by(**filters).order_by( - getattr(order_cls,sort)).paginate(page,count,False) - elif order_cls !=cls: - custom_querys=db.sessoin.query(cls).join(join_class,join_class.id==getattr( - cls,join_id), full=True).order_by( - getattr(order_cls,sort)).paginate(page,count,False) + custom=cls.query.filter_by(**filters).join(join_class,join_class.id==getattr( + cls,join_id), full=True).order_by( + getattr(order_cls,sort)) + custom_querys=custom.paginate(page,count,False) else: custom_querys=cls.query.order_by(getattr( order_cls,sort)).paginate(page,count,False) From b11a18521d7c266df2aa77dd7284656df7e94da3 Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Fri, 6 Jan 2023 07:01:12 -0800 Subject: [PATCH 25/31] still tryiing to debug videos_routes. --- app/routes/customer_routes.py | 32 ++++++++++++++++++++------------ app/routes/video_routes.py | 35 +++++++++++++++++++---------------- 2 files changed, 39 insertions(+), 28 deletions(-) diff --git a/app/routes/customer_routes.py b/app/routes/customer_routes.py index fe59b2a9c..fe716bd2d 100644 --- a/app/routes/customer_routes.py +++ b/app/routes/customer_routes.py @@ -5,51 +5,59 @@ from app.routes.rental_routes import query_rentals from flask import Blueprint, jsonify, abort, make_response, request -def custom_query(cls, approvedsortinig, filters=None): +def custom_query(cls, approvedsortinig, filters={}): #list of accepted sort paramas valid_sort=(approvedsortinig) custom_querys=None #getting sort and pagnation args, with defults and types sort=request.args.get('sort', 'id') - page = request.args.get('page_num', 1, type=int) + page = None count=None + if request.args.get("page"): + page=request.args.get("page", 1, type=int) + elif request.args.get('page_num'): + page=request.args.get('page_num', 1, type=int) + else: page=1 if request.args.get("count"): count=request.args.get("count", 100, type=int) - else: + elif request.args.get('per_page'): count=request.args.get('per_page', 100, type=int) + else: count=100 #making id if not valid. if sort not in valid_sort: sort= 'id' #checking to see if class is the orderby attricute order_cls=cls - if not hasattr(cls,sort): - find_att=[Customer,Video,Rental] - for object in find_att: - if hasattr(object,sort): - order_cls=object #are there filters? if request.args.get('filter'): - filters=request.args.getlist('filter') + filters.update(request.args.getlist('filter')) if cls is Rental: join_id=None join_class=None if filters.get("customer_id"): join_class=Video join_id=join_class.__name__.lower() + "_id" - elif filters.get("video_id"): + else: join_class=Customer join_id=join_class.__name__.lower() + "_id" + + if not hasattr(cls,sort): + find_att=[Customer,Video,Rental] + for object in find_att: + if hasattr(object,sort): + order_cls=object + break custom=db.session.query(cls).filter_by(**filters).join(join_class,join_class.id==getattr( - cls,join_id), full=True).order_by( + cls,join_id)).order_by( getattr(order_cls,sort)) - custom_querys=custom.paginate(page,count,False) + custom_querys=custom.paginate(page=page,per_page=count,error_out=False) else: custom_querys=cls.query.order_by(getattr( order_cls,sort)).paginate(page,count,False) diff --git a/app/routes/video_routes.py b/app/routes/video_routes.py index 2b65a7eaa..5f6ddd0c7 100644 --- a/app/routes/video_routes.py +++ b/app/routes/video_routes.py @@ -5,17 +5,19 @@ from app.routes.rental_routes import query_rentals from flask import Blueprint, jsonify, abort, make_response, request -def custom_query(cls, approvedsortinig, filters=None): +def custom_query(cls, approvedsortinig, filters={}): #list of accepted sort paramas - valid_sort=set(approvedsortinig) + valid_sort=(approvedsortinig) custom_querys=None #getting sort and pagnation args, with defults and types sort=request.args.get('sort', 'id') + page = None + count=None if request.args.get("page"): page=request.args.get("page", 1, type=int) elif request.args.get('page_num'): - page=request.args.get('page_num', 100, type=int) + page=request.args.get('page_num', 1, type=int) else: page=1 if request.args.get("count"): count=request.args.get("count", 100, type=int) @@ -23,38 +25,39 @@ def custom_query(cls, approvedsortinig, filters=None): count=request.args.get('per_page', 100, type=int) else: count=100 - #making id if not valid. if sort not in valid_sort: sort= 'id' #checking to see if class is the orderby attricute order_cls=cls - if not hasattr(cls,sort): - find_att=[Customer,Video,Rental] - for object in find_att: - if hasattr(object,sort): - order_cls=object #are there filters? if request.args.get('filter'): - filters=request.args.getlist('filter') - if cls is Rental: + filters.update(request.args.getlist('filter')) + if cls is Rental: join_id=None join_class=None if filters.get("customer_id"): join_class=Video join_id=join_class.__name__.lower() + "_id" - elif filters.get("video_id"): + else: join_class=Customer join_id=join_class.__name__.lower() + "_id" - - custom=cls.query.filter_by(**filters).join(join_class,join_class.id==getattr( - cls,join_id), full=True).order_by( + if not hasattr(cls,sort): + find_att=[Customer,Video,Rental] + for object in find_att: + if hasattr(object,sort): + order_cls=object + break + + + custom=db.session.query(cls).filter_by(**filters).join(join_class,join_class.id==getattr( + cls,join_id)).order_by( getattr(order_cls,sort)) - custom_querys=custom.paginate(page,count,False) + custom_querys=custom.paginate(page=page,per_page=count,error_out=False) else: custom_querys=cls.query.order_by(getattr( order_cls,sort)).paginate(page,count,False) From c4471a23d2e5bfee344fe720417a5bfa63d481ad Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Fri, 6 Jan 2023 08:52:49 -0800 Subject: [PATCH 26/31] morning debugging. --- app/routes/customer_routes.py | 12 ++++-------- app/routes/video_routes.py | 25 +++++++++++-------------- 2 files changed, 15 insertions(+), 22 deletions(-) diff --git a/app/routes/customer_routes.py b/app/routes/customer_routes.py index fe716bd2d..42bdfc837 100644 --- a/app/routes/customer_routes.py +++ b/app/routes/customer_routes.py @@ -30,12 +30,10 @@ def custom_query(cls, approvedsortinig, filters={}): #checking to see if class is the orderby attricute order_cls=cls - - - #are there filters? if request.args.get('filter'): filters.update(request.args.getlist('filter')) + if cls is Rental: join_id=None join_class=None @@ -54,10 +52,8 @@ def custom_query(cls, approvedsortinig, filters={}): break - custom=db.session.query(cls).filter_by(**filters).join(join_class,join_class.id==getattr( - cls,join_id)).order_by( - getattr(order_cls,sort)) - custom_querys=custom.paginate(page=page,per_page=count,error_out=False) + custom_querys=cls.query.filter_by(**filters).join(join_class).order_by( + getattr(order_cls,sort)).paginate(page=page,per_page=count,error_out=False) else: custom_querys=cls.query.order_by(getattr( order_cls,sort)).paginate(page,count,False) @@ -140,7 +136,7 @@ def update_customer(customer_id): return make_response(customer.to_dict(), 200) @customers_bp.route("//rentals", methods=["GET"]) -def get_rentals_by_video(customer_id): +def get_rentals_by_customer(customer_id): customer = validate_model(Customer, customer_id) query = custom_query(Rental,['id','title','release_date'],{"customer_id":customer.id, "status": Rental.RentalStatus.CHECKOUT}) diff --git a/app/routes/video_routes.py b/app/routes/video_routes.py index 5f6ddd0c7..14a7c5694 100644 --- a/app/routes/video_routes.py +++ b/app/routes/video_routes.py @@ -5,6 +5,8 @@ from app.routes.rental_routes import query_rentals from flask import Blueprint, jsonify, abort, make_response, request +videos_bp = Blueprint("videos_bp", __name__, url_prefix="/videos") + def custom_query(cls, approvedsortinig, filters={}): #list of accepted sort paramas valid_sort=(approvedsortinig) @@ -17,12 +19,13 @@ def custom_query(cls, approvedsortinig, filters={}): if request.args.get("page"): page=request.args.get("page", 1, type=int) elif request.args.get('page_num'): - page=request.args.get('page_num', 1, type=int) + page=request.args.get('page_num',1, type=int) else: page=1 + if request.args.get("count"): - count=request.args.get("count", 100, type=int) + count=request.args.get("count", type=int) elif request.args.get('per_page'): - count=request.args.get('per_page', 100, type=int) + count=request.args.get('per_page', type=int) else: count=100 #making id if not valid. @@ -30,19 +33,17 @@ def custom_query(cls, approvedsortinig, filters={}): #checking to see if class is the orderby attricute order_cls=cls - - - #are there filters? if request.args.get('filter'): filters.update(request.args.getlist('filter')) + if cls is Rental: join_id=None join_class=None if filters.get("customer_id"): join_class=Video join_id=join_class.__name__.lower() + "_id" - else: + elif filters.get("video_id"): join_class=Customer join_id=join_class.__name__.lower() + "_id" @@ -54,10 +55,8 @@ def custom_query(cls, approvedsortinig, filters={}): break - custom=db.session.query(cls).filter_by(**filters).join(join_class,join_class.id==getattr( - cls,join_id)).order_by( - getattr(order_cls,sort)) - custom_querys=custom.paginate(page=page,per_page=count,error_out=False) + custom_querys=cls.query.filter_by(**filters).join(join_class).order_by( + getattr(order_cls,sort)).paginate(page=page,per_page=count,error_out=False) else: custom_querys=cls.query.order_by(getattr( order_cls,sort)).paginate(page,count,False) @@ -66,8 +65,6 @@ def custom_query(cls, approvedsortinig, filters={}): return query -videos_bp = Blueprint("videos_bp", __name__, url_prefix="/videos") - def validate_model(cls, model_id): try: model_id = int(model_id) @@ -83,7 +80,7 @@ def validate_model(cls, model_id): @videos_bp.route("", methods=["GET"]) def get_all_video(): - videos = Video.query.all() + videos = custom_query(Video, ['id','title','release_date']) videos_response = [] for video in videos: videos_response.append(video.to_dict()) From 894e2f06f452c68c0757f5f6fba9bdce8339861f Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Fri, 6 Jan 2023 12:08:41 -0800 Subject: [PATCH 27/31] passes wave 3 minus history! --- app/routes/video_routes.py | 10 ++++----- tests/conftest.py | 10 ++++----- tests/test_wave_03.py | 43 +++++++++++++++++++------------------- 3 files changed, 31 insertions(+), 32 deletions(-) diff --git a/app/routes/video_routes.py b/app/routes/video_routes.py index 14a7c5694..6d3a0e0de 100644 --- a/app/routes/video_routes.py +++ b/app/routes/video_routes.py @@ -38,14 +38,14 @@ def custom_query(cls, approvedsortinig, filters={}): filters.update(request.args.getlist('filter')) if cls is Rental: - join_id=None + #join_id=None join_class=None if filters.get("customer_id"): join_class=Video - join_id=join_class.__name__.lower() + "_id" + # join_id=join_class.__name__.lower() + "_id" elif filters.get("video_id"): join_class=Customer - join_id=join_class.__name__.lower() + "_id" + # join_id=join_class.__name__.lower() + "_id" if not hasattr(cls,sort): find_att=[Customer,Video,Rental] @@ -131,8 +131,8 @@ def delete_a_video(video_id): @videos_bp.route("//rentals", methods=["GET"]) def get_rentals_by_video(video_id): video = validate_model(Video, video_id) - query = custom_query(Rental,['id','name','postal_code', 'registered_at'],{"video_id":video.id, "status": Rental.RentalStatus.CHECKOUT}) - + query = custom_query(Rental,['id','name','postal_code'],{"video_id":video.id, "status": Rental.RentalStatus.CHECKOUT}) + response = [] for rental in query: customer = validate_model(Customer, rental.customer_id) diff --git a/tests/conftest.py b/tests/conftest.py index 7bda8ad2f..a3f43ee9f 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -138,24 +138,22 @@ def one_returned_video(app, client, one_customer, second_video): }) @pytest.fixture -def customer_one_video_three(app, client, one_customer, third_video): +def customer_one_video_three(app, client, one_customer, five_copies_video): response = client.post("/rentals/check-out", json={ "customer_id": 1, "video_id": 1 }) @pytest.fixture -def customer_two_video_three(app, client, second_customer, third_video): +def customer_two_video_three(app, client, second_customer, five_copies_video): response = client.post("/rentals/check-out", json={ "customer_id": 2, "video_id": 1 }) @pytest.fixture -def customer_three_video_three(app, client, third_customer, third_video): +def customer_three_video_three(app, client, third_customer, five_copies_video): response = client.post("/rentals/check-out", json={ "customer_id": 3, "video_id": 1 - }) - - + }) \ No newline at end of file diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index b0c2d15c0..a127b6677 100644 --- a/tests/test_wave_03.py +++ b/tests/test_wave_03.py @@ -107,7 +107,7 @@ def test_get_customers_sorted_by_postal_code(client, one_customer, second_custom assert response_body[2]["phone"] == CUSTOMER_2_PHONE assert response_body[2]["postal_code"] == CUSTOMER_2_POSTAL_CODE -def test_paginate_per_page_greater_than_num_customers(client, one_customer): +def test_paginate_count_greater_than_num_customers(client, one_customer): # Arrange data = {"count": 5, "page_num": 1} @@ -333,7 +333,7 @@ def test_get_rentals_sorted_by_title(client, one_checked_out_video, second_check def test_get_paginate_n_greater_than_rentals(client, one_checked_out_video): # Arrange - data = {"per_page": 5, "page": 1} + data = {"count": 5,"page_num": 1} # Act response = client.get("/customers/1/rentals", query_string = data) @@ -349,7 +349,7 @@ def test_get_paginate_n_greater_than_rentals(client, one_checked_out_video): def test_get_second_page_of_rentals(client, one_checked_out_video, second_checked_out_video): # Arrange - data = {"per_page": 1, "page": 2} + data = {"count": 1, "page_num": 2} # Act response = client.get("/customers/1/rentals", query_string = data) @@ -365,7 +365,7 @@ def test_get_second_page_of_rentals(client, one_checked_out_video, second_checke def test_get_first_page_of_rentals_grouped_by_two(client, one_checked_out_video, second_checked_out_video, third_checked_out_video): # Arrange - data = {"per_page": 2, "page": 1} + data = {"count": 2, "page_num": 1} # Act response = client.get("/customers/1/rentals", query_string = data) @@ -384,7 +384,7 @@ def test_get_first_page_of_rentals_grouped_by_two(client, one_checked_out_video, def test_get_second_page_of_rentals_grouped_by_two(client, one_checked_out_video, second_checked_out_video, third_checked_out_video): # Arrange - data = {"per_page": 2, "page": 2} + data = {"count": 2, "page_num": 2} # Act response = client.get("/customers/1/rentals", query_string = data) @@ -399,7 +399,7 @@ def test_get_second_page_of_rentals_grouped_by_two(client, one_checked_out_video def test_get_rentals_no_page(client, one_checked_out_video, second_checked_out_video, third_checked_out_video): # Arrange - data = {"per_page": 2} + data = {"count": 2} # Act response = client.get("/customers/1/rentals", query_string = data) @@ -418,7 +418,7 @@ def test_get_rentals_no_page(client, one_checked_out_video, second_checked_out_v def test_get_rentals_sorted_and_paginated(client, one_checked_out_video, second_checked_out_video, third_checked_out_video): # Arrange - data = {"per_page": 2, "sort": "title", "page": 2} + data = {"count": 2, "sort": "title", "page_num": 2} # Act response = client.get("/customers/1/rentals", query_string = data) @@ -452,7 +452,7 @@ def test_get_rentals_invalid_sort_param(client, one_checked_out_video, second_ch def test_get_rentals_invalid_n_param(client, one_checked_out_video, second_checked_out_video): # Arrange - data = {"per_page": "invalid"} + data = {"count": "invalid"} # Act response = client.get("/customers/1/rentals", query_string = data) @@ -471,7 +471,7 @@ def test_get_rentals_invalid_n_param(client, one_checked_out_video, second_check def test_get_rentals_invalid_p_param(client, one_checked_out_video, second_checked_out_video): # Arrange - data = {"page": "invalid"} + data = {"page_num": "invalid"} # Act response = client.get("/customers/1/rentals", query_string = data) @@ -566,9 +566,9 @@ def test_get_renters_sorted_by_postal_code(client, customer_one_video_three, cus assert response_body[2]["postal_code"] == CUSTOMER_2_POSTAL_CODE -def test_paginate_per_page_greater_than_num_renters(client, customer_one_video_three): +def test_paginate_count_greater_than_num_renters(client, customer_one_video_three): # Arrange - data = {"per_page": 5, "page": 1} + data = {"count": 5, "page_num": 1} # Act response = client.get("/videos/1/rentals", query_string = data) @@ -585,7 +585,7 @@ def test_paginate_per_page_greater_than_num_renters(client, customer_one_video_t def test_get_second_page_of_renters(client, customer_one_video_three, customer_two_video_three): # Arrange - data = {"per_page": 1, "page": 2} + data = {"count": 1, "page_num": 2} # Act response = client.get("/videos/1/rentals", query_string = data) @@ -602,7 +602,7 @@ def test_get_second_page_of_renters(client, customer_one_video_three, customer_t def test_get_first_page_of_renters_grouped_by_two(client, customer_one_video_three, customer_two_video_three, customer_three_video_three): # Arrange - data = {"per_page": 2, "page": 1} + data = {"count": 2, "page_num": 1} # Act response = client.get("/videos/1/rentals", query_string = data) @@ -623,7 +623,7 @@ def test_get_first_page_of_renters_grouped_by_two(client, customer_one_video_thr def test_get_second_page_of_renters_grouped_by_two(client, customer_one_video_three, customer_two_video_three, customer_three_video_three): # Arrange - data = {"per_page": 2, "page": 2} + data = {"count": 2, "page_num": 2} # Act response = client.get("/videos/1/rentals", query_string = data) @@ -638,9 +638,9 @@ def test_get_second_page_of_renters_grouped_by_two(client, customer_one_video_th assert response_body[0]["postal_code"] == CUSTOMER_3_POSTAL_CODE -def test_get_customers_no_page(client, customer_one_video_three, customer_two_video_three, customer_three_video_three): +def test_get_renters_no_page(client, customer_one_video_three, customer_two_video_three, customer_three_video_three): # Arrange - data = {"per_page": 2} + data = {"count": 2} # Act response = client.get("/videos/1/rentals", query_string = data) @@ -661,7 +661,7 @@ def test_get_customers_no_page(client, customer_one_video_three, customer_two_vi def test_get_renters_sorted_and_paginated(client, customer_one_video_three, customer_two_video_three, customer_three_video_three): # Arrange - data = {"per_page": 2, "sort": "name", "page": 1} + data = {"count": 2, "sort": "name", "page_num": 1} # Act response = client.get("/videos/1/rentals", query_string = data) @@ -704,7 +704,7 @@ def test_get_renters_invalid_sort_param(client, customer_one_video_three, custom def test_get_renters_invalid_n_param(client, customer_one_video_three, customer_two_video_three): # Arrange - data = {"per_page": "invalid"} + data = {"count": "invalid"} # Act response = client.get("/videos/1/rentals", query_string = data) @@ -725,7 +725,7 @@ def test_get_renters_invalid_n_param(client, customer_one_video_three, customer_ def test_get_renters_invalid_p_param(client, customer_one_video_three, customer_two_video_three): # Arrange - data = {"page": "invalid"} + data = {"page_num": "invalid"} # Act response = client.get("/customers", query_string = data) @@ -745,6 +745,8 @@ def test_get_renters_invalid_p_param(client, customer_one_video_three, customer_ assert response_body[1]["postal_code"] == CUSTOMER_2_POSTAL_CODE + + def test_get_customers_rental_history(client, one_checked_out_video, one_returned_video): # Act response = client.get("/customers/1/history") @@ -773,5 +775,4 @@ def test_get_customer_no_rental_history(client, one_checked_out_video): #Assert assert response.status_code == 200 assert len(response_body) == 0 - assert response_body == [] - + assert response_body == [] \ No newline at end of file From 25e2c5f493f2899862496bf096dc291bec087a9a Mon Sep 17 00:00:00 2001 From: Xuan Hien Pham Date: Mon, 9 Jan 2023 12:07:09 -0500 Subject: [PATCH 28/31] created refactor branch and added routes history for customer and video --- app/routes/customer_routes.py | 86 ++++++--------------------------- app/routes/helper_functions.py | 63 ++++++++++++++++++++++++ app/routes/video_routes.py | 88 +++++++--------------------------- tests/test_wave_03.py | 31 +----------- tests/test_wave_04.py | 51 ++++++++++++++++++++ 5 files changed, 147 insertions(+), 172 deletions(-) create mode 100644 app/routes/helper_functions.py create mode 100644 tests/test_wave_04.py diff --git a/app/routes/customer_routes.py b/app/routes/customer_routes.py index 42bdfc837..b47813f3d 100644 --- a/app/routes/customer_routes.py +++ b/app/routes/customer_routes.py @@ -4,76 +4,7 @@ from app.models.rental import Rental from app.routes.rental_routes import query_rentals from flask import Blueprint, jsonify, abort, make_response, request - -def custom_query(cls, approvedsortinig, filters={}): - #list of accepted sort paramas - valid_sort=(approvedsortinig) - custom_querys=None - - #getting sort and pagnation args, with defults and types - sort=request.args.get('sort', 'id') - page = None - count=None - if request.args.get("page"): - page=request.args.get("page", 1, type=int) - elif request.args.get('page_num'): - page=request.args.get('page_num', 1, type=int) - else: page=1 - if request.args.get("count"): - count=request.args.get("count", 100, type=int) - elif request.args.get('per_page'): - count=request.args.get('per_page', 100, type=int) - else: count=100 - - #making id if not valid. - if sort not in valid_sort: sort= 'id' - #checking to see if class is the orderby attricute - order_cls=cls - - #are there filters? - if request.args.get('filter'): - filters.update(request.args.getlist('filter')) - - if cls is Rental: - join_id=None - join_class=None - if filters.get("customer_id"): - join_class=Video - join_id=join_class.__name__.lower() + "_id" - else: - join_class=Customer - join_id=join_class.__name__.lower() + "_id" - - if not hasattr(cls,sort): - find_att=[Customer,Video,Rental] - for object in find_att: - if hasattr(object,sort): - order_cls=object - break - - - custom_querys=cls.query.filter_by(**filters).join(join_class).order_by( - getattr(order_cls,sort)).paginate(page=page,per_page=count,error_out=False) - else: - custom_querys=cls.query.order_by(getattr( - order_cls,sort)).paginate(page,count,False) - - query=custom_querys.items - return query - - -def validate_model(cls, model_id): - try: - model_id = int(model_id) - except: - abort(make_response({"message":f"{cls.__name__} {model_id} invalid"}, 400)) - - model = cls.query.get(model_id) - - if not model: - abort(make_response({"message":f"{cls.__name__} {model_id} was not found"}, 404)) - - return model +from app.routes.helper_functions import validate_model, custom_query customers_bp = Blueprint("customers_bp", __name__, url_prefix="/customers") @@ -148,4 +79,17 @@ def get_rentals_by_customer(customer_id): response.append(rental_info) return jsonify(response) - #@customers_bp \ No newline at end of file +@customers_bp.route("//history", methods=["GET"]) +def get_video_had_been_checked_out(customer_id): + customer = validate_model(Customer, customer_id) + videos = custom_query(Rental,['id','title','release_date'],{"customer_id":customer.id, "status": Rental.RentalStatus.CHECKIN}) + response = [] + rental_info = {} + for rental in videos: + video = validate_model(Video, rental.video_id) + rental_info["title"] = video.title + rental_info["checkout_date"] = rental.checkout_date + rental_info["due_date"] = rental.due_date + response.append(rental_info) + return jsonify(response) + diff --git a/app/routes/helper_functions.py b/app/routes/helper_functions.py new file mode 100644 index 000000000..b482973a3 --- /dev/null +++ b/app/routes/helper_functions.py @@ -0,0 +1,63 @@ +from flask import Blueprint, jsonify, abort, make_response, request +from app.models.rental import Rental +from app.models.customer import Customer +from app.models.video import Video + +def validate_model(cls, model_id): + try: + model_id = int(model_id) + except: + abort(make_response({"message":f"{cls.__name__} {model_id} invalid"}, 400)) + + model = cls.query.get(model_id) + + if not model: + abort(make_response({"message":f"{cls.__name__} {model_id} was not found"}, 404)) + + return model + +def custom_query(cls, approvedsortinig, filters={}): + #list of accepted sort paramas + valid_sort=(approvedsortinig) + custom_querys=None + + #getting sort and pagnation args, with defults and types + sort=request.args.get('sort', 'id') + page = None + count=None + + if request.args.get('page_num'): + page=request.args.get('page_num', 1, type=int) + else: page=1 + + if request.args.get("count"): + count=request.args.get("count", 100, type=int) + else: count=100 + + #making id if not valid. + if sort not in valid_sort: sort= 'id' + #checking to see if class is the orderby attricute + order_cls=cls + + if cls is Rental: + join_class=None + if filters.get("customer_id"): + join_class=Video + else: + join_class=Customer + + if not hasattr(cls,sort): + find_att=[Customer,Video,Rental] + for object in find_att: + if hasattr(object,sort): + order_cls=object + break + + custom_querys=cls.query.filter_by(**filters).join(join_class).order_by( + getattr(order_cls,sort)).paginate(page=page,per_page=count,error_out=False) + else: + custom_querys=cls.query.order_by(getattr( + order_cls,sort)).paginate(page,count,False) + + query=custom_querys.items + return query \ No newline at end of file diff --git a/app/routes/video_routes.py b/app/routes/video_routes.py index 6d3a0e0de..c8a09a463 100644 --- a/app/routes/video_routes.py +++ b/app/routes/video_routes.py @@ -4,80 +4,10 @@ from app.models.customer import Customer from app.routes.rental_routes import query_rentals from flask import Blueprint, jsonify, abort, make_response, request +from app.routes.helper_functions import validate_model, custom_query videos_bp = Blueprint("videos_bp", __name__, url_prefix="/videos") -def custom_query(cls, approvedsortinig, filters={}): - #list of accepted sort paramas - valid_sort=(approvedsortinig) - custom_querys=None - - #getting sort and pagnation args, with defults and types - sort=request.args.get('sort', 'id') - page = None - count=None - if request.args.get("page"): - page=request.args.get("page", 1, type=int) - elif request.args.get('page_num'): - page=request.args.get('page_num',1, type=int) - else: page=1 - - if request.args.get("count"): - count=request.args.get("count", type=int) - elif request.args.get('per_page'): - count=request.args.get('per_page', type=int) - else: count=100 - - #making id if not valid. - if sort not in valid_sort: sort= 'id' - #checking to see if class is the orderby attricute - order_cls=cls - - #are there filters? - if request.args.get('filter'): - filters.update(request.args.getlist('filter')) - - if cls is Rental: - #join_id=None - join_class=None - if filters.get("customer_id"): - join_class=Video - # join_id=join_class.__name__.lower() + "_id" - elif filters.get("video_id"): - join_class=Customer - # join_id=join_class.__name__.lower() + "_id" - - if not hasattr(cls,sort): - find_att=[Customer,Video,Rental] - for object in find_att: - if hasattr(object,sort): - order_cls=object - break - - - custom_querys=cls.query.filter_by(**filters).join(join_class).order_by( - getattr(order_cls,sort)).paginate(page=page,per_page=count,error_out=False) - else: - custom_querys=cls.query.order_by(getattr( - order_cls,sort)).paginate(page,count,False) - - query=custom_querys.items - return query - - -def validate_model(cls, model_id): - try: - model_id = int(model_id) - except: - abort(make_response({"message":f"{cls.__name__} {model_id} invalid"}, 400)) - - model = cls.query.get(model_id) - - if not model: - abort(make_response({"message":f"{cls.__name__} {model_id} was not found"}, 404)) - - return model - @videos_bp.route("", methods=["GET"]) def get_all_video(): videos = custom_query(Video, ['id','title','release_date']) @@ -140,3 +70,19 @@ def get_rentals_by_video(video_id): rental_info["due_date"] = rental.due_date response.append(rental_info) return jsonify(response) + + +@videos_bp.route("//history", methods=["GET"]) +def get_customer_had_been_checked_out_video(video_id): + video = validate_model(Video, video_id) + query = custom_query(Rental,['id','name','postal_code'],{"video_id":video.id, "status": Rental.RentalStatus.CHECKIN}) + + response = [] + for rental in query: + customer = validate_model(Customer, rental.customer_id) + rental_info = customer.to_dict() + rental_info["checkout_date"] = rental.checkout_date + rental_info["due_date"] = rental.due_date + response.append(rental_info) + return jsonify(response) + diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index a127b6677..e5b99174d 100644 --- a/tests/test_wave_03.py +++ b/tests/test_wave_03.py @@ -1,5 +1,6 @@ from app.models.video import Video from app.models.customer import Customer +import pytest VIDEO_1_TITLE = "A Brand New Video" VIDEO_1_ID = 1 @@ -746,33 +747,3 @@ def test_get_renters_invalid_p_param(client, customer_one_video_three, customer_ - -def test_get_customers_rental_history(client, one_checked_out_video, one_returned_video): - # Act - response = client.get("/customers/1/history") - response_body = response.get_json() - - #Assert - assert response.status_code == 200 - assert len(response_body) == 1 - assert response_body[0]["title"] == VIDEO_2_TITLE - -def test_get_customer_not_found_rental_history(client, one_checked_out_video, one_returned_video): - # Act - response = client.get("/customers/2/history") - response_body = response.get_json() - - #Assert - assert response.status_code == 404 - assert response_body == {"message": "Customer 2 was not found"} - - -def test_get_customer_no_rental_history(client, one_checked_out_video): - # Act - response = client.get("/customers/1/history") - response_body = response.get_json() - - #Assert - assert response.status_code == 200 - assert len(response_body) == 0 - assert response_body == [] \ No newline at end of file diff --git a/tests/test_wave_04.py b/tests/test_wave_04.py new file mode 100644 index 000000000..9b74666a6 --- /dev/null +++ b/tests/test_wave_04.py @@ -0,0 +1,51 @@ +VIDEO_2_TITLE = "Video Two" +VIDEO_2_ID = 2 +VIDEO_2_INVENTORY = 1 +VIDEO_2_RELEASE_DATE = "12-31-2000" + +CUSTOMER_1_NAME = "A Brand New Customer" +CUSTOMER_1_ID = 1 +CUSTOMER_1_POSTAL_CODE = "12345" +CUSTOMER_1_PHONE = "123-123-1234" + +#@pytest.mark.skip() +def test_get_customers_rental_history(client, one_checked_out_video, one_returned_video): + # Act + response = client.get("/customers/1/history") + response_body = response.get_json() + + #Assert + assert response.status_code == 200 + assert len(response_body) == 1 + assert response_body[0]["title"] == VIDEO_2_TITLE + +#@pytest.mark.skip() +def test_get_customer_not_found_rental_history(client, one_checked_out_video, one_returned_video): + # Act + response = client.get("/customers/2/history") + response_body = response.get_json() + + #Assert + assert response.status_code == 404 + assert response_body == {"message": "Customer 2 was not found"} + +#@pytest.mark.skip() +def test_get_customer_no_rental_history(client, one_checked_out_video): + # Act + response = client.get("/customers/1/history") + response_body = response.get_json() + + #Assert + assert response.status_code == 200 + assert len(response_body) == 0 + assert response_body == [] + +def test_get_videos_rental_history(client, one_checked_out_video, one_returned_video): + # Act + response = client.get("/videos/2/history") + response_body = response.get_json() + + #Assert + assert response.status_code == 200 + assert len(response_body) == 1 + assert response_body[0]["name"] == CUSTOMER_1_NAME \ No newline at end of file From a88658c4407f2dbfd7d5036ef06f19ec4871d18e Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Mon, 9 Jan 2023 10:36:04 -0800 Subject: [PATCH 29/31] gunicorn on my system --- requirements.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/requirements.txt b/requirements.txt index 89e00b497..971fcb7d7 100644 --- a/requirements.txt +++ b/requirements.txt @@ -8,6 +8,7 @@ click==7.1.2 Flask==1.1.2 Flask-Migrate==2.6.0 Flask-SQLAlchemy==2.4.4 +gunicorn==20.1.0 idna==2.10 iniconfig==1.1.1 itsdangerous==1.1.0 @@ -28,5 +29,6 @@ requests==2.25.1 six==1.15.0 SQLAlchemy==1.3.23 toml==0.10.2 +tomli==2.0.1 urllib3==1.26.5 Werkzeug==1.0.1 From b05a5bff34256f0fff9de2fa9ea4fb1047180a20 Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Mon, 9 Jan 2023 10:40:59 -0800 Subject: [PATCH 30/31] finsihed deploying on personal heroku --- Procfile | 1 - 1 file changed, 1 deletion(-) diff --git a/Procfile b/Procfile index 72bdb9010..066ed31d9 100644 --- a/Procfile +++ b/Procfile @@ -1,2 +1 @@ web: gunicorn 'app:create_app()' - From ae1a7e7797c314fcff12d19e6db38e6c6b42fdfd Mon Sep 17 00:00:00 2001 From: maple-megan333 Date: Mon, 9 Jan 2023 11:03:56 -0800 Subject: [PATCH 31/31] finsiehd deploying personal heroku --- Procfile | 1 + 1 file changed, 1 insertion(+) diff --git a/Procfile b/Procfile index 066ed31d9..72bdb9010 100644 --- a/Procfile +++ b/Procfile @@ -1 +1,2 @@ web: gunicorn 'app:create_app()' +