From 105bbd3e96715ee3b30fa498f922bcdbef739208 Mon Sep 17 00:00:00 2001 From: Thastertyn Date: Sun, 10 Mar 2024 22:47:42 +0100 Subject: [PATCH] Product creation --- app/api/routes/product_routes.py | 19 ++++++++++++++++++- app/services/product_service.py | 22 ++++++++++++++++++---- 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/app/api/routes/product_routes.py b/app/api/routes/product_routes.py index 7c8568d..0e76ffb 100644 --- a/app/api/routes/product_routes.py +++ b/app/api/routes/product_routes.py @@ -1,4 +1,5 @@ from flask import jsonify, abort, request +from flask_jwt_extended import jwt_required, get_jwt_identity from app.api import bp_product @@ -29,7 +30,23 @@ def get_product_info(id: int): return result, status_code + + @bp_product.route('/create', methods=['POST']) +@jwt_required() def create_product_listing(): + user_id = get_jwt_identity() name = request.json.get('name') - \ No newline at end of file + price = request.json.get('price') + + if name is None or price is None: + return abort(401) + + float_price = float(price) + + if not isinstance(float_price, float): + return abort(401) + + result, status_code = ProductService.create_listing(user_id, name, float_price) + + return result, status_code \ No newline at end of file diff --git a/app/services/product_service.py b/app/services/product_service.py index fd050e3..3ff42ed 100644 --- a/app/services/product_service.py +++ b/app/services/product_service.py @@ -3,6 +3,8 @@ import base64 from flask import abort from mysql.connector import Error +from decimal import Decimal + from app.extensions import db_connection class ProductService: @@ -76,11 +78,23 @@ class ProductService: return {"Failed": f"Failed to fetch product info. Error: {e}"}, 500 @staticmethod - def create_listing(name: str, seller_id: str, price: float, image_name: str, image): + def create_listing(seller_id: str, name: str, price: float): 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() + with db_connection.cursor() as cursor: + rounded_price = round(price, 2) + + cursor.execute("insert into product(seller_id, name, price_pc) values (%s, %s, %s)", (seller_id, name, Decimal(str(rounded_price)))) + db_connection.commit() except Error as e: return {"Failed": f"Failed to create product. {e}"}, 400 - return {"Success", "Successfully created new product listing"}, 200 \ No newline at end of file + return {"Success": "Successfully created new product listing"}, 200 + + @staticmethod + def __is_base64_jpg(decoded_string): + try: + # Checking if the decoded data represents a valid JPEG image + image_type = imghdr.what(None, decoded_data) + return image_type == 'jpeg' + except Exception: + return False \ No newline at end of file