Пример #1
0
    def put(self, p_id):

        obj = Product.objects(id=p_id).get()

        if not request.json:

            if request.files:
                obj.update(**{'img': request.files['img'].read()})

            data = json.loads(request.form['request'])

            if data.get('category'):
                category = data.pop('category')
                data['category'] = Category.objects(id=(category['id'])).get()

            obj.update(**data)

        else:

            if request.json.get('category'):

                category = request.json.pop('category')
                request.json['category'] = Category.objects(
                    id=(category['id'])).get()

            obj.update(**request.json)

        return ProductScheme().dump(obj.reload())
Пример #2
0
    def post(self, id=None):

        if not id:
            instance = Category(**request.json).save()
            return CategorySchema().dump(instance)

        category = Category.objects(id=id).get()
        return CategorySchema().dump(category)
Пример #3
0
def product_seeder(amount):

    games_names = ['DOOM', 'DIABLO', 'DOTA', 'GTA', 'Rust', 'Grad', 'Need For Speed', 'The legend of Zelda',
                   'Half-Life', 'BioShock', 'The Witcher', 'Portal', 'Tetris', 'Mario', 'Halo']

    movies_names = ['Hunters of the Forest', 'Girl in pink', 'Wolf and Bear forest friends', 'Some movie', 'King'
                    'Queen of the mexico', 'Green Land', 'Rome The Empire', 'Yakudza', 'Ice Cold', 'The Beast']

    music = ['AppleMusic subscribe']

    p_dict = {
        'Action': games_names,
        'MOVIE': movies_names,
        'MUSIC': music
    }

    for _ in range(amount):

        price = randint(0, 100)

        category = choice(list(p_dict.keys()))

        product_dict = {
            'title': choice(p_dict[category]),
            'description': lorem.sentence(),
            'price': price,
            'new_price': price // 2,
            'is_discount': choice([True, False]),
            'category': Category.objects(title=category).get(),

        }

        product = Product(**product_dict)
        product.save()
Пример #4
0
class InlineKB(InlineKeyboardMarkup):

    queries = {
        'root': Category.get_root_categories()
    }

    def __init__(self,  named_arg, iterable=None, lookup_field='id', key=None, title_field='title', row_width=3):
        if all([iterable, key]):
            raise ValueError('Only one of fields: iterable, key can be set')
        super().__init__(row_width=row_width)
        self._iterable = iterable
        self._named_arg = named_arg
        self._lookup_field = lookup_field
        self._title_field = title_field
        self._query = self.queries.get(key)

    def generate_kb(self):
        buttons = []

        if not self._iterable:
            self._iterable = self._query
        for i in self._iterable:
            buttons.append(InlineKeyboardButton(
                text=str(getattr(i, self._title_field)),
                callback_data=f'{self._named_arg}_' + str(getattr(i, self._lookup_field))
            ))

        self.add(*buttons)
        return self
Пример #5
0
def category_seeder():

    categories = ['VIDEO GAMES', 'MOVIE', 'MUSIC']

    for category in categories:

        category_dict = {
            'title': category,
            'description': lorem.sentence()
        }

        Category(**category_dict).save()

    sub_categories = [{'VIDEO GAMES': 'PC'}, {'VIDEO GAMES': 'XBox'}, {'VIDEO GAMES': 'PlayStation'}]

    for i in sub_categories:
        for k, v in i.items():

            subcategory_dict = {
                'title': v,
                'description': lorem.sentence()
            }

            subcategory = Category(**subcategory_dict).save()

            Category.objects(title=k).get().add_subcategory(subcategory)

    sub_category = {
        'title': 'Action',
        'description': lorem.sentence()
    }
    subsub_c = Category(**sub_category).save()
    Category.objects(title='PC').get().add_subcategory(subsub_c)
Пример #6
0
def create_category():
  if request.form["name"] == '' or len(request.form["name"]) > limit.CATEGORY_NAME:
    flash("カテゴリは50文字以内で入力してください")
    return redirect(url_for('index'))
  name = request.form["name"]
  category = Category(name=name)
  dbsession.add(category)
  dbsession.commit()
  return redirect(url_for('index'))
Пример #7
0
    def delete(self, c_id):

        obj = Category.objects(id=c_id).get()

        if obj.parent:
            return {'ERROR': 'First delete child'}

        obj.delete()

        return {c_id: 'DELETED'}
Пример #8
0
def add_record(record):

    time = datetime.now()

    trash_list = [record[GARBAGE_NAME]]
    if record[SIMILAR_WORDS] != "":
        trash_list.extend(record[SIMILAR_WORDS].split(' '))

    if record[OTHER_RULE] != "":
        category_list = [record[RULE], record[OTHER_RULE]]
    else:
        category_list = [record[RULE]]

    for trash_name in trash_list:
        # register trash
        trash = Trash()
        trash.name = trash_name
        trash.detail = record[HOW_TO]
        trash.created_at = time
        trash.updated_at = time
        db_session.add(trash)
        db_session.commit()

        # insert categories and throw_rules
        for category_name in category_list:
            category = db_session.query(Category).filter_by(
                name=category_name).first()
            if (category is None):
                category = Category()
                category.name = category_name
                category.created_at = time
                category.updated_at = time
                db_session.add(category)
                db_session.commit()

            throw_rule = ThrowRule()
            throw_rule.trash_id = trash.trash_id
            throw_rule.category_id = category.category_id
            throw_rule.created_at = time
            throw_rule.updated_at = time
            db_session.add(throw_rule)
            db_session.commit()
Пример #9
0
    def get(self):
        try:
            #jinja = jinja2.get_jinja2(app=self.app)
            #template = jinja.render_template("basic_table.html")
            a = "hello world!!!"
            sav = Category(
                name="politica",
                keyword=[
                    'beatriz argimón', 'rodolfo nin novoa', 'carmen beramendi',
                    'rafael michelini', 'jos\xe9 amor\xedn batlle',
                    'fernando amado', 'jos\xe9 mujica',
                    'eleuterio fern\xe1ndez huidobro', 'luc\xeda topolansky',
                    'ministro', 'nin novoa', 'gobierno', 'uruguay',
                    'frente amplio', 'diputados', 'legislador',
                    'senadora frenteamplista',
                    'frenteamplista carmen beramendi',
                    'frenteamplista rafael michelini',
                    'nacionalista beatriz argimón', 'frenteamplista',
                    'nacionalista', 'ministerio', 'partidos',
                    'partidos pol\xedticos', 'partido colorado', 'colorados',
                    'partido nacional', 'partido independiente',
                    'resultados electorales'
                    'senador', 'campa\xf1a electoral', 'senadora',
                    'elecciones internas', 'elecciones', 'ley',
                    'nivel nacional', 'interior', 'ancap',
                    'colectivo frenteamplista', 'rep\xfablica', 'marenales',
                    'mln', 'mpp', 'vamos uruguay', 'territorio nacional',
                    'actividad pol\xedtic'
                ])
            sav.put()

            template = JINJA_ENVIRONMENT.get_template('basic_table.html')
            self.response.write(template.render(locals()))
            #self.response.out.write(template.render(template_values))
            #template = JINJA_ENVIRONMENT.get_template('/templates/mono2.html')
        except:
            error = traceback.format_exc()
            print error
            return True
Пример #10
0
    def post(self):

        if not request.json:

            data = json.loads(request.form['request'])

            if request.files:
                data['img'] = request.files['img'].read()

            if data.get('category'):
                category = data.pop('category')
                data['category'] = Category.objects(id=(category['id'])).get()

            obj = Product(**data)

        else:

            category = request.json.pop('category')
            request.json['category'] = Category.objects(
                id=(category['id'])).get()
            obj = Product(**request.json)

        obj.save()
        return ProductScheme().dump(obj)
Пример #11
0
def newCategory():
    if 'username' not in login_session:
        return redirect(url_for('showBookshelf'))
    user_id = login_session['user_id']
    creator = getUserInfo(user_id)
    if request.method == 'POST':
        newCategory = Category(name=request.form['name'],
                               user_id=login_session['user_id'])
        # TODO: add user_id=login_session['user_id'] above
        session.add(newCategory)
        flash('New Category %s Successfully Created' % newCategory.name)
        session.commit()
        return redirect(url_for('showBookshelf'))
    else:
        return render_template('newCategory.html', creator=creator)
Пример #12
0
    def post(self, c_id=None):

        if c_id:
            category = Category.objects(id=c_id).get()
            sub_category = Category(**request.json).save()

            category.add_subcategory(sub_category)

            return CategoryScheme().dump(sub_category)

        obj = Category(**request.json)
        obj.save()

        return CategoryScheme().dump(obj)
Пример #13
0
 def delete(self, id):
     CategorySchema().dump(Category.objects(id=id).delete())
     return jsonify(**{id: 'deleted'})
Пример #14
0
from models.models import Category, Item
from random import choice, randint

category = []

for i in range(1, 6):
    category_ex = Category(
        **{
            'title': f'category number {i}',
            'description': f'description by category number {i}',
        }).save()
    category.append(category_ex)

for i in range(1, 11):
    item_ex = {
        'title': f'item number {i}',
        'category': choice(category),
        'is_availability': True,
        'price': randint(100, 1000),
        'count': randint(10, 50)
    }
    Item(**item_ex).save()
Пример #15
0
 def get(self, id=None):
     if not id:
         return CategorySchema().dump(Category.objects, many=True)
     return CategorySchema().dump(Category.objects(id=id).get())
Пример #16
0
def insert_data(key, data_list):
    time = datetime.now()
    if key == 'trashes':
        for data in data_list:
            trash = Trash()
            trash.trash_id = data['trash_id']
            trash.name = data['name']
            trash.reading = data['reading']
            trash.detail = data['detail']
            trash.created_at = time
            trash.updated_at = time
            db_session.add(trash)
            db_session.commit()
    elif key == 'categories':
        for data in data_list:
            category = Category()
            category.category_id = data['category_id']
            category.name = data['name']
            category.created_at = time
            category.updated_at = time
            db_session.add(category)
            db_session.commit()
    elif key == 'towns':
        for data in data_list:
            town = Town()
            town.town_id = data['town_id']
            town.area_id = data['area_id']
            town.name = data['name']
            town.created_at = time
            town.updated_at = time
            db_session.add(town)
            db_session.commit()
    elif key == 'areas':
        for data in data_list:
            area = Area()
            area.area_id = data['area_id']
            area.name = data['name']
            area.created_at = time
            area.updated_at = time
            db_session.add(area)
            db_session.commit()
    elif key == 'collection_rules':
        for data in data_list:
            collection_rule = CollectionRule()
            collection_rule.collection_rule_id = data['collection_rule_id']
            collection_rule.town_id = data['town_id']
            collection_rule.category_id = data['category_id']
            collection_rule.data = data['data']
            collection_rule.created_at = time
            collection_rule.updated_at = time
            db_session.add(collection_rule)
            db_session.commit()
    elif key == 'throw_rules':
        for data in data_list:
            throw_rules = ThrowRule()
            throw_rules.throw_rule_id = data['throw_rule_id']
            throw_rules.trash_id = data['trash_id']
            throw_rules.category_id = data['category_id']
            throw_rules.created_at = time
            throw_rules.updated_at = time
            db_session.add(throw_rules)
            db_session.commit()
Пример #17
0
    Texts,
    Properties,
    Category,
    Product,
)

beginning_kb = {
    'news': 'Последние новости',
    'products': 'Продукты',
    'sales': 'Товар со скидкой',
    'about': 'Информация о магазине',
    'basket': 'Корзина'
}


category = Category.objects()
category_kb = []
for i in category:
    category_kb.append(i.title)


class ReplyKB(ReplyKeyboardMarkup):
    def __init__(self, one_time_keyboard=True, resize_keyboard=True, row_width=3):
        super().__init__(one_time_keyboard=one_time_keyboard,
                         resize_keyboard=resize_keyboard,
                         row_width=row_width)

    def generate_kb(self, *args):
        '''
        :param args: Button names
        :return: New kb
Пример #18
0
    def get(self, c_id=None):

        if c_id:
            return CategoryScheme().dump(Category.objects(id=c_id).get())

        return CategoryScheme().dump(Category.objects, many=True)
Пример #19
0
    def put(self, c_id):

        obj = Category.objects(id=c_id).get()
        obj.update(**request.json)

        return CategoryScheme().dump(obj.reload())