def get(self, id_persona): try: dirname = os.path.dirname(__file__) user_model = UserModel() id_cliente = yield user_model.get_client_id_by_person_id( id_persona) if not id_cliente: raise Exception('Cliente no encontrado') try: filename = os.path.join(dirname, 'recoms/' + str(id_cliente) + '.json') file = open(filename, 'r') file = file.read() recom = json.loads(file) except: product_model = ProductModel() util = UtilProject() recom = yield product_model.get_default_recommendations() recom = util.cast_numeric_to_string(recom, 'precio_venta') recom = util.cast_numeric_to_string(recom, 'score') self.set_status(200) self.write({'recommendations': recom}) except Exception as error: self.set_status(400) self.write({'message': str(error)})
def get(self, id_usuario, id_departamento): try: util = UtilProject() user_model = UserModel() product_model = ProductModel() products = yield product_model.get_products_by_department( id_departamento) id_cliente = yield user_model.get_client_id_by_person_id( id_usuario) if not id_cliente: raise Exception('Cliente no encontrado') client = yield user_model.get_client_thetas(id_cliente) if client['thetas']: client['theta'] = np.array([client['thetas']], dtype=np.longdouble) del client['thetas'] for product in products: product['x'] = np.array([product['x']], dtype=np.longdouble) client = yield user_model.get_purchases_and_favs_by_client( client) favs = client['favs'] purchases = client['purchases'] recommendations = [] for product in products: if not any( d['fk_id_producto'] == product['id_producto'] for d in favs) or not any( d['fk_id_producto'] == product['id_producto'] for d in purchases): recommendations.append({ 'id_producto': product['id_producto'], 'score': np.matmul(client['theta'].T, product['x'])[0][0] + product['mu'] }) recommendations = yield product_model.get_recommendations_specific_info( recommendations ) #obtenemos los datos de cada recomendacion recommendations = sorted( recommendations, key=lambda k: k['score'], reverse=True) #ordenamos de mayor a menor recommendations = recommendations[:15] else: recommendations = yield product_model.get_default_recommendations_department( id_departamento) recommendations = util.cast_numeric_to_string( recommendations, 'precio_venta') recommendations = util.cast_numeric_to_string( recommendations, 'score') self.set_status(200) self.write({'recommendations': recommendations}) except Exception as error: import traceback traceback.print_exc() self.set_status(400) self.write({'message': str(error)}) """
def get(self): try: CF = CollaborativeFiltering(10, 0.0000000005) recom_class = RecomAuxClass() user_model = UserModel() product_model = ProductModel() util = UtilProject() people = yield user_model.get_all_people( ) # obtenemos personas con mismo cluster people = yield user_model.get_purchases_and_favs_by_people( people ) # obtenemos compras y favoritos hechas por los clientes products = yield product_model.get_all_products_recom( ) # obtenemos los productos del departamento #products = yield product_model.get_products_by_department(1) recom_class.create_user_article_matrix( people, products) # creamos matriz usuario articulo print('Matrices creadas...\n') print('ejecutando algoritmo...') #people, products,x,y = yield CF.CF_algorithm_cross(people, products) #obtenemos todos los usuarios con sus pesos y los productos con sus xs people, products, x, y, y_cross = yield CF.CF_algorithm_cross( people, products ) #obtenemos todos los usuarios con sus pesos y los productos con sus xs dirname = os.path.dirname(__file__) for person in people: client_obj = recom_class.get_user( people, person['id_cliente']) #obtenemos el usuario recommendations = yield CF.predict( client_obj, products) #obtenemos las prediccions recommendations = sorted( recommendations, key=lambda k: k['score'], reverse=True) #ordenamos de mayor a menor recommendations = recommendations[:100] #seleccionamos sólo 10 recommendations = yield product_model.get_recommendations_specific_info( recommendations ) #obtenemos los datos de cada recomendacion recommendations = util.cast_numeric_to_string( recommendations, 'precio_venta') recommendations = util.cast_numeric_to_string( recommendations, 'score') filename = os.path.join( dirname, 'recoms/' + str(person['id_cliente']) + '.json') file = open(filename, 'w') json.dump(recommendations, file) file.close() save_client = yield user_model.save_client_thetas(client_obj) save_xs = yield user_model.save_product_xs(products) self.write({'x': x, 'y': y, 'y_cross': y_cross}) except Exception as error: traceback.print_tb(error) self.set_status(400) self.write({'message': str(error)})
def update_product(_id, *args, **data): product = ProductModel.find_by_id(_id) if not product: return {'not_found': 'Product not found'} name = data.get('name') npc = data.get('npc') stock = data.get('stock') price = data.get('price') if name: product.name = name if npc: product.npc = npc if stock: product.stock = stock if price: product.price = price try: product.save_to_db() except: return {"error": "An error occurred updating the product."} return product.to_dict()
def buy_product(_id, quantity): product = ProductModel.find_by_id(_id) if not product: return {'not_found': 'Product not found'} if product.stock < quantity: return {'stock_not_enough': {'current_stock': product.stock}} product.stock -= quantity try: product.save_to_db() except: return {'error': 'An error occurred buying a product.'} return { 'successful_purchase': { 'product': { 'id': product.id, 'name': product.name, 'npc': product.npc, 'current_stock': product.stock, 'price': product.price }, 'purchase_quantity': quantity } }
def test_update_product(self): with self.app_context(): self.product.price = 90.55 self.product.save_to_db() product = ProductModel.find_by_id(self.product.id) self.assertEqual(product.price, 90.55)
def delete_product(_id): product = ProductModel.find_by_id(_id) if not product: return {'not_found': 'Product not found'} product.delete_from_db() return {'ok': 'Product deleted'}
def delete(self): datas = self.request.body data_dict = json.loads(datas) res = ProductModel().delete_data(data_dict["id"]) if res is True: return self.get() else: self.write({"errcode": 400, "success": False, "errormsg": "删除失败"})
def test_crud(self): with self.app_context(): # Creating dependencies user = UserModel('test_user', 'password', 'admin') user.save_to_db() product = ProductModel('Product X', 'PieceXYZ123', 100, 75.95) product.save_to_db() # Create purchase = PurchaseLogModel(user, product.id, 1) purchase.save_to_db() # Read purchase = next(iter(PurchaseLogModel.find_by_user(user))) self.assertIsNotNone(purchase) product = PurchaseLogModel.find_by_id(1) self.assertIsNotNone(product)
def get_client_favourites_products(self, id_cliente): __product_model = ProductModel() sql = """ SELECT producto.id_producto, producto.nombre as producto, producto.precio_venta, producto.stock,departamento.nombre AS departamento,tienda.nombre AS tienda, categoria.nombre AS categoria, marca.nombre AS marca,promocion.nombre AS promocion FROM producto,departamento,tienda,categoria,marca,promocion, favorito WHERE producto.fk_id_departamento = departamento.id_departamento AND producto.fk_id_categoria = categoria.id_categoria AND producto.fk_id_marca = marca.id_marca AND producto.fk_id_promocion = promocion.id_promocion AND departamento.fk_id_tienda = tienda.id_tienda AND favorito.fk_id_producto = producto.id_producto AND favorito.fk_id_cliente = %s """ % id_cliente results = yield self._session.query(sql) favourites = results.items() favourites = yield __product_model.assign_image_to_product(favourites) results.free() return favourites
def get_product_list(search_by, order_by, page, per_page): sorting = [] if order_by: for field in order_by: if field == 'likes': field = desc(field) sorting.append(field) else: sorting.append('name') # default order only by name order_by = sorting pagination = {'page': page, 'per_page': per_page} if search_by: products = ProductModel.find_by_name(search_by, *order_by, **pagination) else: products = ProductModel.all_items(*order_by, **pagination) total_pages = ceil(products.total / per_page) link = '/products?page={}&per_page={}' prev_page = page - 1 if page > 1 else 1 next_page = page + 1 if page < total_pages else total_pages return { 'metadata': { 'page': page, 'per_page': per_page, 'total_pages': total_pages, 'total_products': products.total, 'links': { 'self': link.format(page, per_page), 'first': link.format(1, per_page), 'prev': link.format(prev_page, per_page), 'next': link.format(next_page, per_page), 'last': link.format(total_pages, per_page) } }, 'products': tuple(map(ProductModel.to_dict, products.items)) }
def post(self): datas = self.request.body data_dict = json.loads(datas) res = ProductModel().insert_data(data_dict) if res is True: return self.get() else: self.write({ "errcode": 400, "success": False, "errormsg": "新增失败,请重新添加" })
def put(self): datas = self.request.body data_dict = json.loads(datas) res = ProductModel().update_data(data_dict, data_dict["id"]) if res is True: return self.get() else: self.write({ "errcode": 400, "success": False, "errormsg": "修改失败,请查询字段等信息,重新修改" })
def give_like_product(_id): product = ProductModel.find_by_id(_id) if not product: return {'not_found': 'Product not found'} product.likes += 1 try: product.save_to_db() except: return {"error": "An error occurred giving a like to the product."} return product.to_dict()
class ProductTest(BaseTest): def setUp(self): super().setUp() with self.app_context(): self.product = ProductModel('Product X', 'PieceXYZ123', 100, 75.95) self.product.save_to_db() def test_create_product(self): with self.app_context(): self.product.save_to_db() product = ProductModel.find_by_id(self.product.id) self.assertEqual(product.name, 'Product X') def test_fail_create_product(self): with self.assertRaises(BaseException): ProductModel() def test_update_product(self): with self.app_context(): self.product.price = 90.55 self.product.save_to_db() product = ProductModel.find_by_id(self.product.id) self.assertEqual(product.price, 90.55) def test_fail_update_product(self): with self.app_context(): with self.assertRaises(BaseException): self.product = None self.product.save_to_db() def test_delete_product(self): with self.app_context(): self.product.delete_from_db() product = ProductModel.find_by_id(self.product.id) self.assertIsNone(product)
def create_product(*args, **data): product = ProductModel.find_by_name(data.get('name')).items if product: return { 'exists': "A product with name '{}' already exists.".format( data.get('name')) } try: product = ProductModel(data.get('name'), data.get('npc'), data.get('stock'), data.get('price')) product.save_to_db() except: return {"error": "An error occurred inserting the product."} return product.to_dict()
def get(self): datas = self.request.body data_dict = json.loads(datas) critern = set() if "productnames" in data_dict: critern.add(ProductModel.product_name == data_dict["productnames"]) if "id" in data_dict: critern.add(ProductModel.id == data_dict["id"]) res = ProductModel().get_data(*critern) result = [] for r in res: result.append({ "id": r.id, "version": r.version, "pro_sys": r.pro_sys, "opernation": r.opernation, "infos": r.infos, "product_name": r.product_name, "channel": r.channel, }) self.write(json.dumps(result))
def test_crud(self): with self.app_context(): # Create product = ProductModel('Product X', 'PieceXYZ123', 100, 75.95) product.save_to_db() # Read product = next(iter(ProductModel.find_by_name('Product X').items)) self.assertIsNotNone(product) product = ProductModel.find_by_id(1) self.assertIsNotNone(product) # Update product.name = 'Product Y' product.save_to_db() product = next(iter(ProductModel.find_by_name('Product Y').items)) self.assertIsNotNone(product) # Delete product.delete_from_db() self.assertListEqual(ProductModel.find_by_name('Product Y').items, [])
def test_fail_create_product(self): with self.assertRaises(BaseException): ProductModel()
def test_delete_product(self): with self.app_context(): self.product.delete_from_db() product = ProductModel.find_by_id(self.product.id) self.assertIsNone(product)
def setUp(self): super().setUp() with self.app_context(): self.product = ProductModel('Product X', 'PieceXYZ123', 100, 75.95) self.product.save_to_db()
def get(self, id_persona): __model_user = UserModel() __model_product = ProductModel() categories = [] purchases_stats = [] favs = [] permits = yield __model_user.get_client_permits(id_persona) benefits = yield __model_user.get_client_benefits(id_persona) if permits['compras']: purchases_stats = yield __model_user.get_client_purchases_stats_year( id_persona) cats = yield __model_user.get_client_most_purchased_categories( id_persona) for cat in cats: if cat['fk_id_padre_cat'] is not None: cat_pat = cat subcategories = [] while cat_pat['fk_id_padre_cat'] is not None: cat_pat = yield __model_product.get_parent_categorie( cat_pat['id_categoria']) subcategories.append({ 'id_categorie': cat_pat['id_categoria'], 'name': cat_pat['nombre'] }) if not any(d['id_categorie'] == cat_pat['id_categoria'] for d in categories): subcategories.remove({ 'id_categorie': cat_pat['id_categoria'], 'name': cat_pat['nombre'] }) categories.append({ 'id_categorie': cat_pat['id_categoria'], 'name': cat_pat['nombre'], 'total': cat['total'], 'subcategories': subcategories }) else: for d in categories: if d['id_categorie'] == cat_pat['id_categoria']: d['total'] += cat['total'] for sub in subcategories: if not any( cat_sub['id_categorie'] == sub['id_categorie'] for cat_sub in d['subcategories'] ) and d['id_categorie'] != sub[ 'id_categorie']: d['subcategories'].append({ 'id_categorie': sub['id_categorie'], 'name': sub['name'] }) else: categories.append({ 'id_categorie': cat['id_categoria'], 'name': cat['nombre'], 'total': cat['total'], 'subcategories': [] }) if permits['favoritos']: favs = yield __model_user.get_client_favorite_products(id_persona) categories.sort(key=self.sort_by_total, reverse=True) print({ 'benefits': benefits, 'categories': categories[:5], 'purchases_stats': purchases_stats, 'favorites': favs }) self.write({ 'benefits': benefits, 'categories': categories[:5], 'purchases_stats': purchases_stats, 'favorites': favs }) self.finish()
def get_product(_id): product = ProductModel.find_by_id(_id) if not product: return {'not_found': 'Product not found'} return product.to_dict()
def test_create_product(self): with self.app_context(): self.product.save_to_db() product = ProductModel.find_by_id(self.product.id) self.assertEqual(product.name, 'Product X')