Пример #1
0
 def category_seeder(self):
     fake = Faker()
     return [
         Category(name=fake.name(), description=fake.sentence()),
         Category(name=fake.name(), description=fake.sentence()),
         Category(name=fake.name(), description=fake.sentence()),
         Category(name=fake.name(), description=fake.sentence()),
         Category(name=fake.name(), description=fake.sentence()),
     ]
Пример #2
0
    def post(self, request, *args, **kwargs):
        category = Category.objects.filter(
            title__icontains=request.data["category"])
        name = request.data['name']
        country = request.data['country']
        street = request.data['street']
        city = request.data['city']
        zip = request.data['zip']
        website = request.data['website']
        phone = request.data['phone']
        email = request.data['email']
        opening_hours = request.data['opening_hours']
        price_level = request.data['price_level']
        image = request.data['image']

        if category:
            restaurant = Restaurant(category=category[0],
                                    name=name,
                                    country=country,
                                    street=street,
                                    city=city,
                                    zip=zip,
                                    website=website,
                                    phone=phone,
                                    email=email,
                                    opening_hours=opening_hours,
                                    price_level=price_level,
                                    image=image,
                                    author=self.request.user)
            restaurant.save()
        else:
            category = Category(title=request.data["category"])
            category.save()
            restaurant = Restaurant(category=category,
                                    name=name,
                                    country=country,
                                    street=street,
                                    city=city,
                                    zip=zip,
                                    website=website,
                                    phone=phone,
                                    email=email,
                                    opening_hours=opening_hours,
                                    price_level=price_level,
                                    image=image,
                                    author=self.request.user)
            restaurant.save()

        return Response(self.get_serializer(restaurant).data)
Пример #3
0
def read_emojis():
    """
    find list of emojis for the agent
    :return:
    """
    emojis = Emoji.objects()
    if request.args.get('name'):
        emojis = emojis.filter(name__iexact=request.args.get('name'))

    if request.args.get('category'):
        category = Category.objects(
            name__iexact=request.args.get('category')).get()
        emojis = emojis.filter(category=category)

    if request.args.get('q'):
        emojis = emojis.filter(tags__icontains=request.args.get('q'))

    if request.args.get('isPaid'):
        emojis = emojis.filter(isPaid=True) if request.args.get(
            'isPaid').lower() == 'true' else emojis.filter(isPaid=False)

    if not emojis:
        return build_response.build_json([])

    response_emojis = []

    for emoji in emojis:
        obj_emoji = transpose_emoji(emoji)
        response_emojis.append(obj_emoji)

    return build_response.build_json(response_emojis)
Пример #4
0
 def init_categories(cls):
     print "*******************************************"
     category = Category.create()
     category.name = u'Uncategorized'
     category.slug = u'uncategorized'
     category.description = u'Fallback category or standard category'
     category.save()
Пример #5
0
def get_categories():
    '''
    For inserting the categories
    '''
    '''categories = ['Bollywood', 'Hollywood', 'Modern']
    for cat in categories:
        category = Category()
        category.name = cat
        category.save()

    return build_response.sent_ok()'''

    categories = Category.objects().order_by('name')
    if not categories:
        return build_response.build_json([])
    #return build_response.sent_json(emojis.to_json())

    response_categories = []

    for category in categories:
        obj_category = {
            'id': str(category.id),
            'name': category.name,
            'date_created': category.date_created.isoformat(),
            'date_modified': category.date_modified.isoformat()
        }
        response_categories.append(obj_category)

    return build_response.build_json(response_categories)
Пример #6
0
 def __init__(self, post, *args, **kwargs):
     Form.__init__(self, *args, **kwargs)
     self.title.data = post.title
     self.body.data = post.body
     self.image_url.data = post.image_url
     self.slug.data = post.slug
     self.category_id.data = post.category_id
     self.category_id.choices = Category.get_list()
Пример #7
0
def seed_categories():
    cat1 = Category(name='freins',
                    slug=fake.slug(value='cat-01-freins'),
                    description=fake.text(max_nb_chars=200),
                    created_at=random_date)
    cat2 = Category(name='carosserie',
                    slug=fake.slug(value='cat-02-freins'),
                    description=fake.text(max_nb_chars=200),
                    created_at=random_date)
    cat3 = Category(name='transmission',
                    slug=fake.slug(value='cat-03-freins'),
                    description=fake.text(max_nb_chars=200),
                    created_at=random_date)
    cat4 = Category(name='moteur',
                    slug=fake.slug(value='cat-04-freins'),
                    description=fake.text(max_nb_chars=200),
                    created_at=random_date)
    cat5 = Category(name='accessoires et equipements',
                    slug=fake.slug(value='cat-05-freins'),
                    description=fake.text(max_nb_chars=200),
                    created_at=random_date)
    cat6 = Category(name='eclairage',
                    slug=fake.slug(value='cat-06-freins'),
                    description=fake.text(max_nb_chars=200),
                    created_at=random_date)
    cat7 = Category(name='equipement interieur',
                    slug=fake.slug(value='cat-07-freins'),
                    description=fake.text(max_nb_chars=200),
                    created_at=random_date)
    db.session.add_all([cat1, cat2, cat3, cat4, cat5, cat6, cat7])
    db.session.commit()
Пример #8
0
def create_category(data, current_user):
    title = data.get('title')
    description = data.get('description')
    parent_id = data.get('parent_id')

    new_cat = Category(title=title,
                       description=description,
                       user_id=current_user.id,
                       parent_id=parent_id)

    try:
        db.session.add(new_cat)
        db.session.commit()
    except SQLAlchemyError:
        db.session.rollback()
        return 'Internal Server Error.', 500

    return new_cat.as_dict(), 201, {'key': 'category'}
Пример #9
0
 def _insert_test_category(self, session, category: dict = {}):
     data = {
         "name": "Test category",
     }
     data.update(category)
     db_category = Category(**data)
     session.add(db_category)
     session.commit()
     return db_category
Пример #10
0
def category(request, session):
    c = Category(name='test category')
    session.add(c)
    session.commit()

    def teardown():
        session.delete(c)
        session.commit()

    request.addfinalizer(teardown)
    return c
Пример #11
0
def get_stat(value):
    if value == 4:
        last_post, count = Post.pagination()
        return last_post
    elif value == 5:
        last_comments, count = Comment.pagination()
        return last_comments
    elif value == 6:
        last_categories, count = Category.pagination()
        return last_categories        
    else:
        return 0
Пример #12
0
def create_new_category():
    if 'username' not in login_session:
        return redirect('/login')
    if request.method == 'POST':
        name = name = request.form['name']
        description = request.form['description']
        new_category = Category(name=name, description=description)
        db.session.add(new_category)
        db.session.flush()
        db.session.commit()
        flash('New category #' + name + ' was created')
        return redirect(url_for('categories.view_all'))
    return render_template('new-category.html')
Пример #13
0
def show_category(cat, page=1):
    limit = 5
    posts, category = Category.get_posts_by_cat(cat, limit=limit, page=page)

    pagination = Pagination(page=page,
        per_page=limit,
        total=category.posts.count(),
        record_name=gettext('posts'),
        alignment='right',
        bs_version=3)
    return render_template("blog/index.html",
        title=category.name,
        posts=posts,
        pagination=pagination,
        category=category)
Пример #14
0
def find_categories():
    """
    find list of categories for the agent
    :return:
    """
    categories = Category.objects(status=1).order_by('name')
    if not categories:
        return build_response.build_json([])

    response_categories = []

    for category in categories:
        obj_category = transpose_category(category)
        response_categories.append(obj_category)
    return build_response.build_json(response_categories)
Пример #15
0
def create_category():
    """
    Create a story from the provided json
    :param json:
    :return:
    """
    category = Category()
    try:
        save_response = save_category(category)
        if 'error' in save_response:
            raise Exception(save_response['error'])
        else:
            return build_response.build_json(
                {"_id": str(save_response['category_id'])})
    except Exception as e:
        return build_response.build_json({"error": str(e)})
Пример #16
0
    def product_data(self):
        fake = Faker()
        with self.app.app_context():
            self.db.session.add(Category(name=fake.name()))
            self.db.session.commit()

        return {
            "name": fake.name(),
            "description": fake.text(),
            "availability": fake.pybool(),
            "quality": fake.word(),
            "price": fake.pyfloat(min_value=20.00, max_value=10000.00),
            "stock": fake.pyint(),
            "manufacturer": fake.name(),
            "categories": [1]
        }
Пример #17
0
def show_article(cat, post):
    try:
        post = Category.get_by_cat_slug(cat, post)
    except:
        post = None

    if post is None:
        abort(404)

    if not current_user.is_authenticated() or post.comments.count() > 50:
        form = None
    else:
        form = CommentForm()

    return render_template("blog/post-detail.html",
        title=gettext('Post | %(title)s', title=post.title),
        post=post,
        form=form)
Пример #18
0
def save_emoji(emoji):

    # check if the post request has the file part
    if 'Image' in request.files:
        imageDirectory = os.path.join(app.config.get('APP_ROOT'), 'static',
                                      'uploads', 'emojis')
        # remove image file if it is update
        if emoji.imagefile is not None:
            try:
                os.remove(os.path.join(imageDirectory, emoji.imagefile))
            except OSError:
                pass

        file = request.files['Image']

        filename = secure_filename(file.filename)
        file.save(os.path.join(imageDirectory, filename))
        emoji.imagefile = filename

    if request.form.get("category"):
        category = Category.objects(name=request.form.get("category")).get()
        if category:
            emoji.category = category

    if request.form.get("tags"):
        tags_string = request.form.get("tags")
        tags = [x.strip() for x in tags_string.split(',')]
        emoji.tags = tags

    if request.form['isPaid'] == 'Paid':
        emoji.isPaid = True
    else:
        emoji.isPaid = False

    emoji.name = request.form['name']

    if request.form.get("description"):
        emoji.description = request.form['description']

    try:
        emoji_id = emoji.save()
        return {'emoji_id': str(emoji_id.id)}
    except Exception as e:
        return {'error': str(e)}
Пример #19
0
def find_emojis():
    """
    find list of emojis for the agent
    :return:
    """
    page_nb = int(request.args.get('pageNumber'))

    items_per_page = int(request.args.get('pageSize'))

    offset = (page_nb - 1) * items_per_page if page_nb > 0 else 0

    emojis = Emoji.objects()
    if request.args.get('name'):
        emojis = emojis.filter(name__iexact=request.args.get('name'))

    if request.args.get('category'):
        category = Category.objects(
            name__iexact=request.args.get('category')).get()
        emojis = emojis.filter(category=category)

    if request.args.get('q'):
        emojis = emojis.filter(tags__icontains=request.args.get('q'))

    if request.args.get('isPaid'):
        emojis = emojis.filter(isPaid=True) if request.args.get(
            'isPaid').lower() == 'true' else emojis.filter(isPaid=False)

    if not emojis:
        return build_response.build_json([])

    emojis = emojis.order_by('-date_modified')
    #emojis = skip( offset ).limit( items_per_page )

    response_emojis = []

    for emoji in emojis:
        obj_emoji = transpose_emoji(emoji)
        response_emojis.append(obj_emoji)

    return build_response.build_json({"payload": response_emojis})
Пример #20
0
def stickers():
    """
    return list  of stikers grouped by category
    :return:
    """
    strikers = []
    categories = Category.objects(status=1).order_by('displayOrder')

    for category in categories:
        emojis = Emoji.objects()
        emojis = emojis.filter(category=category)

        if request.args.get('q'):
            emojis = emojis.filter(tags__icontains=request.args.get('q'))

        emojis_list = []
        for emoji in emojis:
            obj_emoji = transpose_emoji(emoji)
            emojis_list.append(obj_emoji)

        categoryD = {
            'name':
            category.name,
            'icon':
            url_for('categories_file', path=category.imagefile,
                    _external=True),
            'stickers':
            emojis_list
        }

        strikers.append({"category": categoryD})

    isNewUser = True if (datetime.datetime.now() -
                         g.user.date_created).days <= 7 else False
    return build_response.build_json({
        'status': True,
        'isNewUser': isNewUser,
        'result': strikers
    })
Пример #21
0
 def save(self, category):
     category_to_add = Category(name=category.name,
                                description=category.description)
     db.session.add(category_to_add)
     db.session.commit()
     return Category.query.filter_by(name=category_to_add.name).first()
Пример #22
0
def currentCategory(category_id):
    return Category.getCurrentCategory(category_id)
Пример #23
0
 def __init__(self, *args, **kwargs):
     Form.__init__(self, *args, **kwargs)
     self.category_id.data = 1
     self.category_id.choices = Category.get_list()
Пример #24
0
def test_category_creation(session):
    assert(not Category.query.all())
    c = Category(name='test name')
    session.add(c)
    session.commit()
    assert(c in session)