Ejemplo n.º 1
0
    def post(self):
        form = CategoryForm()

        if form.is_submitted():
            try:
                if not form.validate():
                    raise Exception(_('ERROR_INVALID_SUBMISSION'))

                category = Category.create()

                if not form.slug.data:
                    form.slug.data = form.name.data

                form.slug.data = Category.urlify(form.slug.data)

                form.populate_obj(category)
                category.save()

                return render_view(url_for('CategoriesView:put', id=category.id),
                                   message=_('CATEGORY_CREATE_SUCESS'),
                                   redirect=True)
            except Exception as e:
                flash(e.message, 'error')

        return render_view('admin/categories/add.html', form=form)
Ejemplo n.º 2
0
    def transfer_post(self):

        form = TranferForm()

        if form.is_submitted():
            try:
                if not form.validate():
                    raise Exception(_('ERROR_INVALID_SUBMISSION'))

                cat_from = Category.get_by_id(form.from_id.data)
                cat_to = Category.get_by_id(form.to_id.data)

                if not cat_from or not cat_to:
                    raise Exception(_('CATEGORY_TRANSFER_POSTS_CHECK_FAILED'))

                Category.transfer_posts(cat_from, cat_to)

                message = _('CATEGORY_TRANSFER_POSTS_SUCCESS',
                            from_name=cat_from.name,
                            to_name=cat_to.name)

                return render_view(url_for('CategoriesView:index'),
                                   message=message,
                                   redirect=True)
            except Exception as e:
                flash(e.message, 'error')

        return render_view('admin/categories/transfer.html',
                           form=form)
Ejemplo n.º 3
0
def category_add():
    if request.method == 'GET':
        all_categories = Category.select()
        template = env.get_template('post/category_add.html')
        return template.render(categories=all_categories)
    if request.method == 'POST':
        new_category = Category.create(category_name=post_get('category_name'))
        app.flash(u'Нова категорія була успішно додана')
        redirect('/category/add')
Ejemplo n.º 4
0
def addCategory(request):
    if request.method == 'GET':
        category_name = request.GET.get('name')
        user = User.objects.get(pk=request.user.id)
        category = Category(name=category_name, user=user)
        category.save()
        return redirect('home')
    else:
        return Response(status=403)
Ejemplo n.º 5
0
 def create_new(self):
     rv = Form.validate(self)
     if rv:
         category = Category()
         category.init(self.name.data, self.num.data, self.parentid.data, self.visible.data, self.paid.data, self.dcost.data)
         db.session.add(category)
         db.session.commit()
         self.category = category
         return True
     return False
Ejemplo n.º 6
0
def db_init():
    """Initialize the database."""
    from app import db
    db.create_all()
    click.echo('Initialize the database.')

    from app.models import Category
    c1 = Category.create(name=u'Uncategorized', slug=u'uncategorized')
    c1.save()
    c2 = Category.create(name=u'News', slug=u'news')
    c2.save()
Ejemplo n.º 7
0
def deploy():
    """Run deploment tasks."""
    from flask.ext.migrate import upgrade
    from app.models import Role, User, Post, Category

    upgrade()

    Role.insert_roles()
    User.add_self_follows()
    Category.add_categorys()
    Post.add_default_title()
    Post.add_default_category()
Ejemplo n.º 8
0
def add_five_random_categories(request):
	categories = Category.objects.filter(user=request.user)
	for idx in range(5):
		raw_name = list(string.ascii_lowercase)
		random.shuffle(raw_name)
		name = ''.join(raw_name[:6])
		column_number = random.randrange(0, 6)
		row_number = get_max_row_number(categories.filter(column_number=column_number)) + 1
		progress_bar_color = get_random_color()
		category = Category(user=request.user, name=name, column_number=column_number, 
			row_number=row_number, progress_bar_color=progress_bar_color)
		category.save()
	return HttpResponseRedirect('/b/edit')
Ejemplo n.º 9
0
def post_add():
    form = PostForm()
    if request.method == 'GET':
        all_categories = Category.select()
        template = env.get_template('post/add.html')
        return template.render(
            form=form,
            categories=all_categories,
        )
    if request.method == 'POST':
        post = Post.create(
            category=post_get('category-id'),
            post_text=post_get('text'),
            title=post_get('title'),
            slug=post_get('slug'),
            user=app.current_user.user_id,
            date_posted=datetime.now(),
            draft=bool(int(post_get('draft'))),
            show_on_index=bool(post_get('show-on-index')),
            language=post_get('language'),
        )
        post_id = post.post_id
        post.save()
        add_new_tags(post_get('tags'), post_id)
        redirect('/post/' + str(post_id))
Ejemplo n.º 10
0
def adduser(email, username, admin=False):
  """ Register a new user"""
  from getpass import getpass
  password = getpass()
  password2 = getpass(prompt='Confirm: ')

  if password != password2:
    import sys
    sys.exit("Error: Passwords do not match!")

  db.create_all()

  category = Category.get_by_name('Almenn frétt')
  if category is None:
    category = Category(name='Almenn frétt',
                        name_en='General News',
                        active=True)
    db.session.add(category)

  user = User(email=email,
              username=username,
              password=password,
              is_admin=admin)
  db.session.add(user)
  db.session.commit()

  print('User {0} was registered successfully!'.format(username))
Ejemplo n.º 11
0
 def create_new(self):
     rv = Form.validate(self)
     ri = self.img.validate(self)
     if rv and ri:
         category = Category()
         if not check_icon(self.img.data):
             self.img.errors.append(_(u'Image not found'))
             return False
         category.init(self.name.data, self.num.data, self.visible.data, self.img.data)
         i = Upload.query.filter_by(url=self.img.data).first()
         db.session.delete(i)
         db.session.add(category)
         db.session.commit()
         self.category = category
         return True
     return False
Ejemplo n.º 12
0
def post_edit(post_id):
    if request.method == 'GET':
        try:
            post = Post.get(Post.post_id == post_id)  # todo: get not deleted
        except Post.DoesNotExist:
            abort(404)

        form = PostForm(obj=post)
        all_categories = Category.select()
        template = env.get_template('post/edit.html')
        return template.render(
            item=post,
            form=form,
            categories=all_categories,
        )
    elif request.method == 'POST':
        post = Post.get(Post.post_id == post_id)
        post.category = post_get('category-id')
        post.post_text = post_get('text')
        post.slug = post_get('slug')
        post.title = post_get('title')
        post.draft = bool(int(post_get('draft')))  # zero int is False
        post.language = post_get('language')
        post.show_on_index = bool(post_get('show-on-index'))
        post.date_updated = datetime.now()
        new_tags = post_get('tags')
        old_tags = Tag.select().join(Tag_to_Post)\
            .where(Tag_to_Post.post_id == post_id)
        remove_tags(old_tags, new_tags, post_id)
        add_new_tags(new_tags, post_id)
        post.save()
        app.flash('Article updated')
        redirect('/post/' + str(post_id))
Ejemplo n.º 13
0
def add_category(request):
    if request.method == "POST" and request.is_ajax():
        category_name = request.POST.get("name")
        if category_name == "":
            return HttpResponse("分类名称不能为空")
            # print category_name		#打印分类名称
        user = User.objects.get(username=request.user.username)
        # print user.username		#打印当前用户名
        category = Category(name=category_name, user=user)
        category.save()
        return HttpResponse("添加成功")  # ajax post要返回一个值,否则报500错误
    else:
        # print 'get请求, 返回管理界面!'
        category_list = Category.objects.filter(user=request.user)
        # category_list = Category.objects.all()
        content_dict = {"categories": category_list}
        return render(request, "admin/category_manage.htm", content_dict)
Ejemplo n.º 14
0
 def test_is_not_sortable(self):
     """
     A model should only become sortable if it has more than
     record to sort.
     """
     self.create_category()
     self.assertFalse(Category.is_sortable(),
         'Category only has one record. It should not be sortable.')
Ejemplo n.º 15
0
 def handle(self, *args, **options):
     archivo = args[0]
     f = open(archivo, 'r')
     l = f.readlines()
     count = 0
     for c in l:
         c = c[1:]
         c = c[:-2]
         slug = c.replace(' ', '-')
         slug = slug.replace(',', '')
         slug = slug.decode('latin-1')
         slug = unicodedata.normalize('NFKD', slug).encode('ASCII', 'ignore') 
         slug = slug.lower()
         
         category = Category()
         category.name = c
         category.slug = slug
         category.order = 0
         category.active = True
         
         try:
             category.save()
             count += 1
             self.stdout.write('Categoria %s almacenada' %  c)
         except Exception:
             self.stdout.write('Categoria %s NO almacenada' %  c)
         
     self.stdout.write('Se almacenaron %d categorias' % count)
Ejemplo n.º 16
0
    def test_06_rename_category(self):
        """测试分类改名"""
        cate1 = Category(name='cate1')
        db.session.add(cate1)
        db.session.commit()

        cate2 = Category(name='cate2')
        cate2.parent = cate1
        db.session.add(cate2)
        db.session.commit()

        cate3 = Category(name='cate3')
        cate3.parent = cate2
        db.session.add(cate3)
        db.session.commit()

        p = Post()
        Post.publish(post=p,
                     title='post',
                     content='post',
                     category=cate2)

        cate1.name = 'cate11'
        cate2.name = 'cate222'

        self.assertTrue(cate2 in cate1.children.all() and
                        cate2.link == 'cate11/cate222' and
                        cate3 in cate2.children.all() and
                        cate3.link == 'cate11/cate222/cate3' and
                        cate3.level == 2 and
                        cate3.parent == cate2 and
                        cate2.posts_count == 1 and
                        cate1.posts_count == 1 and
                        cate3.posts_count == 0)
Ejemplo n.º 17
0
def category(slug, page=1):
    category = Category.get_by_cat(slug)

    if not category:
        abort(404)

    return render_template('main/stamp/category.html',
                           category=category,
                           page=page)
Ejemplo n.º 18
0
def search_category(page,keyword):
    if not keyword:
        keyword = request.form.get('keyword')

    if keyword == None or keyword == "":
        return redirect(url_for('list_category'))
    else:
        category = Category.search_page(page,keyword)
        return render_template("admin/listcategory.html",category=category,keyword=keyword)
Ejemplo n.º 19
0
def datainit():
    from app.models import Role,User,Post,Category
    print ("Category init")
    Category.insert_categorys()    
    print ("Role init")
    User.add_self_follows()
    Role.insert_roles()    
    print ("User and Post generate")
    User.generate_fake(100)
    Post.generate_fake(100)    
    wen=User.query.filter_by(username='******').first()
    if not wen:
        print ("make wen in admin")
        wen=User(username='******',email='*****@*****.**',password='******',confirmed=True)
        wen.role=Role.query.filter_by(permissions=0xff).first()
        db.session.add(wen)
        db.session.commit()        
    else :
        print ("User(wen) already in data")    
    print ("all_data readly now")
Ejemplo n.º 20
0
 def __init__(self, post=None, *args, **kwargs):
     Form.__init__(self, *args, **kwargs)
     self.category_id.choices = Category.get_list()
     if post:
         self.id = kwargs.get("id") if kwargs.get("id") else 0
         self.title.data = post.title
         self.body.data = post.body
         self.extra_body.data = post.extra_body
         self.anonymous.data = post.anonymous
         self.category_id.data = post.category_id
         self.cover_picture_id.data = post.cover_picture_id
Ejemplo n.º 21
0
def add_starter_bookmarks(request):
	old_categories = Category.objects.filter(user=request.user)
	for category in old_categories:
		category.delete()
	# Delete or not?

	for (name, column_number, row_number, progress_bar_color) in predefined_category_details:
		category = Category(user=request.user, name=name, column_number=column_number, 
			row_number=row_number, progress_bar_color=progress_bar_color)
		category.save()

	categories = Category.objects.filter(user=request.user)

	for category_name in predefined_category_names:
		category = categories.filter(name=category_name)[0]
		for (name, link, row_number, glyphicon) in predefined_bookmarks[category_name]:
			bookmark = Bookmark(category=category, name=name, link=link, row_number=row_number, glyphicon=glyphicon)
			bookmark.save()

	return HttpResponseRedirect('/b/')
Ejemplo n.º 22
0
def category_delete(category_id):
    try:
        category = Category.get(Category.category_id == category_id)
        try:
            category.delete_instance()
        except IntegrityError as e:
            app.flash(u'Категорія містить статті. Неможливо видалити', 'error')

        redirect('/category/add')

    except DoesNotExist:
        abort(404)
Ejemplo n.º 23
0
def deploy():
    """Run deployment tasks."""
    from flask.ext.migrate import upgrade
    
    upgrade()
    
    # create user roles
    Role.insert_roles()
    Category.insert_categories()
    User.generate_fake(6)
    v=User(email='*****@*****.**',username="******",password='******',confirmed=True)
    u=User(email='*****@*****.**',username="******",password='******',confirmed=True,role_id=3)
    v.role_id=2
    db.session.add(v)
    db.session.commit()
    db.session.add(u)  ####插入管理员用户
    db.session.commit()
    
    User.add_self_follows()
    Post.generate_fake(15)
    Comment.generate_fake(15)
Ejemplo n.º 24
0
    def transfer_post(self):
        trans = TranferCatForm()
        if trans.validate_on_submit():
            cat_from = Category.get_by_id(trans.from_id.data)
            cat_to = Category.get_by_id(trans.to_id.data)

            if cat_from and cat_to:
                Category.transfer_posts(cat_from, cat_to)
                flash(
                    gettext(
                        "The posts were transfered from %(from_name)s to %(to_name)s",
                        from_name=cat_from.name,
                        to_name=cat_to.name,
                    )
                )
            else:
                flash(gettext("Either category was not found"), "error")
        else:
            flash(trans.get_errors(), "error")

        return redirect(url_for("CategoriesView:index"))
Ejemplo n.º 25
0
    def test_05_category_family(self):
        """测试分类层级关系"""
        cate1 = Category(name='cate1')
        db.session.add(cate1)
        db.session.commit()

        cate2 = Category(name='cate2')
        cate2.parent = cate1
        db.session.add(cate2)
        db.session.commit()

        cate3 = Category(name='cate3')
        cate3.parent = cate2
        db.session.add(cate3)
        db.session.commit()

        self.assertTrue(cate2 in cate1.children.all() and
                        cate2.link == 'cate1/cate2' and
                        cate3 in cate2.children.all() and
                        cate3.link == 'cate1/cate2/cate3' and
                        cate1.parent is None)
Ejemplo n.º 26
0
    def delete(self, id):
        category = Category.get_by_id(id)

        try:
            if category is None:
                raise Exception(_('CATEGORY_NOT_FOUND'))

            if not category.can_edit():
                abort(401)

            if not Category.transfer_posts(category):
                raise Exception(_('CATEGORY_TRANSFER_POSTS_FAILED'))

            name = category.name
            Category.delete(category.id)

            flash(_('CATEGORY_REMOVE_SUCCESS', name=name))
        except Exception as e:
            flash(e.message, 'error')

        return render_view(url_for('CategoriesView:index'),
                           redirect=True)
Ejemplo n.º 27
0
    def index(self):
        page = request.args.get('page', 1, int)

        limit = 5
        categories, total = Category.pagination(page=page, limit=limit, desc=False)

        categoryForm = CategoryForm()

        return render_view('admin/categories/index.html',
                           page=page,
                           limit=limit,
                           total=total,
                           categories=categories,
                           categoryForm=categoryForm)
Ejemplo n.º 28
0
    def delete(self, id):
        category = Category.get_by_id(id)
        if category is None:
            flash(gettext("The category was not found"), "error")
            return redirect(url_for("CategoriesView:index"))
        if not category.can_edit():
            abort(401)

        try:
            if not Category.transfer_posts(category):
                return util.redirect_json_or_html(
                    url_for("CategoriesView:index"), "category", gettext("Sorry, the last category can not be removed")
                )

            name = category.name
            Category.delete(category.id)
            flash(gettext('The category "%(name)s" was removed', name=name))
        except:
            return util.redirect_json_or_html(
                url_for("CategoriesView:index"), "category", gettext("Error while removing the category")
            )

        return util.redirect_json_or_html(url_for("CategoriesView:index"), "category")
Ejemplo n.º 29
0
    def put(self, id):
        category = Category.get_by_id(id)

        if category is None:
            return render_view(url_for('CategoriesView:index'),
                               status=False,
                               redirect=True,
                               message=_('CATEGORY_NOT_FOUND'))

        if not category.can_edit():
            abort(401)

        form = CategoryForm(category=category)

        if form.is_submitted():
            try:
                if not form.validate():
                    raise Exception(_('ERROR_INVALID_SUBMISSION'))

                if not form.slug.data:
                    form.slug.data = form.name.data

                if category.slug != form.slug.data:
                    form.slug.data = Category.urlify(form.slug.data)

                form.populate_obj(category)
                category.save()

                return render_view(url_for('CategoriesView:put', id=category.id),
                                   message=_('CATEGORY_SAVE_SUCCESS'),
                                   redirect=True)
            except Exception as e:
                flash(e.message, 'error')

        return render_view('admin/categories/edit.html',
                           form=form,
                           category=category)
Ejemplo n.º 30
0
def product_update(pk):
    form = ProductForm()
    form.category_id.choices = Category.get_all_choices()
    form.supplier_id.choices = Supplier.get_all_choices()

    if form.validate_on_submit():
        Product.update_product(pk, form.supplier_id.data,
                               form.category_id.data, form.product_name.data,
                               form.sku.data, form.unit_price.data,
                               form.discount.data, form.units_in_stock.data,
                               form.description.data)
        Product.save_images(request.files.getlist('images'), form.sku.data)
        if form.save.data: return redirect(url_for('admin.panel'))
        else: return redirect(url_for('admin.product_update', pk=pk))

    return render_template('admin/product_update.html', form=form, pk=pk)
Ejemplo n.º 31
0
    def get_categories():
        if request.method == 'GET':  # GET method
            categories = Category.get_all()
            results = []

            for category in categories:
                obj = {
                    'id': category.id,
                    'name': category.name,
                    'url': category.url
                }
                results.append(obj)

            Response = jsonify(results)
            Response.status_code = 200
            return Response
Ejemplo n.º 32
0
def get_attributes(json):
    languages_list = Language.query.all()
    categories_list = Category.query.all()

    language_dict = {l.key(): l for l in languages_list}
    category_dict = {c.key(): c for c in categories_list}

    langs = []
    for lang in json.get('languages') or []:
        language = language_dict.get(lang)
        if not language:
            language = Language(name=lang)
        langs.append(language)
    categ = category_dict.get(json.get('category'),
                              Category(name=json.get('category')))
    return (langs, categ)
Ejemplo n.º 33
0
    def wrapper(*args, **kwargs):
        if 'user' in session:
            # Buscar categoria
            category: Category = Category.by_id(session['user']['category'])

            # Comprobar categoria
            name_category = category.category

            if name_category == 'admin':
                return redirect(url_for('admin.home'))
            elif name_category == 'team_leader':
                return redirect(url_for('team_leader.home'))
            else:
                return function(*args, **kwargs)
        else:
            return function(*args, **kwargs)
Ejemplo n.º 34
0
def add_category():
    if Category.query.filter_by(name=request.form['name']).count():
        flash('Category already exists')
        return redirect(request.form['currentURL'])

    new_category = Category(
        name=request.form['name'],
        header=request.form['header'],
        description=request.form['description'],
        thumbsize_large=True if request.form.get('thumbsize') else False)
    slug = new_category.slug

    db.session.add(new_category)
    db.session.commit()
    flash('success')
    return redirect(url_for('paintings', category_slug=slug))
Ejemplo n.º 35
0
    def test_category(self):
        u = User(email='*****@*****.**')
        c = Category(name='matematyka')
        db.session.add(u)
        db.session.add(c)
        db.session.commit()

        o = Offer(name='Analiza matematycza 1.0',
                  price=24.0,
                  count=20,
                  body='to jest przykladowy opis ksiazki',
                  timestamp=datetime.utcnow(),
                  author=u,
                  category=c)
        db.session.add(o)
        db.session.commit()
Ejemplo n.º 36
0
def productadd(request):
    name = request.POST.get("product-category-name")
    order = request.POST.get("parentid")
    cat = request.POST.get("jibie")
    ztt = request.POST.get("chack")
    photo = request.FILES.get("upload")
    if ztt == "增加":
        path = os.path.join(os.getcwd(), 'static\\upload')
        pathname = os.path.join(path, photo.name)
        path1 = default_storage.save(pathname, ContentFile(photo.read()))
        pathname2 = os.path.join('static/upload', photo.name).replace('\\', '/')
        c = Category(oname=name,cate=cat,path=pathname2,parentid=order)
        c.save()
    if ztt == "禁用":
        c = Category.objects.get(oname=name)
        c.zt = 0
        c.save()
    if ztt == "删除":
        c = Category.objects.get(oname=name)
        c.delete()

    return render(request,'product-category-add.html')
Ejemplo n.º 37
0
def add_user():
    form = AddUser()

    # Obtener datos del formulario
    number_internal = int(form.number_internal.data)
    password = form.password.data
    name = form.name.data
    last_name = form.last_name.data
    category = form.category.data

    # Buscar usuario
    user: Users = Users.by_username(number_internal)

    if user == None:
        # Guardar datos del usuario
        employees: Employees = Employees(name, last_name)
        employees.save()

        # Buscar categoria
        category_db: Category = Category.by_category(category)

        if category_db.category == 'team_leader':
            # Crear Gestion de evaluaciones
            management_evaluation: ManageEvaluations = ManageEvaluations()
            management_evaluation.save()

            # Crear modelo de usuario
            new_user: Users = Users(number_internal, number_internal,
                                    employees.id_employees,
                                    category_db.id_category,
                                    management_evaluation.id_manage_evaluation)
        # Crear modelo de usuario
        new_user: Users = Users(number_internal, number_internal,
                                employees.id_employees,
                                category_db.id_category, None)

        # Encriptar password
        new_user.encrypt_password(password)

        new_user.save()

        flash('Upss! El usuario ya existe!', 'alert-success')
        return redirect(url_for('admin.users'))
    else:
        flash('Upss! El usuario ya existe!', 'alert-danger')
        return redirect(url_for('admin.users'))
Ejemplo n.º 38
0
def delete_recipe(user_id, id, recipe_id, **kwargs):
    """This route handles deleting a recipe by id"""

    identity = Category.find_user_by_id(id, user_id)
    if not identity:
        return jsonify(
            {"message": "You don't have"
             " that recipe in that category"}), 400
    recipe = Recipe.find_recipe_by_id(recipe_id, id)
    if not recipe:
        return jsonify({"message": "No recipes with"
                        " that id to delete "}), 404
    recipe.delete()
    return {
        "message": "recipe {} deleted"
        " successfully".format(recipe.title)
    }, 200
Ejemplo n.º 39
0
def categoryadd():
    title = "添加文章类型"
    categories = Category.query.all()
    if request.method == 'POST':
        newcate = request.form['addText']
        if newcate != "":
            cate = Category(name=newcate, number=0)
            db.session.add(cate)
            db.session.commit()
            flash("添加成功!")
        else:
            flash("不能为空!")
        return redirect(url_for('categoryadd'))
    return render_template('categoryadd.html',
                           title=title,
                           categories=categories,
                           category=category)
Ejemplo n.º 40
0
 def setUp(self):
     super().setUp()
     category = Category(name='test_category')
     item = Item(name='test_item')
     item.category = category
     record_1 = Record(start=datetime(2019, 1, 10, 6, 0, 0),
                       finish=datetime(2019, 1, 10, 7, 0, 0),
                       remark='test_record_1')
     record_2 = Record(start=datetime(2019, 1, 11, 6, 0, 0),
                       finish=datetime(2019, 1, 11, 7, 0, 0),
                       remark='test_record_2')
     tag_1 = Tag(name='test_tag_1')
     tag_2 = Tag(name='test_tag_2')
     record_1.tags = [tag_1, tag_2]
     item.records = [record_1, record_2]
     db.session.add(item)
     db.session.commit()
Ejemplo n.º 41
0
def get_category_by_id(user_id, id, **kwargs):
    """This route handles getting categories by id"""

    category = Category.find_user_by_id(id, user_id)
    if not category:
        return jsonify({"message": "No category found by id"}), 404
    else:
        response3 = category.category_json()
        response = {
            "message":
            "category {} found".format(category.id),
            'category':
            response3,
            'Recipes':
            url_for('recipe.get_recipes', id=category.id, _external=True)
        }
        return make_response(jsonify(response)), 200
Ejemplo n.º 42
0
def addCategory():
    try:
        user_id = get_jwt_identity()
        data = request.json
        user = User.query.filter_by(id=user_id).first()
        if user.role != 'admin':
            return 'Invalid Role for this operation', 401
        newCategory = Category(
            name=data['name'],
            description=data['description'],  # noqa
            picture=data['picture'])
        db.session.add(newCategory)
        db.session.commit()
        category = Category.query.filter_by(name=data['name']).first()
        return jsonify(category=category.serialize), 200
    except:
        return 'Invalid Input for creating category', 401
Ejemplo n.º 43
0
	def query(self):
		id = request.args.get("id") or request.form.get("id")
		# 判断id是否为空
		if not id:
			return error.error_1001()
		# 查询数据库
		row = Category.Query().filter_by(id=id).first()
		category = {}
		if row:
			category = {
				"id": row.id,
				"name": row.name,
				"subject": row.subject,
				"chapter": row.chapter,
				"created_time": datetime.timestamp(row.created_time)
			}
		return error.success(category)
Ejemplo n.º 44
0
def addCategory():
    if current_user.is_authenticated:
        form = CategoryForm()
        hasCategory = Category.query.filter_by(name=form.name.data).first()
        if hasCategory is not None:
            flash('Category is already exists.')
            return render_template('category/addCategory.html', title='Add Category', form=form)

        if form.validate_on_submit():
            category = Category(name=form.name.data, description=form.description.data)
            db.session.add(category)
            db.session.commit()
            flash('Successfully Added the Category!')
            return redirect(url_for('category'))
        elif form.cancel.data == True:
            return redirect(url_for('category'))
    return render_template('category/addCategory.html', title='Add Category', form=form)
Ejemplo n.º 45
0
def category_add():
    form = AddCategoryForm()
    if form.validate_on_submit():
        # 获取用户提交的内容
        content = form.content.data
        old_content = Category.query.filter_by(name=form.content.data).first()
        if old_content is None:
            # 添加到数据库中
            category = Category(name=content, user_id=current_user.id)
            db.session.add(category)
            flash('添加分类成功', category='success')
            return redirect(url_for('todo.category_add'))
        else:
            flash('该分类%s已存在,请重新添加分类' % (form.content.data), category='error')
            return redirect(url_for('todo.category_add'))
    print(Category.query.all())
    return render_template('todo/add_category.html', form=form)
Ejemplo n.º 46
0
def addNewGood(name, parent, intro, icon):
    # 检测不能添加同名商品
    good = Category.query.filter_by(name=name).first()
    if good != None:
        return False

    # 在类别表中新建商品记录
    newCat = Category(name=name, parent=parent, level=4)
    db.session.add(newCat)
    db.session.commit()

    # 在商品表中新建商品记录
    newGood = Good(id=newCat.id, intro=intro, icon=icon)
    db.session.add(newGood)
    db.session.commit()

    return True
Ejemplo n.º 47
0
def add_category():
    form = CategoryForm()
    if current_user.can(Permission.WRITE) and form.validate_on_submit():
        category = Category(name=form.name.data, colour=form.colour.data)
        db.session.add(category)
        db.session.commit()
        flash('Category has been created', 'success')
        return redirect(url_for('categories.add_category'))
    page = request.args.get('page', 1, type=int)
    pagination = Category.query.order_by(Category.name.desc()).paginate(
        page, 5, False)
    categories = pagination.items
    return render_template('settings/add_category.html',
                           title='Add a Category',
                           form=form,
                           categories=categories,
                           pagination=pagination)
 def test_add_a_category(self):
     """ Create a category and add it to the database """
     categories = Category.all()
     self.assertEqual(categories, [])
     category = Category(name="Dog")
     self.assertTrue(category != None)
     self.assertEqual(category.id, None)
     category.save()
     # Asert that it was assigned an id and shows up in the database
     self.assertNotEqual(category.id, None)
     categories = Category.all()
     self.assertEqual(len(categories), 1)
Ejemplo n.º 49
0
    def post(current_user, self):
        """Add Recipe Category"""

        if not current_user:
            return is_unauthorized()

        # get request data
        request_payload = request.get_json()

        # initialize validation schema
        category_schema = CategorySchema()

        request_payload, errors = category_schema.load(request_payload)

        if errors:
            return make_response(jsonify(dict(errors=errors)), 422)

        category_name = _clean_name(request_payload['category_name'])

        # check if category exists
        existing_category = current_user.categories.filter_by(
            name=category_name).first()
        if not existing_category:
            name = category_name
            owner = current_user.id
            description = request_payload['description']

            # Add new category
            try:
                new_category = Category(name, owner, description)
                db.session.add(new_category)
                db.session.commit()
                response_payload = {
                    "categories": [make_payload(category=new_category)]
                }
                response_payload = jsonify(response_payload)
                return make_response(response_payload, 201)
            except:
                response_payload = dict(
                    message="Some error occured. Please try again later.")
                response_payload = jsonify(response_payload)
                return make_response(response_payload, 501)
        response_payload = dict(message="The category already exists!")
        response_payload = jsonify(response_payload)
        return make_response(response_payload, 400)
Ejemplo n.º 50
0
def edit_category(category_id):
    if current_user.UserRole != 0:
        flash("Sorry, you can no permission!", "error")
        return redirect("/index")
    if request.method == "POST":
        name = request.form.get("name")
        description = request.form.get("description")
        father = int(request.form.getlist("father")[0])
        if father == 0:
            father = None
        if category_id == 0:
            category = Category(CategoryName=name,
                                CategoryDescription=description,
                                FatherCategoryID=father)
            db.session.add(category)
        else:
            categories = Category.query.all()
            cids = getChildCategory(categories, category_id)
            if father in cids:
                flash("a category can't be the father of its children")
                return redirect("/category")
            category = Category.query.get(category_id)
            if category.CategoryName != name:
                category.CategoryName = name
            if category.CategoryDescription != description:
                category.CategoryDescription = description
            if category.FatherCategoryID != father:
                category.FatherCategoryID = father
        db.session.commit()
        return redirect("/category")
    categories = Category.query.all()
    filtered_categories = []
    if category_id == 0:
        category = Category(CategoryID=0,
                            CategoryName="",
                            CategoryDescription="",
                            FatherCategoryID=0)
    else:
        category = Category.query.get(category_id)
        cids = getChildCategory(categories, category_id)
        for c in categories:
            if not c.CategoryID in cids:
                filtered_categories.append(c)
    categories = [(c.CategoryID, c.CategoryName) for c in filtered_categories]
    return render_template("category.html",
                           category=category,
                           categories=categories)
def categories():
    """Works with categories"""
    if request.method == 'GET':
        filter_params = {
            key: request.args[key]
            for key in CATEGORY_FILTER_KEYS if request.args.get(key)
        }
        return jsonify([{
            'id': c.id
        } for c in current_app.categories.query(**filter_params)])
    elif request.method == 'POST':
        request_body = request.get_json()
        if isinstance(request_body, list):
            task = category_batch_processing.delay(request_body)
            return jsonify({'process_id': task.id}), 202
        else:
            model = current_app.categories.add(Category(**request_body))
            return jsonify({'id': model.id})
Ejemplo n.º 52
0
def category():
    category_list = Category.query.all()
    form = PostCategoryForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            category = Category(name=form.name.data)
            db.session.add(category)
            flash(u'添加成功')
            return redirect(url_for('admin.category'))
        else:
            flash(u'验证失败')
            return render_template('admin/category.html',
                                   form=form,
                                   clist=category_list)
    else:
        return render_template('admin/category.html',
                               form=form,
                               clist=category_list)
Ejemplo n.º 53
0
class AddCourseForm(Form):
    course_number = TextField(u'course_number',
                              validators=[validators.required()])
    name = TextField(u'name', validators=[validators.required()])
    instructor = TextField(u'instructor', validators=[validators.required()])
    est_num_students = IntegerField(u'est_num_students',
                                    validators=[validators.required()])
    designation_name = SelectField(u'designation_name',
                                   choices=[(d['name'], d['name'])
                                            for d in Designation.get_all()])
    categories = SelectMultipleField(u'categories',
                                     choices=[(c['name'], c['name'])
                                              for c in Category.get_all()])

    def validate(self):
        # if not super(AddCourseForm, self).validate():
        #     return False
        return True
Ejemplo n.º 54
0
def addcategory():
    '''
    添加分类名称
    '''
    if request.method == 'POST':
        category = request.form.get('cat')
        if category == '':
            flash('添加的分类名称不能为空')
            return redirect(url_for('aboutadmin.categorylist'))
        elif Category.query.filter_by(name=category).first():
            flash('分类名称已存在')
            return redirect(url_for('aboutadmin.categorylist'))
        else:
            c = Category(name=category)
            db.session.add(c)
            flash('分类添加成功')
            return redirect(url_for('aboutadmin.categorylist'))
    return redirect(url_for('aboutadmin.categorylist'))
Ejemplo n.º 55
0
def dbinit():
    """数据库初始化信息"""
    db.drop_all()
    db.create_all()
    u = User(username='******', email="*****@*****.**")
    u.password = '******'
    db.session.add(u)
    db.session.commit()
    print("用户%s创建成功......." % (u.username))

    c = Category(name="学习", user_id=1)
    db.session.add(c)
    print("分类%s创建成功...." % (c.name))

    t = Todo(content="学习Flask", category_id=1, user_id=1)
    db.session.add(t)
    print("任务%s添加成功....." % (t.content))
    db.session.commit()
Ejemplo n.º 56
0
def copost():
    if request.method == "POST":
        target = request.json['post_id']
        text_cn = request.json['text_cn']
        text_en = request.json['text_en']
        if target:
            post = Post.query.get_or_404(target)
            checklist = post.authors.split("*")
            if str(current_user.id) not in checklist:
                checklist.append(str(current_user.id))
                post.authors = "*".join(checklist)
            post.text_cn = text_cn
            post.text_en = text_en
            post.title_cn = grab_markdown(text_cn)[0]
            post.title_en = grab_markdown(text_en)[0]
            tag_cn = grab_markdown(text_cn)[3]
            tag_en = grab_markdown(text_en)[3]

            if tag_cn:
            	tag = tag_cn
            else:
            	if tag_en:
            		tag = tag_en
            	else:
            		tag = 'Inbox'

            if Category.query.filter_by(name=tag).first() == None:
                category = Category(name=tag)
                db.session.add(category)
                db.session.flush()
                post.category_id = category.id
                db.session.commit()
            else:
            	post.category_id = Category.query.filter_by(name=tag).first().id

            f = open(os.path.join(app.config['POST_IMG_PATH'], sourcemd), 'w+', encoding = 'utf-8')
            f.write(text_cn)
            f.write('\n-------------------------------------------------------\n')
            f.write(text_en)
            f.close()

            db.session.commit()
        flash('Thanks for your participation!', 'success')
    return redirect(url_for('.show_post', post_id=target))
Ejemplo n.º 57
0
    def metric_data(user):
        results = []
        gender = request.values.get('gender', user.gender)
        categories = Category.get_all()
        for category in categories:
            obj_category = {'name': category.name, 'details': []}
            for metric in category.metrics:
                if metric.gender == gender:
                    obj = {
                        'name': metric.name,
                        'weight': metric.weight,
                        'unit_label': metric.unit_label,
                        'features': {
                            'totalrange':
                            [metric.total_range_min, metric.total_range_max],
                            'healthyrange': [
                                metric.healthy_range_min,
                                metric.healthy_range_max
                            ]
                        }
                    }
                    obj_category['details'].append(obj)
            if obj_category['details']:
                results.append(obj_category)

        metrics = Metric.query.filter_by(gender=gender, category=None)

        for metric in metrics:
            obj = {
                'name': metric.name,
                'weight': metric.weight,
                'unit_label': metric.unit_label,
                'features': {
                    'totalrange':
                    [metric.total_range_min, metric.total_range_max],
                    'healthyrange':
                    [metric.healthy_range_min, metric.healthy_range_max]
                }
            }
            results.append(obj)

        response = jsonify(results)
        response.status_code = 200
        return response
Ejemplo n.º 58
0
    def test_07_order_cate(self):
        """测试分类顺序"""
        cate1 = Category(name='cate1')
        db.session.add(cate1)
        db.session.commit()

        cate2 = Category(name='cate2',
                         order=1)
        cate3 = Category(name='cate3',
                         order=2)
        cate3.parent = cate1
        cate2.parent = cate1
        db.session.add(cate2)
        db.session.add(cate3)
        db.session.commit()

        self.assertTrue(cate2.order < cate3.order)
Ejemplo n.º 59
0
def create_sensor():
    data = request.get_json() or {}
    if "name" not in data:
        return bad_request("must include name field")
    if "categories" not in data:
        return bad_request("must include categories field")
    if not Category.are_valid_categories(data["categories"]):
        return bad_request("invalid categor(y)/(ies) in included categories")
    if Sensor.query.filter_by(name=data["name"]).first():
        return bad_request("please use a different name")
    sensor = Sensor()
    sensor.from_dict(data)
    db.session.add(sensor)
    db.session.commit()
    response = jsonify(sensor.to_dict())
    response.status_code = 201
    response.headers["Location"] = url_for("api.get_sensor",
                                           sensor_id=sensor.id)
    return response