コード例 #1
0
    def post(self):
        data = PayProducts.parser.parse_args()

        try:

            for payed_product in data.get('products'):
                sold_product = SoldProductModel.find_by_id(
                    payed_product.id['id'])
                sold_product.payment_pending = False
                sold_product.update_to_db()

        except:
            return {
                "message": "an error occurred while updating the sales"
            }, 500

        category = CategoryModel.find_by_name('pago_provedor')

        if not category:
            category = CategoryModel.create_category('pago_provedor')

        transaction = TransactionModel(transaction_id=None,
                                       amount=data.get('total'),
                                       date=str(data.get('date'))[:19],
                                       description=data.get('description'),
                                       is_expense=True,
                                       currency_id=data.get('currency_id'),
                                       category_id=category.category_id,
                                       method=data.get('method'),
                                       exchange=data.get('exchange'))
        transaction.save_to_db()

        return transaction.json(), 201
コード例 #2
0
ファイル: category.py プロジェクト: espstan/fBlog
    def put(self, name):
        data = Category.parser.parse_args()

        if len(name) > Configuration.MAX_CATEGORY_NAME_SIZE:
            return {
                'message':
                'A name\'s length is more than {}'.format(
                    Configuration.MAX_CATEGORY_NAME_SIZE)
            }

        posts_id = data['posts']
        if posts_id:
            posts = get_posts(posts_id)
        else:
            posts = []

        category = CM.find_by_name(name)
        if not category:
            category = CM(name=name)
        else:
            category.name = name

        category.posts = []

        if posts:
            category = add_posts(category, posts)

        try:
            category.save_to_db()
        except SQLAlchemyError as e:
            err = str(e.__class__.__name__)
            return {'message': '{}'.format(err)}, 500
        return category.get_json(), 201
コード例 #3
0
def delete_category(category_id):
    try:
        # VALIDATE REQUEST HEADER, TOKEN
        token = validate_request_header(request,
                                        content=False,
                                        authorization=True)
        user = identity(token)  # validate request's token

        # VALIDATE CATEGORY_ID
        category = CategoryModel.find_by_id(category_id)
        if category is None:
            return jsonify({'message': 'No category found'}), 404

        # AUTHORIZE USER
        if user.id != category.author_id:
            return jsonify({'message': 'Unauthorized action'}), 401

        # DELETE CATEGORY
        default_category = CategoryModel.find_by_name(
            current_app.config['DEFAULT_CATEGORY'])
        for item in category.items:
            item.category_id = default_category.id
        item.save_to_db()
        category.delete_from_db()

        # SUCCEED, RETURN MESSAGE
        return jsonify({'message': 'Category deleted'}), 200

    except BadRequestError as err:
        return jsonify(err.represent()), 400
    except UnauthorizedError as err:
        return jsonify(err.represent()), 401
    except NotFoundError as err:
        return jsonify(err.represent()), 404
コード例 #4
0
    def get(self):
        data = Category.parser.parse_args()
        category = CategoryModel.find_by_name(data['name'].lower())

        if category:
            return category.json(), 200
        else:
            return {"message": "Category not found."}, 404
コード例 #5
0
    def delete(self, name):

        category = CategoryModel.find_by_name(name)

        if category:
            category.delete_from_db()

        return {'message': 'Deleted the category'}
コード例 #6
0
    def get(self, name):

        category = CategoryModel.find_by_name(name)

        if category:
            return category.json()
        return {
            'message': "No category with the name of'{}' exists".format(name)
        }
コード例 #7
0
    def delete(self):
        data = Category.parser.parse_args()

        category = CategoryModel.find_by_name(data['name'].lower())
        if category:
            db.session.query(TransactionModel).filter(
                TransactionModel.category == data['name']).delete()
            category.delete_from_db()

        return {"message": "Category and associated transactions deleted."}
コード例 #8
0
 def delete(self, category_name):
     category = CategoryModel.find_by_name(category_name)
     if category:
         category.delete_from_db()
         return {
             'message': 'category {} Deleted'.format(category_name)
         }, 200
     return {
         "message": "category {} is not availabe".format(category_name)
     }, 400
コード例 #9
0
ファイル: category.py プロジェクト: lethaohuong94/Catalog
def create_category(data, user):
    # If category's name is not unique then raises error.
    category = CategoryModel.find_by_name(data['name'])
    if category is not None:
        raise BadRequestError('category already exists')

    # Request is valid then new category is created, saved, and returned.
    data['author_id'] = user.id
    category = CategoryModel(**data)
    category.save_to_db()
    return jsonify(dump_schema().dump(category).data), 201
コード例 #10
0
    def post(self, name):
        if CategoryModel.find_by_name(name):
            return {'message': "A category with name '{}' already exists.".format(name)}, 400

        category = CategoryModel(name)
        try:
            category.save_to_db()
        except:
            return {"message": "An error occurred creating the category."}, 500

        return category.json(), 201
コード例 #11
0
    def post(self, name):
        if CategoryModel.find_by_name(name):
            return {'message': 'Category already exists'}, 400
        category = CategoryModel(name)

        try:
            category.save_to_db()
        except Exception:
            return {'message': 'Error occured while creating category'}, 500

        return category.json(), 201
コード例 #12
0
ファイル: category.py プロジェクト: espstan/fBlog
 def delete(self, name):
     category = CM.find_by_name(name)
     if category:
         try:
             category.delete_from_db()
         except SQLAlchemyError as e:
             err = str(e.__class__.__name__)
             return {'message': '{}'.format(err)}, 500
         return {'message': 'Category was deleted'}
     return {
         'message': 'Category with name: \'{}\' was not found'.format(name)
     }
コード例 #13
0
ファイル: category.py プロジェクト: basgir/bibliotek
    def get(self, name):
        """GET request that deals with requests that look for a category by name"""

        # Request to the model        
        Category = CategoryModel.find_by_name(name)
        
        # if exists
        if Category:

            # we return a json
            return Category.json()
        
        # if not found
        return {'message': 'Category not found'}, 404
コード例 #14
0
ファイル: category.py プロジェクト: pbohora/flask-app
    def post(self, name):
        category = CategoryModel.find_by_name(name)
        if category:
            return {
                "message": f"A category with name {name} already exists"
            }, 400

        category = CategoryModel(name)
        try:
            category.save_to_db()
        except:
            return {"message": "An error occured while creating category"}, 500

        return category.json(), 201
コード例 #15
0
ファイル: category.py プロジェクト: ysabel31/Python
    def post(self, args):
        if CategoryModel.find_by_name(**args):
            return {
                "message":
                "A category named {} already exists".format(args['name'])
            }, 400  # Bad request

        category = CategoryModel(**args)
        # creator = CreatorModel(data['username'], data['password'])
        # for each of the keys in data say key = value
        # ie username = value, password = value
        category.save_to_db()

        return {
            "message": "Category {} created successfully".format(args['name'])
        }, 201  # created
コード例 #16
0
    def put(self, category_name):

        data = Category.parser.parse_args()
        category = CategoryModel.find_by_name(category_name)

        if category is None:
            category = CategoryModel(category_name, data['category_value'])
        else:
            category.category_value = data['category_value']

        try:
            category.save_to_db()
        except:
            return {"message": " unable to save /update category in DB"}, 500

        return category.json(), 200
コード例 #17
0
    def delete(self, name):
        category = CategoryModel.find_by_name(name)
        if category is None:
            return {
                'success': False,
                'message': 'Category was not found.'
            }, 404

        # try to delete
        try:
            category.delete_from_db()
        except:
            return {'success': False, 'message': 'Something went wrong.'}, 500
        return {
            'success': True,
            'message': 'Category was successfully deleted.'
        }, 200
コード例 #18
0
def put(id, **token):
    """Handles the request of updating an item from its owner

    If the item has a new category we create that category too.

    Arguments:
    id: int
        the index of the item user want to update
    Token: dictionary
        format {"identity": user id, "iat": the time the token was created}

    Return:
    Message if success: dictionary
        format {"msg": "Item updated!"}
    Message if error: dictionary
        format {"msg": The error message}
    Status code: int
        200 if OK
        403 if user is not the owner
        404 if item not found
    """

    # Get the id of the request sender from JWT
    user_identity = token["identity"]
    item = ItemModel.find_by_id(id)

    # Validate information on the request body
    data = validate_item_input(request.json, ItemSchema)

    # Only update an existing item
    if item:
        if item.user_id != user_identity:
            return {"msg": "You need to be the owner!"}, 403

        # Create a new category if necessary for the item
        category = CategoryModel.find_by_name(data["category"]["name"])
        if not category:
            category = CategoryModel(data["category"]["name"])
        category.save_to_db()

        data["category"] = category.id
        item.update_to_db(**data)

    else:
        return {"msg": "Item not found!"}, 404
    return {"msg": "Item updated!"}, 200
コード例 #19
0
ファイル: category.py プロジェクト: basgir/bibliotek
    def delete(self, name):
        """DELETE request that deals with the deletion of a category with at a certain name"""

        # Call the category Model to find a category with a specific name
        Category = CategoryModel.find_by_name(name)

        # If the category exists
        if Category:
            try:
                # then we try to delete
                Category.delete_from_db()
                return {'message': 'Category deleted'}
            except:
                # In case of error
                return {'message': 'ERROR : During the deletion of category : {}'.foramt(id)}
        else:
            # If the category not found
            return {'message' : 'Category not found'}, 404
コード例 #20
0
    def post(self):
        data = Category.parser.parse_args()
        if CategoryModel.find_by_name(data['name']):
            return {
                'message':
                "A category with name '{}' already exists.".format(
                    data['name'])
            }, 400

        category = CategoryModel(uuid.uuid4().hex, data['name'])
        try:
            category.save_entity()
        except:
            return {
                'message': "An error occurred while creating the category."
            }, 500

        return category.json(), 201
コード例 #21
0
    def post(self, name):

        if CategoryModel.find_by_name(name):
            return {
                'message':
                "A category with the name of '{}' already exists".format(name)
            }

        category = CategoryModel(name)

        try:
            category.save_to_db()
        except:
            return {
                'message': "An error occured while creating the category."
            }, 500

        return {'message': "Category '{}' was created".format(name)}, 201
コード例 #22
0
ファイル: category.py プロジェクト: ysabel31/Python
    def put(self, args, _id):
        if CategoryModel.find_by_name(args['name']):
            return {
                "message":
                "Category name {} already exists".format(args['name'])
            }, 400  # category exists

        category = CategoryModel.find_by_id(_id)
        if category:
            category.name = args['name']
            category.save_to_db()
            return {
                "message": "Category name {} has been updated".format(_id)
            }, 200

        return {
            "message": "Category id {} doesn't exists".format(_id)
        }, 400  # media to update not found
コード例 #23
0
    def post(self):
        _category_parser = reqparse.RequestParser(bundle_errors=True)
        _category_parser.add_argument('name',
                                      type=non_empty_string,
                                      required=True,
                                      help="The name field is required!"
                                      )
        data = _category_parser.parse_args()
        if CategoryModel.find_by_name(data['name']):
            return {'message': "A category with name {} already exists".format(data['name'])}, 400

        article = CategoryModel(**data)
        try:
            article.save_to_db()
        except Exception as e:
            return {'message': 'An error occurred while creating the category.'}, 500

        return article.json(), 201
コード例 #24
0
    def post(self):
        """
		Agregar una nueva categoría (Solo los admin pueden hacerlo).
		"""
        if current_identity.user_type != user_types['admin']:
            return {
                "message": "No tiene permitido crear nuevas categorías."
            }, 401

        data = CategoryList.parser.parse_args()
        if CategoryModel.find_by_name(data['name']):
            return {
                "message": f"La categoría {data['name']!r} ya existe."
            }, 400

        new_category = CategoryModel(**data)
        new_category.save_to_db()

        return new_category.json(), 201
コード例 #25
0
    def post(self, name):
        if CategoryModel.find_by_name(name):
            return {
                'success': False,
                'message': 'A category with this name already exists'
            }, 400

        category = CategoryModel(None, name)

        # try to save
        try:
            category.save_to_db()
        except:
            return {'success': False, 'message': 'Something went wrong'}, 500

        return {
            'success': True,
            'message': 'A category was successfully created'
        }, 201
コード例 #26
0
ファイル: category.py プロジェクト: lethaohuong94/Catalog
def delete_category(user, category_id):
    # If the requested category doesn't exist then return 404 error.
    category = CategoryModel.find_by_id(category_id)
    if category is None:
        raise NotFoundError('No category found')

    # If user is not the creator of the category then returns unauthorized error.
    if user.id != category.author_id:
        raise UnauthorizedError('Unauthorized action')

    # Before the category is deleted, all items it contains is moved to default category.
    default_category = CategoryModel.find_by_name(current_app.config['DEFAULT_CATEGORY'])
    for item in category.items:
        item.category_id = default_category.id
        item.save_to_db()

    # If the action is valid, category is deleted. Succeed message is returned.
    category.delete_from_db()
    return jsonify({'message': 'Category deleted'})
コード例 #27
0
ファイル: category.py プロジェクト: lethaohuong94/Catalog
def update_category(data, user, category_id):
    # If name is changed and new name exists then raises error.
    category = CategoryModel.find_by_name(data['name'])
    if category is not None and category.id != category_id:
        raise BadRequestError('category name already exists')

    # The resource that is requested has to exist.
    category = CategoryModel.find_by_id(category_id)
    if category is None:
        raise NotFoundError('No category found')

    # If user is not the creator of category then returns unauthorized error.
    if user.id != category.author_id:
        raise UnauthorizedError('Unauthorized action')

    # Request is valid. Category is updated, saved, and returned.
    category.update(data)
    category.save_to_db()
    return jsonify(dump_schema().dump(category).data)
コード例 #28
0
ファイル: category.py プロジェクト: tuvsheezz/flask-api
    def post(self):
        data = CreateCategory.parser.parse_args()
        if CategoryModel.find_by_name(data['name']):
            return {
                'message':
                "An category with name '{}' already exists.".format(
                    data['name'])
            }, 400

        category = CategoryModel(**data)

        try:
            category.save_to_db()
        except:
            return {
                "message": "An error occurred inserting the category."
            }, 500

        return category.json(), 201
コード例 #29
0
ファイル: category.py プロジェクト: basgir/bibliotek
    def post(self, name):
        """POST request that deals with creation of a category provided a name"""

        # Call the model to look for a category provided a name
        if CategoryModel.find_by_name(name):
            return {'message': "A Category with name '{}' already exists.".format(name)}, 400

        # We create the category with the given name      
        Category = CategoryModel(name)

        try:
            # try to save and commit
            Category.save_to_db()
        except:
            # if error during saving and committing
            return {"message": "An error occurred creating the Category."}, 500

        # we return the json of the category
        return Category.json(), 201
コード例 #30
0
    def post(self, category_name):

        category = CategoryModel.find_by_name(category_name)
        if category:
            return {
                'message': " category {} already exists".format(category_name)
            }, 400

        data = Category.parser.parse_args()
        category = CategoryModel(category_name, data['category_value'])

        try:
            category.save_to_db()  # passing product object to insert
            # print(category)
        except:
            return {
                "message": "error occured while loading category data into DB "
            }, 400

        return category.json(), 201