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, beacon): if beacon == 'all': __util = UtilProject() beacons = monitor_model.MonitorModel().get_beacons() result = yield beacons result = __util.cast_datetime_to_string(result, ['fecha_sincronizacion']) return self.write({'beacons': result}) else: conn = http.client.HTTPSConnection("cloud.estimote.com") payload = "{\n\t\"id_beacon\" : 2,\n\t\"x\" : 19.4336249,\n\t\"y\" : -99.1848619,\n\t\"fk_id_departamento\": 1\n}" headers = { 'content-type': "application/json", 'authorization': "Basic c2FwcGhpcmUtN3NjOjJiMzIzYzgyMWJjYTFhMzE3OTM3ZGJkZjk1ZmZhYzA2", 'cache-control': "no-cache", 'postman-token': "eda58ff2-7ee8-dd7e-5bf2-bfed18a69269" } conn.request("GET", "/v2/devices/" + beacon, payload, headers) res = conn.getresponse() beacon_data = json.loads(res.read().decode('utf-8')) beacon_data_db = monitor_model.MonitorModel.get_beacon_info beacon_data_db = yield beacon_data_db(monitor_model.MonitorModel(), beacon) beacon_data['store'] = beacon_data_db['tienda'] beacon_data['department'] = beacon_data_db['departamento'] return self.write(beacon_data) self.finish()
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 get(self, filter): self.__util = UtilProject() self.__model = FlyerModel() try: if self.__util.isInt(filter): pass elif filter == 'all': flyers = yield self.__model.get_all_flyers() if len(flyers) == 0: raise Exception('No hay ningún anuncio publicado') self.set_status(200) self.finish({'flyers': flyers}) except Exception as error: self.set_status(400) self.finish({'message': str(error)})
class ProductHandler(tornado.web.RequestHandler): __util = UtilProject() __model = product_model.ProductModel() def set_default_headers(self): self.set_header("Access-Control-Allow-Origin", "*") self.set_header("Access-Control-Allow-Headers", "x-requested-with") self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS') @gen.coroutine def get(self, product): if self.__util.isInt(product): __product = yield self.__model.get_product_by_id(product) self.write(__product) else: if product == 'all': __products = yield self.__model.get_all_products() self.write({'products': __products}) else: if 'product' in self.request.arguments: __products = yield self.__model.get_product_by_name( self.get_argument('product')) else: __products = yield self.__model.get_product_by_name( product) self.write({'products': __products}) def options(self, product): self.set_status(200) self.finish()
class FlyerHandler(AuthHandler): @gen.coroutine def get(self, filter): self.__util = UtilProject() self.__model = FlyerModel() try: if self.__util.isInt(filter): pass elif filter == 'all': flyers = yield self.__model.get_all_flyers() if len(flyers) == 0: raise Exception('No hay ningún anuncio publicado') self.set_status(200) self.finish({'flyers': flyers}) except Exception as error: self.set_status(400) self.finish({'message': str(error)}) @gen.coroutine def post(self, filter): data = json.loads(self.request.body.decode('utf-8')) self.__model = FlyerModel() try: result = yield self.__model.register_flyer(data) if not result: raise Exception('No se pudo publicar el folleto.') self.set_status(200) self.finish({'message': 'Anuncio publicado correctamente.'}) except Exception as error: self.set_status(400) self.finish({'message': str(error)}) def options(self, _): self.set_status(200) self.finish()
def get(self): try: self.__model = UserModel() self.__util = UtilProject() id_cliente = yield self.__model.get_cliente_id_from_persona_id(self.get_argument('id_persona')) if not id_cliente: raise Exception('Ha ocurrido un error al buscar el cliente.') favourites = yield self.__model.get_client_favourites_products(id_cliente) if not favourites or len(favourites) == 0: raise Exception('No tienes ningún favorito registrado.') favourites = self.__util.cast_numeric_to_string(favourites, 'precio_venta') self.set_status(200) self.write({'products': favourites}) except Exception as error: self.set_status(400) self.write({'message' : str(error)})
def get(self, filter): self.__util = UtilProject() if filter == 'all': conn = http.client.HTTPSConnection("") self.__model = BeaconModel() userAndPass = b64encode(b"key").decode("ascii") headers = { 'content-type': "application/json", 'authorization': "Basic %s" % userAndPass, } conn.request("GET", "/v2/devices", None, headers) res = conn.getresponse() data = res.read().decode('utf-8') data = json.loads(data) data = yield self.__model.get_beacons_data(data) self.__util.cast_datetime_to_string(data, ['fecha_sincronizacion']) self.write({'beacons': data})
class BeaconAdminHandler(AuthHandler): @gen.coroutine def get(self, filter): self.__util = UtilProject() if filter == 'all': conn = http.client.HTTPSConnection("") self.__model = BeaconModel() userAndPass = b64encode(b"key").decode("ascii") headers = { 'content-type': "application/json", 'authorization': "Basic %s" % userAndPass, } conn.request("GET", "/v2/devices", None, headers) res = conn.getresponse() data = res.read().decode('utf-8') data = json.loads(data) data = yield self.__model.get_beacons_data(data) self.__util.cast_datetime_to_string(data, ['fecha_sincronizacion']) self.write({'beacons': data}) @gen.coroutine def put(self, id_beacon): data = json.loads(self.request.body.decode('utf-8')) try: self.__model = BeaconModel() status, message = yield self.__model.update_beacon_department( id_beacon, data['department_id']) if not status: raise Exception(message) self.set_status(200) self.finish({'message': message}) except Exception as error: self.set_status(400) self.finish({'message': str(error)}) def options(self, _): # no body self.set_status(200) self.finish()
def get(self): __util = UtilProject() conn = http.client.HTTPSConnection("cloud.estimote.com") userAndPass = b64encode(b"key").decode("ascii") headers = { 'content-type': "application/json", 'authorization': "Basic %s " % userAndPass, } conn.request("GET", "/v3/devices", headers=headers) res = conn.getresponse() data = res.read().decode('utf-8') data = json.loads(data) data = self.__util.create_proximity_zones(data['data']) self.write(data)
class FavouriteHandler(tornado.web.RequestHandler): @gen.coroutine def post(self): try: self.__model = UserModel() data = json.loads(self.request.body.decode('UTF-8')) if not 'id_persona' in data and not 'id_producto' in data and not 'favorito' in data: raise Exception('No cumples con los datos necesarios.') id_cliente = yield self.__model.get_client_id_by_person_id(data['id_persona']) if not id_cliente: raise Exception('Ha ocurrido un error al buscar el cliente.') if data['favorito'] is 1: registered = yield self.__model.existent_favourite(id_cliente, data['id_producto']) if registered: raise Exception('Este producto ya estaba agregado a tus favoritos.') register = yield self.__model.add_client_favourite(id_cliente, data['id_producto']) if not register: raise Exception('Ha ocurrido un error.') self.set_status(200) self.write({'message': 'Producto agregado a favoritos'}) else: errased = yield self.__model.remove_client_favourite(id_cliente, data['id_producto']) if not errased: raise Exception('Ha habido un problema al remover de favoritos.') self.set_status(200) self.write({'message' : 'Se ha removido el producto de favoritos.'}) except Exception as error: self.set_status(400) self.write({'message' : str(error)}) @gen.coroutine def get(self): try: self.__model = UserModel() self.__util = UtilProject() id_cliente = yield self.__model.get_cliente_id_from_persona_id(self.get_argument('id_persona')) if not id_cliente: raise Exception('Ha ocurrido un error al buscar el cliente.') favourites = yield self.__model.get_client_favourites_products(id_cliente) if not favourites or len(favourites) == 0: raise Exception('No tienes ningún favorito registrado.') favourites = self.__util.cast_numeric_to_string(favourites, 'precio_venta') self.set_status(200) self.write({'products': favourites}) except Exception as error: self.set_status(400) self.write({'message' : str(error)})
class BeaconAttachments(AuthHandler): __util = UtilProject() def get(self): conn = http.client.HTTPSConnection("cloud.estimote.com") payload = "{\n\t\"id_beacon\" : 2,\n\t\"x\" : 19.4336249,\n\t\"y\" : -99.1848619,\n\t\"fk_id_departamento\": 1\n}" headers = { 'content-type': "application/json", 'authorization': "Basic c2FwcGhpcmUtN3NjOjJiMzIzYzgyMWJjYTFhMzE3OTM3ZGJkZjk1ZmZhYzA2", 'cache-control': "no-cache", 'postman-token': "eda58ff2-7ee8-dd7e-5bf2-bfed18a69269" } conn.request("GET", "/v3/attachments", payload, headers) res = conn.getresponse() data = res.read().decode('utf-8') data = json.loads(data) data = self.__util.create_proximity_zones(data['data']) self.write(data)
def post(self): try: user_model = UserModel() util = UtilProject() __mimesis_person = Person('es') data = json.loads(self.request.body.decode('utf-8')) found = yield user_model.find_user_by_email_password( data['email'], data['password']) if not found: raise Exception('Usuario y/o contrasena incorrectos.') user_data = yield user_model.get_client_data_by_id(found) if not user_data['imagen']: user_data['imagen'] = __mimesis_person.avatar(size=256) self.write({'user': user_data}) self.finish() except Exception as error: self.set_status(400) print(error) self.write({'message': str(error)})