Compare commits

..

4 Commits

10 changed files with 111 additions and 90 deletions

View File

@ -5,11 +5,12 @@ app = Flask(__name__)
jwt_manager = JWTManager(app) jwt_manager = JWTManager(app)
def create_app(): def create_app():
from app.api import bp, bp_errors, bp_product, bp_user from app.api import bp, bp_errors, bp_product, bp_user, bp_cart
app.register_blueprint(bp) app.register_blueprint(bp)
app.register_blueprint(bp_errors) app.register_blueprint(bp_errors)
app.register_blueprint(bp_product) app.register_blueprint(bp_product)
app.register_blueprint(bp_user) app.register_blueprint(bp_user)
app.register_blueprint(bp_cart)
from app.config import FlaskTesting, FlaskProduction from app.config import FlaskTesting, FlaskProduction
app.config.from_object(FlaskTesting) app.config.from_object(FlaskTesting)

View File

@ -4,5 +4,6 @@ bp_errors = Blueprint('errors', __name__)
bp = Blueprint('api', __name__) bp = Blueprint('api', __name__)
bp_product = Blueprint('product', __name__, url_prefix="/product") bp_product = Blueprint('product', __name__, url_prefix="/product")
bp_user = Blueprint('user', __name__, url_prefix="/user") bp_user = Blueprint('user', __name__, url_prefix="/user")
bp_cart = Blueprint('cart', __name__, url_prefix="/cart")
from . import routes from . import routes

View File

@ -1 +1 @@
from . import main_routes,error_routes, product_routes, user_routes from app.api.routes import main_routes, error_routes, product_routes, user_routes, cart_routes

View File

@ -0,0 +1,16 @@
from flask import jsonify, abort, request
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.api import bp_cart
from app.services.cart_service import CartService
@bp_cart.route('add/<int:product_id>', methods=['PUT'])
@jwt_required()
def add_to_cart(product_id: int):
user_id = get_jwt_identity()
count = request.args.get('count', default=1, type=int)
result, status_code = CartService.add_to_cart(user_id, product_id, count)
return result, status_code

View File

@ -1,4 +1,4 @@
from .. import bp_errors from app.api import bp_errors
@bp_errors.app_errorhandler(400) @bp_errors.app_errorhandler(400)
def bad_request(e): def bad_request(e):

View File

@ -1,6 +1,6 @@
from flask import jsonify, abort from flask import jsonify, abort
from .. import bp from app.api import bp
@bp.route('/') @bp.route('/')
def hello(): def hello():

View File

@ -5,58 +5,14 @@ from app.api import bp_product
from app.services.product_service import ProductService from app.services.product_service import ProductService
@bp_product.route('/<int:id>', methods=['GET']) @bp_product.route('/<int:id>', methods=['GET'])
def all_product_info(id: int): def get_product_info(id: int):
result = ProductService.get_all_info(id) fields = ['name', 'price', 'image', 'image_name', 'seller']
if result is not None: fields_param = request.args.get('fields')
return jsonify(result) requested_fields = []
else:
abort(404) return abort(501)
@bp_product.route('/<int:id>/name', methods=['GET'])
def get_name(id: int):
result = ProductService.get_name(id)
if result is not None:
return jsonify({"name": result})
else:
return abort(404)
@bp_product.route('/<int:id>/manufacturer', methods=['GET'])
def get_manufacturer(id: int):
result = ProductService.get_manufacturer(id)
if result is not None:
return jsonify({"name": result})
else:
return abort(404)
@bp_product.route('/<int:id>/price', methods=['GET'])
def get_price(id: int):
result = ProductService.get_price(id)
if result is not None:
return jsonify({"price": result})
else:
return abort(404)
@bp_product.route('/<int:id>/image', methods=['GET'])
def get_image(id: int):
result = ProductService.get_image(id)
if result is not None:
return jsonify({"image": result})
else:
return abort(404)
@bp_product.route('/<int:id>/image_name', methods=['GET'])
def get_image_name(id: int):
result = ProductService.get_image_name(id)
if result is not None:
return jsonify({"image_name": result})
else:
return abort(404)
@bp_product.route('/create', methods=['POST']) @bp_product.route('/create', methods=['POST'])
def create_product_listing(): def create_product_listing():

View File

@ -0,0 +1,30 @@
from mysql.connector import Error
from typing import Tuple, Union
from app.extensions import db_cursor, db_connection
class CartService:
@staticmethod
def add_to_cart(user_id: str, product_id: int, count: int) -> Tuple[Union[dict, str], int]:
try:
with db_connection.cursor() as cursor:
db_connection.begin()
db_cursor.execute("select * from cart_item where cart_id = %s and product_id = %s", (user_id, product_id))
if db_cursor.rowcount != 0:
db_cursor.execute("update cart_item set count = count + %s where cart_id = %s and product_id = %s", (count, user_id, product_id))
else:
db_cursor.execute("insert into cart_item(cart_id, product_id, count) values (%s, %s, %s)", (user_id, product_id, count))
db_connection.commit()
return {"Success": "Successfully added to cart"}, 200
except Error as e:
return {"Failed": f"Failed to add item to cart. {e}"}
@staticmethod
def show_cart(user_id: str):
return None

View File

@ -1,44 +1,70 @@
import base64 import base64
from ..extensions import db_cursor as cursor from flask import abort
from mysql.connector import Error
from app.extensions import db_connection
class ProductService: class ProductService:
@staticmethod @staticmethod
def get_name(product_id: int): def get_name(product_id: int):
cursor.execute(f"select name from product where product.id = {product_id}") db_cursor.execute(f"select name from product where product.id = {product_id}")
result = cursor.fetchone()
if db_cursor.rowcount != 1:
return abort(404)
result = db_cursor.fetchone()
return result['name'] return result['name']
@staticmethod @staticmethod
def get_manufacturer(product_id: int): def get_manufacturer(product_id: int):
cursor.execute(f"select user.displayname as seller from product inner join user on product.seller_id = user.id where product.id = {product_id}") db_cursor.execute(f"select user.displayname as seller from product inner join user on product.seller_id = user.id where product.id = {product_id}")
result = cursor.fetchone()
if db_cursor.rowcount != 1:
return abort(404)
result = db_cursor.fetchone()
return result['seller'] return result['seller']
@staticmethod @staticmethod
def get_price(product_id: int): def get_price(product_id: int):
cursor.execute(f"select price_pc from product where product.id = {product_id}") db_cursor.execute(f"select price_pc from product where product.id = {product_id}")
result = cursor['price_pc']
return result[0] if db_cursor.rowcount != 1:
return abort(404)
result = db_cursor.fetchone()
return result['price_pc']
@staticmethod @staticmethod
def get_image(product_id: int): def get_image(product_id: int):
cursor.execute(f"select image from product where product.id = {product_id}") db_cursor.execute(f"select image from product where product.id = {product_id}")
result = cursor['image']
return base64.b64encode(result[0]).decode('utf-8') if db_cursor.rowcount != 1:
return abort(404)
result = db_cursor.fetchone()
return base64.b64encode(result['image']).decode('utf-8')
@staticmethod @staticmethod
def get_image_name(product_id: int): def get_image_name(product_id: int):
cursor.execute(f"select image_name from product where product.id = {product_id}") db_cursor.execute(f"select image_name from product where product.id = {product_id}")
result = cursor['image_name']
return result[0] if db_cursor.rowcount != 1:
return abort(404)
result = db_cursor.fetchone()
return result['image_name']
@staticmethod @staticmethod
def get_all_info(product_id: int): def get_all_info(product_id: int):
cursor.execute(f"select name, user.displayname as seller, price_pc, image_name, image from product inner join user on product.seller_id = user.id where product.id = {product_id}") db_cursor.execute(f"select name, user.displayname as seller, price_pc, image_name, image from product inner join user on product.seller_id = user.id where product.id = {product_id}")
result = cursor.fetchone()
if db_cursor.rowcount != 1:
return abort(404)
result = db_cursor.fetchone()
return { return {
"name": result['name'], "name": result['name'],
"seller": result['seller'], "seller": result['seller'],
@ -48,5 +74,11 @@ class ProductService:
} }
@staticmethod @staticmethod
def create_listing(): def create_listing(name: str, seller_id: str, price: float, image_name: str, image):
print("asd") try:
db_cursor.execute("insert into product(seller_id, name, price_pc, image, image_name) values (%s, %s, %s, %s, %s)", (seller_id, name, price, image, image_name))
db_connection.commit()
except Error as e:
return {"Failed": f"Failed to create product. {e}"}, 400
return {"Success", "Successfully created new product listing"}, 200

View File

@ -18,8 +18,8 @@ create table user_role(
role varchar(32) not null unique role varchar(32) not null unique
); );
insert into user_role(role) values ('normal') insert into user_role(id, role) values (1, 'normal');
insert into user_role(role) values ('admin') insert into user_role(id, role) values (2, 'admin');
create table user_statistics( create table user_statistics(
id int primary key, id int primary key,
@ -77,7 +77,6 @@ create table purchase_item(
foreign key (product_id) references product(id) foreign key (product_id) references product(id)
); );
delimiter //
create trigger after_user_insert create trigger after_user_insert
after insert after insert
on user for each row on user for each row
@ -85,10 +84,7 @@ begin
insert into user_statistics(id) values (new.id); insert into user_statistics(id) values (new.id);
insert into cart(id) values (new.id); insert into cart(id) values (new.id);
end; end;
//
delimiter;
delimiter //
create trigger after_user_delete create trigger after_user_delete
after delete after delete
on user for each row on user for each row
@ -96,10 +92,7 @@ begin
delete from user_statistics where id = old.id; delete from user_statistics where id = old.id;
delete from cart where id = old.id; delete from cart where id = old.id;
end; end;
//
delimiter;
delimiter //
create trigger after_cart_insert create trigger after_cart_insert
after insert after insert
on cart_item for each row on cart_item for each row
@ -112,10 +105,7 @@ begin
) )
where id = new.cart_id; where id = new.cart_id;
end; end;
//
delimiter;
delimiter //
create trigger after_cart_delete create trigger after_cart_delete
after delete after delete
on cart_item for each row on cart_item for each row
@ -129,10 +119,7 @@ begin
) )
where id = old.cart_id; where id = old.cart_id;
end; end;
//
delimiter;
delimiter //
create trigger calculate_price_subtotal create trigger calculate_price_subtotal
before insert on cart_item before insert on cart_item
for each row for each row
@ -142,6 +129,4 @@ begin
from product p from product p
where p.id = new.product_id where p.id = new.product_id
); );
end; end;
//
delimiter;