def test_get_product(self): product = ProductModel.get(1) assert product.name == 'Produto 01' products = ProductModel.list() assert len(products) == 1 assert type(products) == type([])
def get(self): formato_fecha = "%Y-%m-%d" times = time.strftime(formato_fecha) producto = [x.json() for x in ProductModel.find_all()] fechas = [x['fecha_vencimiento'] for x in producto] variable = [x for x in fechas] ss = datetime.strptime(variable[0], formato_fecha) sd = datetime.strptime(times, formato_fecha) aa = ss - sd print("ssss: {}".format(aa.days)) listaaa = [] for s in fechas: aa = datetime.strptime(s, formato_fecha) - datetime.strptime( times, formato_fecha) aaa = [t for t in s if aa.days < 20] hh = "".join(aaa) if hh: data = ProductModel.find_by_date(hh) #print("kenyyy: {}".format(data.json())) print("aaaa: {}".format(data)) listaaa.append(data.json()) #return {"Productos por vencer": data.json()} #for n in aaa: # print("xdddd: {}".format(n)) #print("fechasssss: {}".format(aa.days)) #if aa.days < 20: # print("it is True") # aaa = [s for s in fechas if aa.days < 20] # print("asdasd: {}".format(aaa)) # else: # print("you are nob") return {'productos': listaaa}
def create_database(): if not os.path.exists('./database.db'): print("Create a database\n") database.create_all() sleep(0.1) file_name = "products_79936.json" if not os.path.exists(file_name): # Download of mock database Process.run( 'curl https://servicespub.prod.api.aws.grupokabum.com.br/descricao/v1/descricao/produto/79936 >> %s' % file_name) ## Save database ## # Read $filename config_file = './%s' % file_name config_helper = ConfigHelper(config_file) config = config_helper.load_config() # Read only products of config config = config['familia']['produtos'] for data in config: product = ProductModel(**data) try: # Save products in database product.save_product() sleep(0.01) except: print({"message": "An error ocurred trying to create product."}, 500) # Internal Server Error
def delete(self, product_id): try: ProductModel.delete_from_db(product_id) except: return {"message": "An error occurred deleting the Product"}, 500 return {"message": "Product deleted"}, 200
def get(self): recv_data = request.get_json() if recv_data is not None: product=ProductModel.find_by_name(recv_data['name']) if ProductModel.find_by_name(recv_data['name']): return product.json() return {"message":"Product does not exist!!"},404 else: return {'products':[product.json() for product in ProductModel.query.all()]}
def put(self, id_product): product_data = Product.attribute.parse_args() products = ProductModel(**product_data) product = ProductModel.find_product(id_product) id_provider = ProductModel.find_id_provider(products.id_provider) if not id_provider: return { "message": "The id '{}' does not found.".format(products.id_provider) }, 404 if not product: return { "message": "Product id '{}' does not found.".format(id_product) }, 404 product_found = ProductModel.find_product(id_product) if product_found: product_found.update_product(**product_data) product_found.save_product() return product_found.json(), 200 product = ProductModel(id_product, **product_data) try: product.save_product() except: return {'message': 'Internal error'}, 500 return product.json(), 201
def put(self): data = Product.parser.parse_args() product = ProductModel(**data) try: product.update_to_db() except: return {"message": "An error occurred updating the operation"}, 500 return {"message": "update OK"}, 200
def get(self): if 'id' in request.args: item = ProductModel.get(request.args['id']) item = serialize_model(item) return item elif 'id_provider' in request.args: itens = ProductModel.list_by_provider(request.args['id_provider']) itens = serialize_model_list(itens) return itens list = ProductModel.list() return serialize_model_list(list)
def get(self): custom_filter = ProductList.parser.parse_args() if custom_filter.get('deleted'): return [ transaction.json() for transaction in ProductModel.filter_by_deleted( str_to_bool(custom_filter.get('deleted'))) ] else: return [product.json() for product in ProductModel.find_all()]
def post(self): data = parser.parse_args() product = ProductModel(data['name'], data['description'], data['price'], data['parent_id']) try: product.save() except Exception as e: return {'message': 'An error occurred inserting into db: {}'.format(e)}, 500 return product.json(), 201
def post(self): data = Product.parser.parse_args() product = ProductModel(**data) try: product.save_to_db() except: return {"message": "An error occurred creating the operation"}, 500 return product.json(), 201
def post(self): try: data = request.get_json() item = ProductModel() for parameter in data: setattr(item, parameter, data[parameter]) item.save() return "success", 201 except: return "error", 401
def put(self, codigo): dados = Product.argumentos.parse_args() product_object = ProductModel(codigo, **dados) new_product = product_object.json() prod = Product.find_product(codigo) if prod: prod.update(new_product) return new_product, 200 try: products.append(new_product) except: return {'messege': 'An internal error ocurred trying to save produto'}, 500 # An server error return new_product, 200
def post(self, codigo): if Product.find_product(codigo): return {"message":"Codigo '{}' alredy existis." .format(codigo)}, 400 # Bad Request dados = Product.argumentos.parse_args() product_object = ProductModel(codigo, **dados) new_product = product_object.json() try: products.append(new_product) except: return {'messege': 'An internal error ocurred trying to save produto'}, 500 # An server error return new_product, 200
def post(self, product_id): data = ResponsedOrder.parser.parse_args() if not data["accepted"]: return {"message": "Your request has been denied"}, 400 data.update({"notified": False, "expired": False}) OrderModel.update_order(data) ProductModel.search_from_database_by_id( data["product_id"]).update_status(data["accepted"]) return {"message": "The lender has been accepted your request"}, 200
def post(self): product_data = Product.attribute.parse_args() product = ProductModel(**product_data) if not ProviderModel.find_by_id_provider(product.id_provider): return { 'message': 'The product must be associated with a valid id. ' }, 400 try: product.save_product() except: return {'message': 'Internal error'}, 500 return product.json(), 200
def post(self, name): if self.find_by_name(name): return { 'message': "An product with the name '{}' already exists.".format(name) } data = Product.parser.parse_args() product = ProductModel(name, **data) try: product.save_to_db() except: return { 'message': 'An error has occurred inserting the product' }, 500 return product.json(), 201
def first_product(): if ProviderModel.get_by_cnpj("04790618000153") == None: first_provider() return new_product = ProductModel() new_product.name = "Produto 01" new_product.provider = ProviderModel.get_by_cnpj("04790618000153") new_product.quantity = 100 new_product.price = 10.0 new_product.available = True new_product.save() return
def get(self, item_id): item = ItemModel.find_by_id(item_id) if item is None: return {'status': False, 'message': 'Item not found', 'data': None} product_id = item.json()['product_id'] product = ProductModel.find_by_id(product_id) promotion_items = PromotionModel.find_promotion_items(product_id) sold_price = product.json()['price'] if promotion_items: for p_item in promotion_items: sold_price -= (p_item.json()['discount'] / 100) * product.json()['price'] p_item.used_items += 1 p_item.save_to_db() order = OrderModel(item_id, float("{:.2f}".format(sold_price))) order.save_to_db() item.delete_from_db() return { 'status': True, 'message': 'A item has been sold.', 'data': order.json() }
def get(self, catalog_type): return { "products": [ product.json() for product in ProductModel.search_from_database_by_catalog(catalog_type) ] }
def get(self, name): return { "products": [ product.json() for product in ProductModel.search_from_database_by_name(name) ] }, 200
def get(self, _id): product = ProductModel.find_by_id(_id) if not product: return {'message': 'Product not found'}, 404 return product.json_with_children()
def put(self, product_id: int): """ Actualiza los detalles de un producto si pertenece al vendedor. """ product = ProductModel.find_by_id(product_id) if not product: return {"message": f"El producto con ID {product_id!r} no ha sido encontrado."}, 404 if product.user_id != current_identity.id or current_identity.user_type != user_types['vendor']: return {"message": "No tiene permitido modificar este producto."}, 401 data = Product.parser.parse_args() if imgurlRegex.match(data['image']) is None: return {"message": "La imagen debe ser una URL."}, 400 product.category_id = data['category_id'] product.name = data['name'] product.description = data['description'] product.price = data['price'] product.image = data['image'] product.visible = data['visible'] product.save_to_db() return product.json()
def get(self, user_id: int): """ Devuelve la lista de productos de un vendedor, sean visibles o no. Solo lo puede realizar el mismo vendedor. """ if current_identity.id != user_id: return {"message": "No tiene permitido consultar la lista de productos."}, 401 return [product.json() for product in ProductModel.get_by_user(user_id)]
def post(self): """ Agrega un nuevo producto a los favoritos del usuario. """ if current_identity.user_type == user_types['vendor']: return { "message": "No puede marcar un producto como favorito." }, 401 data = FavouriteList.parser.parse_args() if not ProductModel.find_by_id(data['product_id']): return { "message": f"El producto con ID {data['product_id']!r} no ha sido encontrado." }, 404 if FavouriteModel.find_if_exists(current_identity.id, data['product_id']): return { "message": f"El producto con ID {data['product_id']!r} ya está marcado como favorito." }, 400 new_favourite = FavouriteModel(current_identity.id, data['product_id']) new_favourite.save_to_db() return new_favourite.json()
def get(self, product_id): if redis.get('catalog.product-' + str(product_id)) != None: return json.loads(redis.get('catalog.product-' + str(product_id))), 201 product = ProductModel.get_product(product_id) if (product == None): return {'message': 'Product not found.'}, 404 product.pop('_id') compact = { 'name': product['name'], 'price': product['price'], 'status': product['status'], 'categories': product['categories'], } redis.set('catalog.product-' + str(product_id), json.dumps({ 'complete': product, 'compact': compact }), ex=(60 * int(os.environ["CACHE_CATALOG_PRODUCTS_EXPIRE"]))) return {"compact": compact, "complete": product}, 200
def delete(self): try: if 'id' in request.args: item = ProductModel.delete(request.args['id']) return "success", 201 return "No ID", 401 except: return "error", 401
def put(self, user_id: int): """ Actualizar los datos del usuario. Permitir solo si es el mismo usuario quien lo solicita. """ if current_identity.id != user_id: return { "message": "No tiene permiso para modificar los datos de esta cuenta." }, 401 data = User.parser.parse_args() user = UserModel.find_by_id(user_id) if identityRegex.match( data['first_name']) is None or identityRegex.match( data['last_name']) is None: return { "message": "El formato del nombre o apellido no es correcto." }, 400 if emailRegex.match(data['email']) is None: return { "message": "El correo proporcionado no parece ser un correo realmente." }, 400 if UserModel.find_by_email( data['email']) and user.email != data['email']: return { "message": "El correo proporcionado ya pertenece a una cuenta registrada." }, 400 if user.user_type == user_types['vendor'] and data.get( 'user_type') == user_types['normal']: ProductModel.delete_user_products(user_id) if data.get('user_type'): user.user_type = data['user_type'] user.first_name = data['first_name'] user.last_name = data['last_name'] user.email = data['email'] user.is_active = data['is_active'] user.save_to_db() return user.json()
def get(self): recv_data = request.get_json() if recv_data is not None: product = ProductModel.find_by_id(recv_data['product_id']) if ProductModel.find_by_id(recv_data['product_id']): product_id = recv_data['product_id'] print(r.get("product_id/%d" % product_id)) result = eval(r.get("product_id/%d" % product_id)) return product.get_info() return {"message": "Product does not exist!!"}, 404 else: return { 'products': [product.get_info() for product in ProductModel.query.all()] }
def get(self): producto = [x.json() for x in ProductModel.find_all()] #if x['cantidad'] <= 20 and x['cantidad'] > 0 zz = [produss['cantidad'] for produss in producto] poco = [x for x in zz if x <= 20 and x > 0] a = [] for i in poco: #print("ttt: {}".format(i)) #ss = [y.json() for y in ProductModel.fin_by_cantidad(i)] #tt = ProductModel.find_by_date(i) tt = ProductModel.fin_by_cantidad(i) a.append(tt.json()) return {"productos": a}