def load_categories(self): with open(self.category_file, newline='') as csvfile: reader = csv.reader(csvfile, delimiter=csv.excel.delimiter, quotechar=csv.excel.quotechar) header = next(reader, None) # use headers to set availability for row in reader: id = eval(row[0]) category = Category(id=id, brief_description=row[4], name=row[3], description=row[5], color=row[7], image=row[8]) if row[2] != '': parent_id = eval(row[2]) category.parent_id = parent_id if row[6] != '': icon_id = eval(row[6]) category.icon_id = icon_id if row[9] != '': display_order = eval(row[9]) category.display_order = display_order db.session.add(category) # As we manually set the ids, we need to update the sequence manually as well. db.session.commit() db.session.execute( "SELECT setval('category_id_seq', " "COALESCE((SELECT MAX(id) + 1 FROM category), 1), false);") db.session.commit() print( "Categories. There are now %i category records in the database." % db.session.query(Category).count())
def register_categories_database(): dao = CategoryDao() programming = Category('Programação') ciencias = Category('Ciências') dao.save(programming) dao.save(ciencias)
def construct_category(self, name="Ultimakers", parent=None): category = Category(name=name) if parent is not None: category.parent = parent db.session.add(category) db_category = db.session.query(Category).filter_by(name=category.name).first() self.assertIsNotNone(db_category.id) return db_category
def test_add_ng_invalid_value(self): # id model = Category('a', 'test') self.assertFalse(model.is_valid()) # name model = Category(1, '') self.assertFalse(model.is_valid()) model = Category(1, None) self.assertFalse(model.is_valid())
def setUp(self): self.book_dao = BookDao() category_dao = CategoryDao() category_dao.save(Category('Ciências')) author_dao = AuthorDao() author_dao.save(Author('Luciano Pereira', '*****@*****.**')) self.book_sciences = Book( 'Ciências Básica', 'Resumo '*80, 'Sumário do Livro', 700, "978-85-08-22282-8", Author('Luciano Pereira', '*****@*****.**'), Category('Ciências'), 2, 220.56 ) self.book_dao.save(self.book_sciences)
def register_books_database(): book_dao = BookDao() python_fluente = Book('Python Fluente', 'Resumo ' * 80, 'Sumário do Livro', 800, "978-85-08-13196-9", Author('Luciano Ramalho', '*****@*****.**'), Category('Programação'), 2, 120.56) ciencias_basica = Book('Ciências Básica', 'Resumo ' * 80, 'Sumário do Livro', 700, "978-85-08-22232-8", Author('Luciano Pereira', '*****@*****.**'), Category('Ciências'), 1, 220.56) book_dao.save(python_fluente) book_dao.save(ciencias_basica)
def edit(id): request_data = request.get_json() if request_data is None: raise BadRequest() category = Category(**request.json) if not category.is_valid(): raise BadRequest( description='保存エラー。エラー内容を確認してください。', response=category.validation_errors ) mapper = CategoryMapper() saved = mapper.save(category) if not saved: raise Conflict() return ApiResponse(200, message='更新しました')
def update_category_counts(self, category, results): if not category: category = Category(name="Topics") category.children = db.session.query(Category)\ .filter(Category.parent_id == None)\ .order_by(Category.name.desc())\ .all() else: c = category while c.parent: c = c.parent c.parent = Category(name="Topics") for child in category.children: for bucket in results.aggregations.terms.buckets: if bucket.key == child.search_path(): child.hit_count = bucket.doc_count return category
def add_category(): if not request.is_json: return jsonify({"msg": "Missing JSON in request"}), 400 data = request.get_json() new_category = Category( data['title'], data['icon']) mongo.db.categories.insert_one(new_category.__dict__) response = flask.make_response(jsonify({'inserted': True})) response.headers['Access-Control-Allow-Origin'] = '*' return response, 201
def _setup(self, title='Python Fluente', resume='Resumo ' * 80, summary='Sumário do Livro', number_of_page=800, isbn="978-85-08-13196-9", author=Author('Luciano Ramalho', '*****@*****.**'), category=Category('Programação'), edition=2, price=120.56): category_dao = CategoryDao() category_dao.save(Category('Programação')) author_dao = AuthorDao() author_dao.save(Author('Luciano Ramalho', '*****@*****.**')) return Book(title, resume, summary, number_of_page, isbn, author, category, edition, price)
def get_category_by_name(self, category_name, parent=None, create_missing=False): category = db.session.query(Category).filter(Category.name == category_name).first() if category is None: if create_missing: category = Category(name=category_name, parent=parent) db.session.add(category) db.session.commit() else: raise(Exception("This category is not defined: " + category_name)) return category
def add(): request_data = request.get_json() if request_data is None: raise BadRequest() category = Category(**request.json) if not category.is_valid(): raise BadRequest( description='保存エラー。エラー内容を確認してください。', response=category.validation_errors ) mapper = CategoryMapper() if mapper.is_upper_limit(): raise BadRequest(description='商品カテゴリの登録数は10件までです') saved = mapper.save(category) if not saved: raise Conflict() return ApiResponse(201, message='保存しました')
def updateCategoryVisibility(id): if not request.is_json: return jsonify({"msg": "Missing JSON in request"}), 400 data = request.get_json() newTitle = data['title'] icon = data['icon'] is_visible = data['visible'] updatedCategory = Category(newTitle, icon) updatedCategory.visible = is_visible oldCategory = mongo.db.categories.find_one_and_update( {'_id': ObjectId(id)}, {'$set': updatedCategory.__dict__}) if oldCategory is not None: oldTitle = oldCategory['title'] updatePointsOfCategory(oldTitle, newTitle, is_visible) else: pass response = flask.make_response(jsonify({'updated': True})) response.headers['Access-Control-Allow-Origin'] = '*' return response, 201
def add(self, title: str) -> bool: try: session = DatabaseFactory.session cat = session.query(Category).filter( title == Category._title).first() if cat is None: category = Category(title=title) session.add(category) session.flush() session.commit() return True except Exception as e: print('Exception', e) return False
def updateCategory(id): data = request.files img = data['file'] newTitle = request.form['title'] newIcon = newTitle + str(random.randint( 0, 1000)) #para que cambie el icono y refrezque updatedCategory = Category(newTitle, newTitle) oldCategory = mongo.db.categories.find_one_and_update( {'_id': ObjectId(id)}, {'$set': { 'title': newTitle, 'icon': newIcon }}) if oldCategory is not None: oldTitle = oldCategory['title'] updatePointsOfCategoryWithTitle(oldTitle, newTitle) try: img.save('/usr/src/web/app/static/icons/' + newIcon) except Exception as e: print(e, flush=True) response = flask.make_response(jsonify({'updated': True})) response.headers['Access-Control-Allow-Origin'] = '*' return response, 201 else: response = flask.make_response( jsonify({ 'updated': False, 'message': 'category not found' })) response.headers['Access-Control-Allow-Origin'] = '*' return response, 404
def test_edit_ok(self): self.__init_data() data = Category(1, 'Morning set') result = self.mapper.save(data) self.assertTrue(result)
def test_add_ok(self): data = Category(None, 'test') result = self.mapper.save(data) self.assertTrue(result)
def not_found(): return make_response(jsonify({'error': 'Not found'}), 404) if __name__ == '__main__': points = [] categories = [] suggestions = [] point1 = Point({'lat': -34.6, 'lng': -58.5}, 'Rodicio', 'Comida rica', "Rodicio", "Restaurantes") point2 = Point({'lat': -34.52, 'lng': -58.55}, 'PF Changs', 'Comida asiática', "PF Changs", "Restaurantes") point3 = Point({'lat':-34.55, 'lng': -58.52}, 'Sakiko', 'Comida japonesa', "Sakiko", "Restaurantes") point4 = Point({'lat': -34.56, 'lng': -58.4432}, 'Club Amigos', 'Tenis, Football y más', "Club Amigos", "Deportes") point5 = Point({'lat': -34.573, 'lng': -58.4548}, 'Future Bar', 'Cerveza artesanal', "Future Bar", "Bares") cat1 = Category("Restaurantes", "Restaurantes") cat2 = Category("Bares", "Bares") cat3 = Category("Deportes", "Deportes") sug1 = Suggestion("Colegios", "Colegios") sug2 = Category("Entretenimiento", "Entretenimiento") points.append(point1) points.append(point2) points.append(point3) points.append(point4) points.append(point5) categories.append(cat1) categories.append(cat2) categories.append(cat3)
def init_database(app): icons_dir = "http://localhost:" + os.environ.get('PORT') + "/static/icons" images_dir = "http://localhost:" + os.environ.get( 'PORT') + "/static/pointImages" cat_id = dict() with app.app_context(): mongo.db.points.remove({}) mongo.db.categories.remove({}) mongo.db.suggestions.remove({}) categories = [] categories.append(Category("Restaurantes", icons_dir + "/Restaurantes")) categories.append(Category("Bares", icons_dir + "/Bares")) categories.append(Category("Deportes", icons_dir + "/Deportes")) with app.app_context(): for category in categories: mongo.db.categories.insert_one(category.__dict__) cat_id[category.title] = mongo.db.categories.find_one( {'title': category.title})['_id'] points = [] points.append( Point({ 'lat': -34.6, 'lng': -58.5 }, 'Rodicio', 'Comida rica', images_dir + "/9170", cat_id['Restaurantes'], "Restaurantes")) points.append( Point({ 'lat': -34.52, 'lng': -58.55 }, 'PF Changs', 'Comida asiática', images_dir + "/9170", cat_id['Restaurantes'], "Restaurantes")) points.append( Point({ 'lat': -34.55, 'lng': -58.52 }, 'Sakiko', 'Comida japonesa', images_dir + "/9170", cat_id['Restaurantes'], "Restaurantes")) points.append( Point({ 'lat': -34.56, 'lng': -58.4432 }, 'Club Amigos', 'Tenis, Football y más', images_dir + "/8888", cat_id['Deportes'], "Deportes")) points.append( Point({ 'lat': -34.573, 'lng': -58.4548 }, 'Future Bar', 'Cerveza artesanal', images_dir + "/5888", cat_id['Bares'], "Bares")) suggestions = [] suggestions.append(Suggestion("Colegios", "SinImagen")) suggestions.append(Suggestion("Entretenimiento", "SinImagen")) print("Cargando datos de prueba", flush=True) with app.app_context(): for point in points: mongo.db.points.insert_one(point.__dict__) for sug in suggestions: mongo.db.suggestions.insert_one(sug.__dict__)
def test_should_throw_an_exception_when_the_name_category__is_none(self): with self.assertRaises(ValueError): Category(None)
def test_should_throw_an_exception_when_the_name_category_is_empty_full_spaces(self): with self.assertRaises(ValueError): Category(' ')
class CategoryResonse: len: int categories: [] def __init__(self, len: int, categories: []): self.len = len self.categories = categories def __del__(self): pass def __str__(self): return f'len={self.len},' + \ f'categories={self.categories}' def toJson(self): return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=4) if __name__ == '__main__': print(__name__) categories = CategoryResonse(1, [Category(1, "test", 1)]) print(categories) print(categories.toJson())