Example #1
0
    def __extractCategories(self, stringList, cursor, prodId):
        categoryList = []

        for string in stringList:
            if '[' in string and ']' in string:
                try:
                    # print(string)
                    idInitPos = string.find('[')
                    # print(idInitPos)
                    idEndPos = string.find(']')
                    # print(idEndPos)
                    id = string[idInitPos + 1:idEndPos]
                    title = string[0:idInitPos]

                    if str(id).isnumeric():
                        currentCategory = Category(int(id), title)
                        currentCategoryByProd = CategoryByProduct(
                            int(id), prodId)
                        categoryList.append(
                            currentCategoryByProd.getValuesString())

                        # if currentCategoryByProd.executeInsertStatement(cursor):
                        #     pass
                        # else:
                        #     print("insertion failed:", currentCategoryByProd.toString())
                        # categoryList.append(currentCategory)

                        self.mapCategorioes[id] = currentCategory

                    else:  # tratando um caso chato em que a string vem assim "title [guitar][213213]"
                        string = string.replace("[", "(", 1)
                        string = string.replace("]", ")", 1)
                        idInitPos = string.find('[')
                        idEndPos = string.find(']')
                        id = string[idInitPos + 1:idEndPos]
                        title = string[0:idInitPos]

                        if str(id).isnumeric():
                            currentCategory = Category(int(id), title)
                            currentCategoryByProd = CategoryByProduct(
                                int(id), prodId)
                            categoryList.append(
                                currentCategoryByProd.getValuesString())

                            # if currentCategoryByProd.executeInsertStatement(cursor):
                            #     pass
                            # else:
                            #     print("insertion failed:", currentCategoryByProd.toString())
                            # categoryList.append(currentCategory)

                            self.mapCategorioes[id] = currentCategory
                        else:
                            print("inconsistent category: ", string)

                except Exception as e:
                    print(e)

        return ",".join(categoryList)
Example #2
0
def _create_categories():
    categories = [
        Category(id="coffee",
                 name="Кофе",
                 is_base_expenses=False,
                 aliases=['coffee', 'кофе', 'tea', 'чай']),
        Category(id="cafe",
                 name="Кафе и рестораны",
                 is_base_expenses=False,
                 aliases=['cafe', 'кафе', 'ресторан', 'рестик', 'мак']),
        Category(id="base",
                 name="Базовые расходы",
                 is_base_expenses=True,
                 aliases=['food', 'еда', 'продукты', 'быт', 'base']),
        Category(id="subs",
                 name="Подписки, телеком",
                 is_base_expenses=True,
                 aliases=['subs', 'phone', 'телефон', 'инет']),
        Category(id="house",
                 name="Дом, покупки",
                 is_base_expenses=True,
                 aliases=['house', 'ремонт', 'дом', 'покупки', 'комуналка']),
        Category(id="transport",
                 name="Машина, транспорт",
                 is_base_expenses=True,
                 aliases=['car', 'машина', 'сто', 'то', 'такси', 'проезд']),
        Category(id="rest",
                 name="Отдых, поездки, путешествия",
                 is_base_expenses=True,
                 aliases=['отдых', 'поездки', 'путешествия', 'отпуск']),
        Category(id="beauty",
                 name="Красота, уход, здоровье",
                 is_base_expenses=True,
                 aliases=['beauty', 'красота', 'маник', 'ногти', 'аптека']),
        Category(id="self-improvement",
                 name="Саморазвитие",
                 is_base_expenses=True,
                 aliases=[
                     'англ',
                     'курсы',
                     'треша',
                     'треня',
                 ]),
        Category(id="other",
                 name="Прочее",
                 is_base_expenses=False,
                 aliases=['other', 'прочее']),
    ]
    Category.drop_collection()
    Category.objects.insert(categories)
Example #3
0
def add_category(type_flow_str: str, category_name: str):
    type_flow = calc_flow(type_flow_str)
    # сохранение категории в базу
    session = Database.get_instance().session()
    session.add(Category(category_name, type_flow))
    session.commit()
    return f'Категория {category_name} добавлена!'
Example #4
0
def category():
    if request.method == "POST":
        category_name = request.form['category_name']
        add_category = Category([category_name]).create_category()

        return redirect(url_for('index'))
    return render_template('category.html')
Example #5
0
def category_posts(id):
    posts = Post().view_by_category(id)
    # return json.dumps(post)
    category = Category().view_single_category(id)
    return render_template('category_posts.html',
                           posts=posts,
                           category=category)
Example #6
0
 def test_add_flow_1000_bad_category_transport_in_base(self):
     self.session.add(Category('работа', TypeFlow.PROFIT))
     self.session.commit()
     text_answer('Wallet добавь 1000 в работа')
     flow = self.session.query(Flow).all()[0]
     self.assertEqual(1000, flow.money)
     self.assertEqual('работа', flow.category.name)
 def create_category(self):
     text = self.window.ed_category.text()
     if text:
         category = Category(name=text)
         db.session.add(category)
         db.session.commit()
         self.window.ed_category.setText('')
         self.get_all_categories()
Example #8
0
 def post(self):
     parser.add_argument('name', type=str)
     args = parser.parse_args()
     name = args['name']
     try:
         category = Category(name=name)
         category.save()
         return category.json()
     except:
         return abort(400, message="Name cannot be null!")
Example #9
0
 def _get_categories(self, names_list: list):
     categories = []
     if names_list:
         for category_name in names_list:
             existing_category = Category.query.filter_by(
                 name=category_name).first()
             if not existing_category:
                 existing_category = Category(name=category_name)
                 existing_category.save()
             categories.append(existing_category)
     return categories
Example #10
0
def reset_database():
    # Delete 'emails.db' sqlite database
    if os.path.exists('emails.db'):
        os.remove('emails.db')
        logger.info("Deleted database 'emails.db'")

    # Re-create 'emails.db' sqlite database
    db = SqliteDatabase('emails.db')
    logger.info("Created database 'emails.db'")
    Email.create_table()
    SenderMetadata.create_table()
    Comment.create_table()
    Form.create_table()
    Category.create_table()

    Category(name="Meetings").save()
    Category(name="Opinions").save()
    Category(name="Question").save()
    Category(name="Action").save()
    Category(name="Thank You").save()
Example #11
0
def findAll():
    conn = ConnectionDB().getConnection()
    cursor = conn.cursor()

    try:
        categories = []
        for row in cursor.execute("SELECT * FROM categories"):
            categories.append(Category(row[0], row[1]))
        return categories
    except sqlite3.Error as error:
        print(error.with_traceback())
Example #12
0
def findOneByName(name):
    conn = ConnectionDB().getConnection()
    cursor = conn.cursor()

    try:
        cursor.execute('SELECT * FROM categories WHERE name = ?', (name, ))
        row = cursor.fetchone()
        category = Category(row[0], name)
        return category
    except sqlite3.Error as error:
        print(error.with_traceback())
Example #13
0
def findOneById(id_cat):
    conn = ConnectionDB().getConnection()
    cursor = conn.cursor()

    try:
        cursor.execute('SELECT * FROM categories WHERE id = ?', (id_cat, ))
        row = cursor.fetchone()
        category = Category(id_cat, row[1])
        return category
    except sqlite3.Error as error:
        print(error.with_traceback())
Example #14
0
def category_create(user):
    category_fields = category_schema.load(request.json)
    new_category = Category()
    new_category.title = category_fields["title"]
    new_category.description = category_fields["description"]
    new_category.private = category_fields["private"]
    new_category.owner = user.id

    user.category.append(new_category)

    db.session.commit()
    return jsonify(category_schema.dump(new_category))
Example #15
0
def create():
    schema = CategorySchema()

    try:
        data = schema.load(request.get_json())
        category = Category(**data)
        db.commit()
    except ValidationError as err:
        return jsonify({
            'message': 'Validation failed',
            'errors': err.messages
        }), 422
    return schema.dumps(category), 201
Example #16
0
def load_data_into_models(data):
    categories = []
    for item in data['category_data']:
        c = Category(**item)
        categories.append(c)

    players = []
    for player in data['player_data']:
        p = Player(**player)
        players.append(p)

    populated_models = {'players': players, 'categories': categories}
    return populated_models
Example #17
0
def findByRecipe(id_recipe):
    conn = ConnectionDB().getConnection()
    cursor = conn.cursor()

    try:
        categories = []
        for row in cursor.execute(
                '''SELECT categories.id, categories.name FROM map_recipe_category 
                                    JOIN categories on categories.id=map_recipe_category.id_category 
                                    WHERE id_recipe = ?''', (id_recipe, )):
            categories.append(Category(row[0], row[1]))
        return categories
    except sqlite3.Error as error:
        print(error.with_traceback())
 def create_category(self):
     """ Add a new category to the database """
     try:
         category = self.get_argument("category", "")
         if Category.by_category(category) is not None:
             raise ValidationError("Category already exists")
         else:
             new_category = Category()
             new_category.category = category
             self.dbsession.add(new_category)
             self.dbsession.commit()
             self.redirect("/admin/view/categories")
     except ValidationError as error:
         self.render("admin/create/category.html", errors=[str(error)])
def add_category() -> Category:
    category_name = input("The name of the new category: ")
    parent_id = int(input("To which parent category does it belong (parent_id): "))
    new_budgeted_amount = float(input("Write budgeted amount: "))
    category = Category(name=category_name, parent_id=parent_id)
    session.add(category)
    session.commit()
    # TODO: If more than one person creates a new category at the same time we might get incorrect data here
    new_category = session.query(Category).order_by(Category.id.desc()).first()
    category_budget = CategoryBudget(budgeted_amount=new_budgeted_amount, category_id=new_category.id,
                                     datetime=datetime.now())
    session.add(category_budget)
    session.commit()
    return new_category
Example #20
0
def edit_post(id):
    today_date = date.today()
    if request.method == "POST":
        title = request.form['title']
        content = request.form['content']
        category_id = request.form['category']

        add_post = Post().update_post([title, content, category_id],
                                      current_user.id)

        return redirect(url_for('dashboard'))
    post = Post().view_single_post(id)

    category = Category().view_all_category()
    return render_template('edit_post.html', post=post, category=category)
Example #21
0
def getCategoryAndRecordInfo():
    #get data 
    categories = []
    req = Request(url=base_url, headers=headers) 
    res = urlopen(req).read().decode()
    categoryData = json.loads(res)


    #set categoriesInformation
    for x in categoryData["categories"]:
        c = Category(x["displayName"], x["node"], x["recordCount"])
        categories.append(c)
    
    #set node information for future category specific API calls
    if _DEBUG_:
        for c in categories:
            print(c.name + " : " + str(c.node) + " : " + str(c.recordCount) + " : " + str(totalProducts))  
    return categories
Example #22
0
    def post(self):
        json_data = request.get_json(force=True)
        if not json_data:
            return {'message': 'No input data provided'}, 400
        # Validate and deserialize input
        data, errors = category_schema.load(json_data)
        if errors:
            return errors, 422
        category = Category.query.filter_by(name=data['name']).first()
        if category:
            return {'message': 'Category already exists'}, 400
        category = Category(name=json_data['name'])

        db.session.add(category)
        db.session.commit()

        result = category_schema.dump(category).data

        return {"status": 'success', 'data': result}, 201
Example #23
0
def posts():
    today_date = date.today()
    now_time = datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
    if request.method == "POST":
        author = current_user.id
        title = request.form['title']
        content = request.form['content']
        publish_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        permalink = title.replace(' ', '-').lower() + "-" + now_time
        isPublish = 1
        category_id = request.form['category']
        add_post = Post([
            author, title, content, publish_date, permalink, isPublish,
            category_id
        ]).create_post()

        return redirect(url_for('dashboard'))
    category = Category().view_all_category()
    return render_template("new_post.html", category=category)
Example #24
0
def put_new_category():
    session = get_session()
    content = g.data

    locale = get_post_locale(session)

    category = Category()
    name_id = str(uuid4())
    locale_string = LocaleString(id=name_id,
                                 locale=locale,
                                 text=content['name'])
    category.name_id = name_id
    category.name.set(locale_string)
    category.label = content['label']

    session.add(category)

    session.commit()
    session.close()

    return 'ok'
Example #25
0
# 表关联操作

with db_session:
    p = Post.get(post_pk=1)
    Comment(content="你瞅啥", post=p)
    Comment(content="瞅你咋地", post=p)

    # 查看关联的数据
    print(p.comments)

# 之后就可以通过p.comments取到与之关联的评论。
# 那么再来试试多对多关系

with db_session:
    c1 = Category(name="tech")
    c2 = Category(name="blog")

    Post(title="第5篇文章", content="Hello world too", categories=[c1])
    Post(title="第6篇文章", content="Hello world 3", categories=[c1, c2])

    # 查看关联的数据
    print(Category["tech"].posts)  # 这个Category["tech"]等同于Category.get("tech")
    print(Post[6].categories)

# 删除
# 调用Entity实例的.delete()方法可以删掉这条数据。
# 如果需要把相关联的数据一并删掉,需要在定义model字段的时候加上cascade_delete = True的参数。

with db_session:
    Category["tech"].delete()
Example #26
0
                 email='*****@*****.**',
                 password_hash=user_schema.generate_hash('pass'))

    user8 = User(username='******',
                 email='*****@*****.**',
                 password_hash=user_schema.generate_hash('pass'))

    user9 = User(username='******',
                 email='*****@*****.**',
                 password_hash=user_schema.generate_hash('pass'))

    user10 = User(username='******',
                  email='*****@*****.**',
                  password_hash=user_schema.generate_hash('pass'))

    household = Category(name='Household')
    toys = Category(name='Toys')
    garden = Category(name='Garden')
    furniture = Category(name='Furniture')
    clothing = Category(name='Clothing')
    electrical = Category(name='Electrical')
    bags = Category(name='Bags')
    pets = Category(name='Pets')
    books = Category(name='Books')
    bicycles = Category(name='Bicycles')
    kitchen = Category(name='Kitchen')

    flower_vase = Listing(
        title='Flower vase',
        image=
        'https://images.unsplash.com/photo-1490312278390-ab64016e0aa9?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1650&q=80',
Example #27
0
def create(category):
    name = category.get("name", None)
    category = Category(None, name)
    id_cat = CategoryDAOimpl.insert(category)
    json.dumps(id_cat)
    return id_cat
Example #28
0
def update(id_cat, category):
    name = category.get("name", None)
    category = Category(id_cat, name)
    CategoryDAOimpl.update(category)
Example #29
0
category_names = [[
    "Prąd", "Internet", "Telefon", "Telewizja", "Woda", "Czynsz", "Gaz"
], ["Kredyt studencki", "Kredyt w baku", "Kredyt hipoteczny", "Samochód"],
                  ["Artykuły spożywcze", "Artykuły higieniczne"],
                  ["Na remont łazienki", "Na wakacje", "Skarbonka"],
                  ["Restauracja", "Kino"]]

# loop through parent categories
for parent_instance in session.query(ParentCategory).order_by(
        ParentCategory.id):
    # create categories based on list of names
    index = parent_category_names.index(parent_instance.name)
    for c in range(len(category_names[index])):
        category_list.append(
            Category(
                name=category_names[index][c],
                # budgeted_amount=round(uniform(30.0, 2500.0), 2),  # PyCharm complains but it's expected behaviour because of getter-setter setup
                parent_id=parent_instance.id))

session.add_all(category_list)
session.commit()

# ADD TRANSACTIONS
# ------------------------------

transaction_list = []
# loop through categories
for category_instance in session.query(Category).order_by(Category.id):
    for i in range(randint(1, 10)):
        transaction_list.append(
            Transaction(name="Transakcja",
                        payee_name="Nazwa sklepu / płatnika",
Example #30
0
db.drop_all_tables(with_all_data=True)
db.create_tables()

with db_session():
    schema = UserSchema()
    valeriux = User(username='******',
                    email='*****@*****.**',
                    password_hash=schema.generate_hash('pass'))

    schema = UserSchema()
    doris = User(username='******',
                 email='*****@*****.**',
                 password_hash=schema.generate_hash('pass'))

    Body_Care = Category(name='Body Care')
    Bath = Category(name='Bath')
    Hair_Care = Category(name='Hair Care')
    Hand_Feet = Category(name='Hair and Feet')

    Product(
        name='Acai Beautifying Dry Oil',
        images=[
            'https://www.naturabrasil.fr/product/image/large/50172170_1.jpg',
            'https://www.naturabrasil.fr/product/image/medium/50172119-huile-seche-ekos-castanha.jpg',
            'https://res.cloudinary.com/feelunique-com/image/upload/f_auto,t_product_listing/v1/live/product/main-image/79304/fchtpv1deft6vcazrlme.jpg'
        ],
        description=
        'A wonderful and amazingly soft skin, with a delicate and comforting fragrance. The beautifying dry oil Ekos Castanha is enriched with Castanha oil and 100% vegetal oils.Its exclusive formula, with a dry touch, is rapidly absorbed and leaves a protective moisturizing layer on your skin, with delicate sweet and comforting notes.Vegan formula.',
        price='25',
        qty="12",