def get(self, id): response = {} try: # SELECT * FROM SecondaryCategoryDB WHERE category_id=id document = SecondaryCategoryDB.objects(category_id=id).first() if document is None: data = 'No Content' else: data = get_secondary_category_json(document, secondary_resource_fields) product_ids = data.pop('product_ids', []) data['products'] = ( GetSecondaryCategory.get_products(product_ids)) data['kind'] = 'SecondaryCategory' data['self'] = ( f"{current_app.config['SERVICE_BASE_URL']}" f"/api/secondary-categories/{data['category_id']}") response['status'] = 'success' response['msg'] = {'data': data} return response, 200 except Exception as e: response['status'] = 'fail' response['msg'] = str(e) return response, 500
def get_seconday_categories(seconday_category_ids: list) -> dict: r""" Get all the secondary categories of perticular primary category """ # All the sproducts of perticular secondary category seconday_categories = (SecondaryCategoryDB.objects( category_id__in=seconday_category_ids).all()) # List of marshmallows of ProductDB objects data = [] for seconday_category in seconday_categories: category_data = get_secondary_category_json( seconday_category, secondary_resource_fields) data.append(category_data) return data
def get(self): args = parser.parse_args() response = {} log_info(args) try: category_ids = args['category_id'] min_max_price = args['price'] if not (isinstance(category_ids, list) and isinstance(min_max_price, list) and len(category_ids) > 0 and len(min_max_price) == 2): return {'status': 'fail', 'msg': 'Bad Request'}, 400 category_ids = list(map(int, category_ids)) min_max_price = list(map(int, min_max_price)) min_price, max_price = min(min_max_price), max(min_max_price) # SELECT * FROM SecondaryCategoryDB category_docs = (SecondaryCategoryDB.objects( category_id__in=category_ids).all()) product_docs = (ProductDB.objects( category__in=category_docs, discounted_price__gt=min_price, discounted_price__lt=max_price).all()) if len(product_docs) == 0: data = [] else: data = [ get_product_json(doc, product_resource_fields) for doc in product_docs ] response['status'] = 'success' response['msg'] = {'data': data} return response, 200 except Exception as e: response['status'] = 'fail' response['msg'] = str(e) return response, 500
def get(self, id=None): if id is None: return {'status': 'success', 'msg': {'data': None}}, 204 args = parser.parse_args() response = {} try: # SELECT * FROM ProductDB WHERE product_id=id product = ProductDB.objects(product_id=id).first() if product is None: response['status'] = 'fail' response['msg'] = f'product_id {id} not available in db' return response, 404 # Marshmallow-ing product object product_marshal = get_product_json(product, product_resource_fields) # Get corresponding category from SecondaryCategoryDB # SELECT * FROM SecondaryCategoryDB WHERE category_id=parent_category_id parent_category_id = product.category.category_id category_doc = (SecondaryCategoryDB.objects( category_id=parent_category_id).first()) if category_doc is not None: # Marshmallow-ing category object category_data = get_secondary_category_json( category_doc, secondary_category_resource_fields) product_marshal['category_data'] = category_data response['status'] = 'success' response['msg'] = {'data': product_marshal} return response, 200 except Exception as e: # log_info(e) response['status'] = 'fail' response['msg'] = str(e) return response, 500
def get(self): response = {} try: # SELECT * FROM SecondaryCategoryDB documents = (SecondaryCategoryDB.objects(__raw__={ 'product_ids.0': { '$exists': 1 } }).all()) if len(documents) == 0: data = 'No Content' else: data = [] for doc in documents: category_data = get_secondary_category_json( doc, secondary_resource_fields) product_ids = category_data.pop('product_ids', []) products = (SmallBanner.get_products(product_ids)) category_data['max_discount'] = ( SmallBanner.get_max_discount(products)) category_data['min_discounted_price'] = ( SmallBanner.get_min_discounted_price(products)) category_data['img_base_url'] = ( SmallBanner.get_img_base_url(products)) data.append(category_data) response['status'] = 'success' response['msg'] = {'data': data} return response, 200 except Exception as e: response['status'] = 'fail' response['msg'] = str(e) return response, 500
def get_products(product_ids: list) -> dict: r""" Get all the sproducts of perticular secondary category """ # All the sproducts of perticular secondary category products = ProductDB.objects(product_id__in=product_ids).all() parent_category_ids = [ product.category.category_id for product in products ] # Get corresponding all categories from SecondaryCategoryDB # SELECT * FROM SecondaryCategoryDB WHERE category_id in parent_category_ids category_docs = (SecondaryCategoryDB.objects( category_id__in=parent_category_ids).all()) # List of product marshmallows products_marshal = [] for product in products: # Marshmallow-ing product object product_marshal = get_product_json(product, product_resource_fields) for category_doc in category_docs: if product.category.category_id == category_doc['category_id']: # Marshmallow-ing category object and then # break the inner for-loop category_data = get_secondary_category_json( category_doc, secondary_category_resource_fields) product_marshal['category_data'] = category_data break products_marshal.append(product_marshal) return products_marshal
def post(self): args = parser.parse_args() response = {} try: content, status_code = (Product.decode_token( token=args['Authorization'])) if content['status'] == 'success': # Authorized seller product_args = { 'product_name': args['product_name'], 'short_description': args['short_description'], 'long_description': args['long_description'], 'quantity': args['quantity'], 'base_price': args['base_price'], 'discount': args['discount'], 'seller_id': content['data']['user_id'], 'features': [ feature.strip() for feature in args['features'].split(',') ], 'colors': [color.strip() for color in args['colors'].split(',')], 'sizes': [size.strip() for size in args['sizes'].split(',')], 'category_id': args['category_id'], 'img_base_url': args['img_base_url'], 'img_aux_urls': list( filter(lambda x: x is not None, [ args.get('aux_img_url_1'), args.get('aux_img_url_2'), args.get('aux_img_url_3') ])) } if current_app.config['DEBUG'] is True: log_info(args) log_info(product_args) # Add product product = ProductDB.add_document(**product_args) # product.extra = {} # Marshmallow-ing product object product_marshal = get_product_json(product, product_resource_fields) # Get corresponding category from SecondaryCategoryDB # SELECT * FROM SecondaryCategoryDB WHERE category_id=parent_category_id parent_category_id = product.category.category_id category_doc = (SecondaryCategoryDB.objects( category_id=parent_category_id).first()) if category_doc is not None: # Append this product into corresponding category product_id = product_marshal['product_id'] (category_doc.update( add_to_set__product_ids=[product.product_id])) # Marshmallow-ing category object category_data = object_to_json( category_doc, secondary_category_resource_fields) product_marshal['category_data'] = category_data product.save() # SELECT * FROM Seller2Products WHERE seller_id=product.seller_id s2p = (Seller2Products.objects( seller_id=product.seller_id).first()) if s2p is None: # If this seller has not has any product yet s2p = Seller2Products(seller_id=product.seller_id, product_ids=[product.product_id]) s2p.save() else: # If seller already has added few products # then append product.product_id to the # same category's product_ids list s2p.update(add_to_set__product_ids=[product.product_id]) response['status'] = 'success' response['msg'] = {'data': product_marshal} return response, 201 elif content['status'] == 'fail': return content, status_code except KeyError as e: # log_info(e) response['status'] = 'fail' response['msg'] = str(e) + " is not available in json data" return response, 400 except ValidationError as e: # log_info(e) response['status'] = 'fail' response['msg'] = str(e) return response, 400 except Exception as e: # log_info(e) response['status'] = 'fail' response['msg'] = str(e) return response, 500
def delete(self, id): args = parser.parse_args() response = {} try: content, status_code = (Product.decode_token( token=args['Authorization'])) if content['status'] == 'success': # Authorized seller # SELECT * FROM ProductDB WHERE product_id=id product = ProductDB.objects(product_id=id).first() if product is None: response['status'] = 'fail' response['msg'] = f'product_id {id} not available in db' return response, 404 # SELECT * FROM Seller2Products WHERE seller_id=product.seller_id s2p = (Seller2Products.objects( seller_id=product.seller_id).first()) if s2p is None or id not in s2p.product_ids: # This seller has not has any product yet, or # This product was added by another seller response['status'] = 'fail' response[ 'msg'] = f'product_id {id} was not added by seller id {product.seller_id}' else: # If seller already has added few products # then remove product.product_id from the # same category's product_ids list and # add product.product_id to the # same category's archive_product_ids list s2p.update(pull__product_ids=product.product_id) s2p.update( add_to_set__archive_product_ids=[product.product_id]) # Get corresponding category from SecondaryCategoryDB # SELECT * FROM SecondaryCategoryDB WHERE category_id=parent_category_id parent_category_id = product.category.category_id category_doc = (SecondaryCategoryDB.objects( category_id=parent_category_id).first()) if category_doc is not None: # Remove product.product_id from the # same category's product_ids list category_doc.update(pull__product_ids=product.product_id) # Delete the product product.delete() response['status'] = 'success' response['msg'] = f'product_id {id} has deleted from db' return response, 200 elif content['status'] == 'fail': return content, status_code except Exception as e: # log_info(e) response['status'] = 'fail' response['msg'] = str(e) return response, 500
def put(self, id): args = parser.parse_args() response = {} try: content, status_code = (Product.decode_token( token=args['Authorization'])) if content['status'] == 'success': # Authorized seller product_args = { 'product_name': args['product_name'], 'short_description': args['short_description'], 'long_description': args['long_description'], 'quantity': args['quantity'], 'discount': args['discount'], 'features': [ feature.strip() for feature in args['features'].split(',') ], 'colors': [color.strip() for color in args['colors'].split(',')], 'sizes': [size.strip() for size in args['sizes'].split(',')], 'img_base_url': args['img_base_url'], 'img_aux_urls': list( filter(lambda x: x is not None, [ args.get('aux_img_url_1'), args.get('aux_img_url_2'), args.get('aux_img_url_3') ])) } if current_app.config['DEBUG'] == True: log_info(args) log_info(product_args) # SELECT * FROM ProductDB WHERE product_id=id product = ProductDB.objects(product_id=id).first() # Update values setattr(product.date, 'date_last_update', datetime.utcnow()) # product.extra = {} for key, value in product_args.items(): if hasattr(product, key): setattr(product, key, value) elif hasattr(product.description, key): setattr(product.description, key, value) # Marshmallow-ing product object product_marshal = get_product_json(product, product_resource_fields) # Get corresponding category from SecondaryCategoryDB # SELECT * FROM SecondaryCategoryDB WHERE category_id=parent_category_id parent_category_id = product.category.category_id category_doc = (SecondaryCategoryDB.objects( category_id=parent_category_id).first()) if category_doc is not None: # Marshmallow-ing category object category_data = object_to_json( category_doc, secondary_category_resource_fields) product_marshal['category_data'] = category_data product.save() response['status'] = 'success' response['msg'] = {'data': product_marshal} return response, 200 elif content['status'] == 'fail': return content, status_code except KeyError as e: # log_info(e) response['status'] = 'fail' response['msg'] = str(e) + " is not available in json data" return response, 400 except ValidationError as e: # log_info(e) response['status'] = 'fail' response['msg'] = str(e) return response, 400 except Exception as e: # log_info(e) response['status'] = 'fail' response['msg'] = str(e) return response, 500