Beispiel #1
0
def add_category():
    """
	add a category to the
	database
	"""
    check_admin()

    add_category = True

    form = CategoriesForm()

    if form.validate_on_submit():
        filename = request.files['image']
        _, f_ext = os.path.splitext(filename.filename)
        name = form.name.data
        picture_fn = name + f_ext
        photos.save(filename, name=picture_fn)
        url = photos.url(picture_fn)
        category = Categories(category_name=form.name.data, category_image=url)
        try:
            db.session.add(category)
            db.session.commit()
            flash("You have successfully added a new category")
            gc.collect()
        except Exception as e:
            flash('Error: category name already exits. ')

        return redirect(url_for('admin.list_categories'))
    return render_template('admin/categories/category.html',
                           action="Add",
                           form=form,
                           add_category=add_category,
                           title="Add Categories")
def create_categories():
    form = CategoriesForm()
    subform = SubCategoriesForm()
    subform.catid.choices = [(c.id, c.categories)
                             for c in db.session.query(Categories).all()]
    if form.validate_on_submit():
        categories = Categories(categories=form.cat.data)
        db.session.add(categories)
        db.session.commit()
        flash(_('New categories added'))
        return redirect(url_for('product.create_categories'))
    elif subform.validate_on_submit():
        subcategories = SubCategories(subcategories=subform.subcat.data,
                                      categories_id=subform.catid.data)
        db.session.add(subcategories)
        db.session.commit()
        flash(_('New Sub-Categories added'))
        return redirect(url_for('product.create_categories'))
    categoriess = Categories.query.order_by(Categories.id)
    subcategoriess = SubCategories.query.order_by(SubCategories.categories_id)
    return render_template('product/create_categories.html',
                           title=_('Create Categories'),
                           form=form,
                           subcategoriess=subcategoriess,
                           categoriess=categoriess,
                           subform=subform)
def new_book():
    form = BookForm()
    if form.validate_on_submit():

        publisher = db.session.query(Publishers).filter(Publishers.publishes_name==form.publisher.data).first()
        if publisher:#якщо таке видавництво є в базі даних
            publisher_id = publisher.publishers_id
        else:#якщо його немає
            publisher_id = db.session.query(Publishers).order_by(Publishers.publishers_id.desc()).first().publishers_id + 1
            publisher = Publishers(publishers_id=publisher_id, publishes_name=form.publisher.data)
            db.session.add(publisher)
            # db.session.commit()


        category = db.session.query(Categories).filter(Categories.category_name==form.category.data).first()
        if category:
            category_id = category.category_id
        else:
            category_id = db.session.query(Categories).order_by(Categories.category_id.desc()).first().category_id + 1
            category = Categories(category_id=category_id, category_name=form.category.data)
            db.session.add(category)
            # db.session.commit()
        

        author_name = db.session.query(Authors).filter(Authors.first_name==form.name_author.data).all()#отримуємо всіх авторів з таким ім'ям
        author_surname = db.session.query(Authors).filter(Authors.second_name==form.surname_author.data).all()#отримуємо всіх авторів з таким прізвищем
        author = list(set(author_name).intersection(author_surname))#отримуємо автора з таким ім'ям і прізвищем

        if author:
            author_id = author[0].author_id
        else:
            author_id = db.session.query(Authors).order_by(Authors.author_id.desc()).first().author_id + 1
            author = Authors(author_id=author_id, first_name=form.name_author.data, second_name=form.surname_author.data)
            db.session.add(author)
            # db.session.commit()

        # date_add = form.data_added.data.split('.')



        book_id = db.session.query(Books).order_by(Books.book_id.desc()).first().book_id + 1
        book = Books(book_id=book_id, book_name=form.name_book.data, description=form.description.data, page=form.page.data,
         year=form.year.data, publisher_id=publisher_id, categories_id=category_id)





        db.session.add(book)
        # db.session.add(user_book)

        db.session.commit()

        ins = autor_has_books.insert().values(book_id=book_id, author_id=author_id)
        db.engine.execute(ins)
        # flash('Your post has been created!', 'success')
        return redirect(url_for('home'))
    return render_template('new_book.html', title='New Book',
                           form=form, legend='New Book')
def add_category(html, human):
    try:
        new_category = Categories(category_html=html, category_human=human)
        db.session.add(new_category)
        db.session.commit()
        return True
    except:
        db.session.rollback()
        return False
Beispiel #5
0
def admin_categories():
    form = CategoryForm()
    categories = Categories.query.all()
    if request.method == 'POST':
        category = Categories(cat_name=form.cat_name.data)
        db.session.add(category)
        db.session.commit()
        return redirect('/admin/categories')
    return render_template('admin/categories.html',
                           form=form,
                           categories=categories)
Beispiel #6
0
 def make_product(self, data, **kwargs):
     category = db.session.query(Categories).filter_by(
         name=data['category_name']).first()
     if category is not None:
         category_id = category.id
     else:
         new_category = Categories(name=data['category_name'])
         db.session.add(new_category)
         db.session.commit()
         category_id = new_category.id
     del data['category_name']
     return Product(category_id=category_id, **data)
Beispiel #7
0
def create_category():
    data = request.get_json() or {}
    if 'category_name' not in data:
        return bad_request('must include category_name fields')
    if Categories.query.filter_by(category_name=data['category_name']).first():
        return bad_request('please use a different category_name')
    category = Categories()
    category.from_dict(data, new_category=True)
    db.session.add(category)
    db.session.commit()
    response = jsonify(category.to_dict())
    response.status_code = 201
    response.headers['Location'] = url_for(
        'api.get_categories', id=category.category_id)
    return response
    def post(self, user_in_session):
        """
       Create category
       ---
       tags:
         - Categories Endpoints
       parameters:
         - in: body
           name: Category details
           description: Create category by providing category name
           type: string
           required: true
           schema:
             id: create_categories
             properties:
               category_name:
                 default: Lunch
       responses:
         201:
           description: Category created successfully
         409:
           description: Category exists!
         400:
           description: Invalid category name given
         422:
           description: Please fill all the fields
        """
        category_name = str(request.data.get('category_name', '')).strip()
        print(category_name)
        check_category_exist = Categories.query.filter_by(users_id=user_in_session).all()

        if not category_name:
            return make_response(jsonify({'message': 'Please fill all the fields'})), 400

        if not re.search(self.regex_category_name, category_name):
            # This checks whether the category name matches the pattern specified.
            return make_response(jsonify({'message': 'Invalid category name given'})), 400

        for category_in_list in check_category_exist:
            category_name_in_list = category_in_list.category_name
            if category_name.upper() == category_name_in_list.upper():
                return make_response(jsonify({'message': 'Category exists!'})), 409

        categories = Categories(category_name=category_name, users_id=user_in_session)
        categories.save()
        # This saves the new categories after it passes all the conditions.
        return make_response(jsonify({'message': 'Category created successfully'})), 201
Beispiel #9
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RegistrationForm()
    if form.validate_on_submit():
        user = Users(username=form.username.data, email=form.email.data)
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        user = Users.query.filter_by(username=form.username.data).first()
        categories = [
            'Car', 'Shopping', 'Girlfriend', 'Dates', 'School', 'Training',
            'Work', 'Personal data'
        ]
        for c in categories:
            entry = Categories(c, user_id=user.id)
            db.session.add(entry)
        db.session.commit()
        flash('Successful registration!')
        return redirect(url_for('login'))
    return render_template('register.html', title='Registration', form=form)
Beispiel #10
0
    def post(self, current_user):
        """Method to add a new category to the endpoint
        ---
        tags:
            - Categories
        produces:
            - application/json
        security:
          - TokenHeader: []
        parameters:
            - in: body
              name: Category Name
              descrption: Name of the category
              required: true
              type: string
              schema:
                id: categories create
                properties:
                  category_name:
                    type: string
                    default: Breakfast


        responses:
          200:
            schema:
              id: categories
              properties:
                category_name:
                  type: string
                  default: Breakfast
                created_by:
                 type: integer
                 default: 2
                date_created:
                 type: string
                 default: Wed 20 Dec
                date_modified:
                 type: string
                 default: Wed 20 Dec
                id:
                 type: integer
                 default: 1
          400:
            description: category name not valid
          400:
            description: category name not provided
          400:
            description: category name exists
          401:
            description: category not created because user is unauthenticated
          201:
            description: category created
        """

        try:
            category_name = str(request.data.get('category_name', ''))
            category_details = Categories.query.filter_by(
                category_name=category_name,
                created_by=current_user.id).first()
            category_validation(category_name)
            if category_details:
                response = {'message': 'Category name exists'}
                return make_response(jsonify(response)), 400

            category = Categories(category_name=category_name,
                                  created_by=current_user.id)
            category.save()
            response = jsonify({
                'id': category.id,
                'category_name': category.category_name,
                'created_by': category.created_by,
                'date_created': category.date_created,
                'date_modified': category.date_modified
            })
            response.status_code = 201
            return response
        except Exception as e:
            response = {'message': str(e)}
            return make_response(jsonify(response)), 400
Beispiel #11
0
def seed_categories():
    category1 = Categories(categoryName="Girl Dresses", mainCategoryId=1)
    category2 = Categories(categoryName="Girl Pants", mainCategoryId=1)
    category3 = Categories(categoryName="Girl Tops",
                           mainCategoryId=1)
    category4 = Categories(categoryName="Toddler Girl Dresses", mainCategoryId=2)
    category5 = Categories(categoryName="Toddler Girl Pants", mainCategoryId=2)
    category6 = Categories(categoryName="Toddler Girl Tops", mainCategoryId=2)
    category7 = Categories(categoryName="Boy Shirts", mainCategoryId=3)
    category8 = Categories(categoryName="Boy Jackets", mainCategoryId=3)
    category9 = Categories(categoryName="Boy Pants", mainCategoryId=3)
    category10 = Categories(categoryName="Toddler Boy Shirts", mainCategoryId=4)
    category11 = Categories(categoryName="Toddler Boy Jackets", mainCategoryId=4)
    category12 = Categories(categoryName="Toddler Boy Pants", mainCategoryId=4)
    
    db.session.add(category1)
    db.session.add(category2)
    db.session.add(category3)
    db.session.add(category4)
    db.session.add(category5)
    db.session.add(category6)
    db.session.add(category7)
    db.session.add(category8)
    db.session.add(category9)
    db.session.add(category10)
    db.session.add(category11)
    db.session.add(category12)
    db.session.commit()