Ejemplo n.º 1
0
def edit_category(id: int) -> wrappers.Response:
    Categories.query.get_or_404(id)
    try:
        Categories.edit(request.form['data'], id)
        return jsonify({"200 OK": "HTTP/1.1"})
    except:
        return jsonify({"403 Forbidden": "HTTP/1.1"})
Ejemplo n.º 2
0
def add_category() -> wrappers.Response:
    category = request.form['data']
    try:
        Categories.add(category)
        return jsonify({"201 Created": "HTTP/1.1"})
    except:
        return jsonify({"403 Forbidden": "HTTP/1.1"})
Ejemplo n.º 3
0
def add_category() -> wrappers.Response:
    category = request.get_json()
    print(category)
    try:
        Categories.add(category)
        return jsonify({"201 Created": "HTTP/1.1"})
    except:
        return jsonify({"403 Forbidden": "HTTP/1.1"})
Ejemplo n.º 4
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
Ejemplo n.º 5
0
def productView(request):
    product = None
    categories = Categories.get_all_categories()
    categoryId = request.GET.get("category")
    if categoryId:
        categoryId = int(categoryId)
        product = Products.get_all_products_by_id(categoryId)
    else:
        categoryId = int(categories[0].id)
        product = Products.get_all_products_by_id(categoryId)

    dataJSON = serializers.serialize('json', product)

    specialItems = SpecialItems.get_all_items()
    cardJSONData = serializers.serialize('json', specialItems)

    return render(
        request,
        "products.html",
        {
            "products": product,
            "jsonProducts": dataJSON,
            "categories": categories,
            "selectedCategoryId": categoryId,
            "specialCardItems": cardJSONData,
        },
    )
Ejemplo n.º 6
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")
Ejemplo n.º 7
0
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)
Ejemplo n.º 8
0
    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
Ejemplo n.º 9
0
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')
Ejemplo n.º 10
0
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
Ejemplo n.º 11
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)
Ejemplo n.º 12
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)
Ejemplo n.º 13
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)
Ejemplo n.º 14
0
def get_categories():
    page = request.args.get('page', 1, type=int)
    per_page = min(request.args.get('per_page', 10, type=int), 100)
    data = Categories.to_collection_dict(
        Categories.query, page, per_page, 'api.get_categories')
    return jsonify(data)
def categories() -> Dict[str, List[Dict[str, str]]]:
    return jsonify(Categories.get_categories())
Ejemplo n.º 16
0
def delete_category(id: int) -> wrappers.Response:
    Categories.query.get_or_404(id)
    Categories.delete_note(id)
    return jsonify({"200 OK": "HTTP/1.1"})
Ejemplo n.º 17
0
def categories() -> wrappers.Response:
    return jsonify(dict(Categories.get_categories()))
Ejemplo n.º 18
0

class CategorySchema(Schema):
    @validates('name')
    def validate_name(self, name):
        category = Categories.query.filter(func.lower(Categories.name) == func.lower(name)).first()
        if category:
            raise ValidationError({'detail': 'Category "%s" already exists.' % name, 'status': 409})

    class Meta:
        fields = Categories.all_columns


create_category_serializer = resource_schema_factory(
    'categories', CategorySchema,
    attributes={'only': Categories.get_columns(Method.CREATE, Role.ADMIN)}
)

read_category_serializer = resource_schema_factory(
    'categories', CategorySchema,
    attributes={'only': Categories.get_columns(Method.READ, Role.GUEST)}
)

update_category_serializer = resource_schema_factory(
    'categories', CategorySchema,
    id={'required': True},
    attributes={'only': Categories.get_columns(Method.UPDATE, Role.ADMIN)}
)

delete_category_serializer = resource_schema_factory(
    'categories', CategorySchema,
Ejemplo n.º 19
0
    def get(self, user_in_session):
        """
           Retrieve categories
           ---
           tags:
             - Categories Endpoints
           parameters:
             - in: query
               name: q
               description: Search parameter
               type: string

             - in: query
               name: page
               description: page number
               type: integer
               default: 1

             - in: query
               name: limit
               description: Limit
               type: integer
               default: 10

           responses:
             201:
               description: Category created successfully
             409:
               description: Category exists!
             400:
               description: Invalid category name given
             422:
               description: Please fill all the fields
        """
        page_number = int(request.args.get("page", default=1, type=int))
        no_items_per_page = int(request.args.get("limit", default=8, type=int))

        all_categories = Categories.get_all(user_in_session).paginate(
            page_number, no_items_per_page, error_out=False)
        # The all_categories variables stores all the categories
        #   belonging to the current user in session.

        search = request.args.get('q')
        category_list = []

        if search:
            # This filters the categories when user provides a search parameter q.
            searched_categories = Categories.query.filter(Categories.users_id == user_in_session,
                                                          Categories.category_name.ilike('%' + search + '%')).\
                paginate(page_number, no_items_per_page, error_out=False)
            # The searched_categories stores the result of search.
            if searched_categories:
                for categories in searched_categories.items:
                    # This loops all the categories matching the search parameter.
                    obj = {
                            'id': categories.id,
                            'category_name': categories.category_name,
                            'user_id': categories.users_id,
                            'date_created': categories.created_at,
                            'date_updated': categories.updated_at
                            }
                    category_list.append(obj)
                if len(category_list) <= 0:
                    # This checks whether the list contains data.
                    return make_response(jsonify({'message': "no_category_on_search"})), 401
                list_of_categories = {'categories': category_list, "total_items": searched_categories.total,
                                      "total_pages": searched_categories.pages, "current_page": all_categories.page}
                return make_response(jsonify(list_of_categories)), 200

        for categories in all_categories.items:
            # This loops all the categories of the user in session when the search
            #   parameter has not been provided.
            obj = {
                'id': categories.id,
                'category_name': categories.category_name,
                'user_id': categories.users_id,
                'date_created': categories.created_at,
                'date_updated': categories.updated_at
            }
            category_list.append(obj)
        if len(category_list) <= 0:
            # This checks whether the user has categories created.
            return make_response(jsonify({'message': "no_categories"})), 401
        list_of_categories = {'categories': category_list, "total_items": all_categories.total,
                              "total_pages": all_categories.pages, "current_page": all_categories.page}
        return make_response(jsonify(list_of_categories)), 200
Ejemplo n.º 20
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()
Ejemplo n.º 21
0
def categories() -> Dict[str, List[Dict[str, str]]]:
    return Categories.to_json(dict(Categories.get_categories()))
Ejemplo n.º 22
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
Ejemplo n.º 23
0
def get_category(id: int) -> Dict[str, List[Dict[str, str]]]:
    category = Categories.query.get_or_404(id)
    return Categories.to_json(
        dict([[category.category_id, category.category_name]]))
Ejemplo n.º 24
0
    def get(self, current_user):
        """Method to get all categories of a user in a paginated way
        ---
        tags:
            - Categories
        produces:
            - application/json
        security:
          - TokenHeader: []
        parameter:
          - in: path
        responses:
          200:
            schema:
              id: Categories
              properties:
                    category_name:
                     type: json
                     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: Limit number not valid
          400:
            description: Limit number not valid
          400:
            description: Page number not valid
          404:
            description: No category found
        """

        page = request.args.get('page', default=1, type=int)

        limit = request.args.get('limit', default=10, type=int)

        categories = Categories.get_all_user_categories(
            current_user.id).paginate(page, limit, error_out=False)
        results = []
        for category in categories.items:

            category_object = {
                'id': category.id,
                'category_name': category.category_name,
                'date_created': category.date_created,
                'date_modified': category.date_modified,
                'previous_page': categories.prev_num,
                'next_Page': categories.next_num
            }

            results.append(category_object)
        if len(results) <= 0:
            response = {'message': 'No  category found '}
            response = make_response(jsonify(response)), 404
            return response
        response = jsonify(results)
        response.status_code = 200

        return response