Ejemplo n.º 1
0
def create_order():
    user = current_user
    # You can not check is user is not None because user is LocalProxy even when no authenticated
    # to check if the user is authenticated we may do hasattr
    user_id = user.id if hasattr(user, 'id') else None

    address_id = request.json.get('address_id', None)

    if address_id is not None:
        # reusing address, the user has to be authenticated and owning that address
        address = Address.query.filter_by(id=address_id, user_id=user_id).first()
        if address is None:
            return get_error_response('Permission Denied, you can not use this address', 401)
    else:
        first_name = request.json.get('first_name', None)
        last_name = request.json.get('last_name', None)
        zip_code = request.json.get('zip_code', None)
        street_address = request.json.get('address', None)
        country = request.json.get('address', None)
        city = request.json.get('address', None)

        if user_id is not None:
            if first_name is None:
                first_name = user.first_name

            if last_name is None:
                last_name = user.last_name

        address = Address(first_name=first_name, last_name=last_name, city=city, country=country,
                          street_address=street_address, zip_code=zip_code, )
        if hasattr(user, 'id'):
            address.user_id = user.id

        db.session.add(address)
        db.session.flush()  # we would need the address.id so let's save the address to the db to have the id

    import faker
    fake = faker.Faker()
    order = Order(order_status=0, tracking_number=fake.uuid4(), address_id=address.id)

    cart_items = request.json.get('cart_items')
    product_ids = [ci['id'] for ci in cart_items]
    products = db.session.query(Product).filter(Product.id.in_(product_ids)).all()
    if len(products) != len(cart_items):
        return get_error_response('Error, make sure all products you want to order are still available')

    for index, product in enumerate(products):
        order.order_items.append(OrderItem(price=product.price,
                                           quantity=cart_items[index]['quantity'], product=product,
                                           name=product.name,
                                           slug=product.slug,
                                           user_id=user_id))

    db.session.add(order)
    db.session.commit()
    return get_success_response('Order created successfully', data=order.get_summary(include_order_items=True),
                                status_code=200)
Ejemplo n.º 2
0
def destroy_comment(comment_id):
    comment = Comment.query.get(comment_id)
    if comment is None:
        return get_error_response('Comment not found', status_code=404)

    if current_user.is_admin() or comment.user_id == current_user.id:
        db.session.delete(comment)
        db.session.commit()
        return get_success_response('Comment deleted successfully')
    else:
        return get_error_response(
            'Permission denied, you can not delete this comment',
            status_code=401)
Ejemplo n.º 3
0
def unfollow_user(username):
    user = current_identity
    following = User.query.filter_by(username=username).options(load_only('id')).first()
    if not hasattr(following, 'id'):
        return get_error_response('Permission denied, This user does not exist')

    user_subscription = UserSubscription.query.filter_by(following_id=following.id, follower_id=user.id).first()

    if user_subscription is not None:
        db.session.delete(user_subscription)
        db.session.commit()
        return get_success_response('You are now not following %s' % username)
    else:
        return get_error_response('Permission denied, You are not following this user')
Ejemplo n.º 4
0
def destroy_comment(id):
    todo = Todo.query.get(id)
    if todo is None:
        return get_error_response(messages='not found', status_code=404)
    db.session.delete(todo)
    db.session.commit()
    return '', 204
Ejemplo n.º 5
0
def order_details(order_id):
    order = Order.query.get(order_id)
    user = current_user
    if order.user_id is user.id or user.is_admin():
        return jsonify(order.get_summary(include_order_items=True)), 200
    else:
        return get_error_response('Access denied, this does not belong to you', status_code=401)
Ejemplo n.º 6
0
def update(product_slug):
    name = request.json.get('name')
    description = request.json.get('description')
    stock = request.json.get('stock')
    price = request.json.get('price')

    if not (name and description and price and stock and price):
        return jsonify(
            get_error_response(
                'You must provide a name, description, stock and price'))

    product = Product.query.filter_by(slug=product_slug).first()
    if product is None:
        return get_error_response(messages='not found', status_code=404)

    product.name = name
    product.description = description
    product.price = price
    product.body = stock

    tags_input = request.json.get('tags')
    categories_input = request.json.get('categories')
    tags = []
    categories = []
    if categories_input:
        for category in categories_input:
            categories.append(
                get_or_create(
                    db.session,
                    Category,
                    {'description': category.get('description', None)},
                    name=category['name'])[0])

    if tags_input:
        for tag in tags_input:
            tags.append(
                get_or_create(db.session,
                              Tag, {'description': tag.get('description')},
                              name=tag['name'])[0])

    product.tags = tags
    product.categories = categories
    db.session.commit()
    response = {'full_messages': ['Product updated successfully']}
    response.update(ProductDetailsSerializer(product).data)
    return jsonify(response)
Ejemplo n.º 7
0
def unlike(article_slug):
    user = current_identity
    article = Article.query.filter_by(slug=article_slug).options(load_only('id', 'title')).first()
    like = Like.query.filter_by(article_id=article.id, user_id=user.id).first()
    if like is not None:
        db.session.delete(like)
        db.session.commit()
        return get_success_response('You have just successfully disliked the article: %s' % article.title)
    else:
        return get_error_response('Permission denied, You are not liking this article')
Ejemplo n.º 8
0
def follow_user(username):
    user = current_identity
    following = User.query.filter_by(username=username).options(load_only('id')).first()
    if not hasattr(following, 'username'):
        return get_error_response('Permission denied, This user does not exist')
    if following.id == user.id:
        return get_error_response('Permission denied, You can not follow yourself')

    user_subscription = UserSubscription.query.filter_by(following_id=following.id, follower_id=user.id).first()

    if user_subscription is None:
        if following.is_admin_or_author():
            user_subscription = UserSubscription(following_id=following.id, follower_id=user.id)
            db.session.add(user_subscription)
            db.session.commit()
            return get_success_response('You are now following %s' % username)
        else:
            return get_error_response('Permission denied, You can not follow a non author user')
    else:
        return get_error_response('Permission denied, You already following this user')
Ejemplo n.º 9
0
def like_article(article_slug):
    user = current_identity
    article = Article.query.filter_by(slug=article_slug).options(load_only('id', 'title')).first()

    if Like.query.filter_by(article_id=article.id, user_id=user.id).count() == 0:
        like = Like(article_id=article.id, user_id=user.id)
        db.session.add(like)
        db.session.commit()
        return get_success_response('You are now liking %s' % article.title)
    else:
        return get_error_response('Permission denied, You already liked this article')
Ejemplo n.º 10
0
def update_comment(comment_id):
    comment = Comment.query.get_or_404(comment_id)
    if comment is None:
        return get_error_response(messages='not found', status_code=404)
    content = request.json.get('content')
    if content:
        comment.content = content

    db.session.commit()
    return get_success_response(data=CommentDetailsSerializer(comment).data,
                                messages='Comment updated successfully')
Ejemplo n.º 11
0
def update_comment(id):
    todo = Todo.query.get(id)
    if todo is None:
        return get_error_response(messages='not found', status_code=404)
    todo.title = request.json.get('title')
    description = request.json.get('description', None)

    if description is not None:
        todo.description = description

    todo.completed = request.json.get('completed')
    db.session.commit()
    return jsonify(TodoDetailsSerializer(todo).data), 200
Ejemplo n.º 12
0
def update_comment(comment_id):
    # comment = Comment.query.get_or_404(comment_id)
    comment = Comment.query.get(comment_id)
    if comment is None:
        return get_error_response(messages='not found', status_code=404)

    if current_user.is_admin() or comment.user_id == current_user.id:
        content = request.json.get('content')
        rating = request.json.get('rating')

        if content:
            comment.content = content
        if rating:
            comment.rating = rating

        db.session.commit()
        return get_success_response(
            data=CommentDetailsSerializer(comment).data,
            messages='Comment updated successfully')
    else:
        return get_error_response(
            'Permission denied, you can not update this comment',
            status_code=401)
Ejemplo n.º 13
0
def create_tag():
    if current_user.is_not_admin():
        return jsonify(
            get_error_response('Permission denied, you must be admin',
                               status_code=401))

    name = request.form.get('name')
    description = request.form.get('description')

    tag = Tag(name=name, description=description)

    if 'images[]' in request.files:
        for image in request.files.getlist('images[]'):
            if image and validate_file_upload(image.filename):
                filename = secure_filename(image.filename)
                dir_path = app.config['IMAGES_LOCATION']
                dir_path = os.path.join((os.path.join(dir_path, 'tags')))

                if not os.path.exists(dir_path):
                    os.makedirs(dir_path)

                file_path = os.path.join(dir_path, filename)
                image.save(file_path)

                file_path = file_path.replace(
                    app.config['IMAGES_LOCATION'].rsplit(os.sep, 2)[0], '')
                if image.content_length == 0:
                    file_size = image.content_length
                else:
                    file_size = os.stat(file_path).st_size

                ti = TagImage(file_path=file_path,
                              file_name=filename,
                              original_name=image.filename,
                              file_size=file_size)
                tag.images.append(ti)

    db.session.add(tag)
    db.session.commit()

    return get_success_response(data=tag.get_summary(),
                                messages='Tag created successfully')
Ejemplo n.º 14
0
def update_article(article_slug):
    article = Article.query.filter_by(slug=article_slug).first()
    if article is None:
        return get_error_response(messages='not found', status_code=404)
    title = request.json.get('title')
    if title:
        article.title = title

    description = request.json.get('description')
    if description:
        article.description = description

    body = request.json.get('body')
    if body:
        article.body = body

    tags_input = request.json.get('tags')
    categories_input = request.json.get('categories')
    tags = []
    categories = []
    if categories_input:
        for category in categories_input:
            categories.append(
                get_or_create(db.session, Category, {'description': category.get('description', None)},
                              name=category['name'])[0])

    if tags_input:
        for tag in tags_input:
            tags.append(get_or_create(db.session, Tag, {'description': tag.get('description')}, name=tag['name'])[0])

    article.tags = tags
    article.categories = categories
    db.session.commit()
    response = {'full_messages': ['Article updated successfully']}
    response.update(ArticleDetailsSerializer(article).data)
    return jsonify(response)
Ejemplo n.º 15
0
def create():
    if current_user.is_not_admin():
        return jsonify(
            get_error_response('Permission denied, you must be admin',
                               status_code=401))

    product_name = request.form.get('name')
    description = request.form.get('description')
    price = request.form.get('price')
    stock = request.form.get('stock')
    tags = []
    categories = []

    for header_key in list(request.form.keys()):
        if 'tags[' in header_key:
            name = header_key[header_key.find("[") + 1:header_key.find("]")]
            description = request.form[header_key]
            tags.append(
                get_or_create(db.session,
                              Tag, {'description': description},
                              name=name)[0])

        if header_key.startswith('categories['):
            result = re.search('\[(.*?)\]', header_key)
            if len(result.groups()) == 1:
                name = result.group(1)
                description = request.form[header_key]
                categories.append(
                    get_or_create(db.session,
                                  Category, {'description': description},
                                  name=name)[0])

    product = Product(name=product_name,
                      description=description,
                      price=price,
                      stock=stock,
                      tags=tags,
                      categories=categories)

    if 'images[]' in request.files:
        for image in request.files.getlist('images[]'):
            if image and validate_file_upload(image.filename):
                filename = secure_filename(image.filename)
                dir_path = app.config['IMAGES_LOCATION']
                dir_path = os.path.join((os.path.join(dir_path, 'products')))

                if not os.path.exists(dir_path):
                    os.makedirs(dir_path)

                file_path = os.path.join(dir_path, filename)
                image.save(file_path)

                file_path = file_path.replace(
                    app.config['IMAGES_LOCATION'].rsplit(os.sep, 2)[0], '')
                if image.content_length == 0:
                    file_size = image.content_length
                else:
                    file_size = os.stat(file_path).st_size

                product_image = ProductImage(file_path=file_path,
                                             file_name=filename,
                                             original_name=image.filename,
                                             file_size=file_size)
                product.images.append(product_image)

    db.session.add(product)
    db.session.commit()

    response = {'full_messages': ['Product created successfully']}
    response.update(ProductDetailsSerializer(product).data)
    return jsonify(response)