Пример #1
0
    def post(self, product_id):  # pylint: disable=no-self-use
        """Puts a product information in to DB with product ID as a key.

        Args:
            product_id: Unique ID of the product.

        Returns:
            A dictionary containing success message.
        """
        LOGGER.info('Recieved POST request for product ID: %s', product_id)
        data = request.form.get('data', '{}')
        if not data:
            # Return '400' with 'no data to save' message.
            return {'success': False, 'msg': 'No data to post.'}, BAD_REQUEST
        try:
            data_dict = json.loads(data)
            product_name = data_dict.get('product_name', '')
            products.ProductsDetails.cached_create(
                    product_id=product_id, product_name=product_name,
                    product_json=data)
        except Exception as error:
            message = ('Error while saving product ID %s: %s' %
                       (product_id, error.message))
            LOGGER.error(message)
            return {'success': False, 'msg': message}, INTERNAL_ERROR
        return {'success': True, 'msg': 'Data posted successfully.'}
Пример #2
0
    def post(self, product_id, request=request):  #pylint: disable=no-self-use
        """Puts a product information in to DB with product ID as a key.

        Args:
            product_id: Unique ID of the product.

        Returns:
            A dictionary containing success message.
        """
        LOGGER.info('Received POST request for product ID: %s', product_id)
        data = json.loads(request.data)
        product_name = data.get('product_name', '')
        product_type = data.get('product_type', '')
        if not (product_name or product_type):
            # Return '400' with 'no data to save' message.
            return ({'success': False, 'msg': 'No data to post.'}, BAD_REQUEST,
                    ACCESS_CONTROL_HEADERS)
        try:
            products.ProductsDetails.cached_create(
                    product_id=product_id, product_name=product_name,
                    product_type=product_type)
        except Exception as error:  #pylint: disable=broad-except
            message = ('Error while saving product ID %s: %s' %
                       (product_id, error.message))
            LOGGER.error(message)
            return ({'success': False, 'msg': message}, INTERNAL_ERROR,
                    ACCESS_CONTROL_HEADERS)
        return ({'success': True, 'msg': 'Data posted successfully.'}, SUCCESS,
                ACCESS_CONTROL_HEADERS)
Пример #3
0
    def post(self, product_id, request=request):  #pylint: disable=no-self-use
        """Puts a product information in to DB with product ID as a key.

        Args:
            product_id: Unique ID of the product.

        Returns:
            A dictionary containing success message.
        """
        LOGGER.info('Received POST request for product ID: %s', product_id)
        data = json.loads(request.data)
        product_name = data.get('product_name', '')
        product_type = data.get('product_type', '')
        if not (product_name or product_type):
            # Return '400' with 'no data to save' message.
            return {'success': False, 'msg': 'No data to post.'}, BAD_REQUEST
        try:
            products.ProductsDetails.cached_create(
                    product_id=product_id, product_name=product_name,
                    product_type=product_type)
        except Exception as error:  #pylint: disable=broad-except
            message = ('Error while saving product ID %s: %s' %
                       (product_id, error.message))
            LOGGER.error(message)
            return {'success': False, 'msg': message}, INTERNAL_ERROR
        return {'success': True, 'msg': 'Data posted successfully.'}
Пример #4
0
    def post(self, product_id, request=request):  # pylint: disable=no-self-use
        """Puts a product information in to DB with product ID as a key.

        Args:
            product_id: Unique ID of the product.

        Returns:
            A dictionary containing success message.
        """
        LOGGER.info('Recieved POST request for product ID: %s', product_id)
        data =request.forms.get('data', '{}')

        if not data:
            raise ProductApiError('No data to post.')
        try:
            data_dict = json.loads(data)
            product_name = data_dict.get('product_name', '')
            val = products.ProductsDetails.cached_create(
                    product_id=product_id, product_name=product_name,
                    product_json=data)
            print "RETUN VAL", val
        except Exception as error:
            print str(traceback.format_exc())
            message = ('Error while saving product ID %s: %s' %
                       (product_id, error.message))
            LOGGER.error(message)
            return {'success': False, 'msg': message}
        return {'success': True, 'msg': 'Data posted...'}
Пример #5
0
    def cached_create(cls, **kwargs):
        """Creates coloumn in to DB and deletes key from cache.

        Use this function instead of 'Models.create()' to enforce clearing of
        cache for the same key.

        Args:
            kwargs: Dictionary containing column name to value mapping.
        """
        key_name = cls._primary_keys.keys()[0]
        value = kwargs[key_name]
        LOGGER.info('Inserting product with ID %s in to DB.', value)
        cls.create(**kwargs)
        REDIS_CLIENT.delete(value)
Пример #6
0
    def cached_create(cls, **kwargs):
        """Creates column in to DB and deletes key from cache.

        Use this function instead of 'Models.create()' to enforce clearing of
        cache for the same key.

        Args:
            kwargs: Dictionary containing column name to value mapping.
        """
        key_name = cls._primary_keys.keys()[0]
        value = kwargs[key_name]
        LOGGER.info('Inserting product with ID %s in to DB.', value)
        cls.create(**kwargs)
        REDIS_CLIENT.delete(value)
Пример #7
0
    def cached_delete(cls, **kwargs):
        """Deletes a column DB and from cache.

        Use this function instead of 'Models.delete()' to enforce clearing of
        cache for the same key.

        Args:
            kwargs: Dictionary containing column name to value mapping.
        """
        key_name = cls._primary_keys.keys()[0]
        value = kwargs[key_name]
        data = cls.get(**kwargs)
        LOGGER.info('Deleting product with ID %s from DB.', value)
        data.delete()
        REDIS_CLIENT.delete(value)
Пример #8
0
    def get(self):  # pylint: disable=no-self-use
        """Gets information about all available products.

        Returns:
            A dictionary containing products info as JSON string.
        """
        LOGGER.info('Received GET request for products list')
        try:
            query = products.ProductsDetails.objects.all()
            products_list = []
            for product in query:
                products_list.append({
                    'product_id': product.product_id,
                    'product_name': product.product_name,
                    'product_type': product.product_type
                })
        except Exception as error:
            message = ('Error while fetching products list, %s' % error.message)
            LOGGER.error(message)
            return {'success': False, 'msg': message}, INTERNAL_ERROR
        return {'success': True, 'products': products_list}
Пример #9
0
    def get(self, product_id):  #pylint: disable=no-self-use
        """Gets a product information by its product ID.

        Args:
            product_id: Unique ID of the product.

        Returns:
            A dictionary containing product info as JSON string.
        """
        LOGGER.info('Received GET request for product ID: %s', product_id)
        try:
            product = products.ProductsDetails.cached_get(product_id=product_id)
            data = {
                'product_name': product.product_name,
                'product_id': product.product_id,
                'product_type': product.product_type
            }
        except products.ProductsDetails.DoesNotExist:
            message = 'No data found with product ID %s.' % product_id
            LOGGER.error(message)
            # Return '200' with 'no data found' message.
            return {'success': True, 'msg': message}
        except Exception as error:
            message = ('Error while fetching product ID %s: %s' %
                       (product_id, error.message))
            LOGGER.error(message)
            return {'success': False, 'msg': message}, INTERNAL_ERROR
        return {'success': True, 'data': data}
Пример #10
0
    def delete(self, product_id):  #pylint: disable=no-self-use
        """Deletes a product information from DB.

        Args:
            product_id: Unique ID of the product.

        Returns:
            A dictionary containing success message.
        """
        LOGGER.info('Received DELETE request for product ID: %s', product_id)
        try:
            products.ProductsDetails.cached_delete(product_id=product_id)
        except products.ProductsDetails.DoesNotExist:
            message = 'No data found with product ID %s.' % product_id
            LOGGER.error(message)
            # Return '500' with 'no data found' message.
            return ({'success': False, 'msg': message}, INTERNAL_ERROR,
                    ACCESS_CONTROL_HEADERS)
        except Exception as error:  # pylint: disable=broad-except
            message = ('Error while deleting product ID %s: %s' %
                       (product_id, error.message))
            LOGGER.error(message)
            return ({'success': False, 'msg': message}, INTERNAL_ERROR,
                    ACCESS_CONTROL_HEADERS)
        return ({'success': True, 'msg': 'Data deleted successfully.'}, SUCCESS,
                ACCESS_CONTROL_HEADERS)
Пример #11
0
    def cached_get(cls, **kwargs):
        """Gets data from DB only if it is not found in cache.

        Use this function instead of 'Models.get()' to enforce first lookup from
        cache. Data will be retrieved from DB only if it is not available in
        cache and cache will be filled with data for future retrievals.

        Args:
            kwargs: Dictionary contaning primary key name to value mapping.
                Only one primary key is supported here.

        Returns:
            Object stored with the given primary key.
        """
        key_name = kwargs.keys()[0]
        value = kwargs[key_name]
        data = REDIS_CLIENT.get(value)
        if not data:
            LOGGER.info('Fetching DB for product ID: %s.', value)
            data = cls.get(**kwargs)
            REDIS_CLIENT.set(value, pickle.dumps(data))
        else:
            data = pickle.loads(data)
        return data
Пример #12
0
    def cached_get(cls, **kwargs):
        """Gets data from DB only if it is not found in cache.

        Use this function instead of 'Models.get()' to enforce first lookup from
        cache. Data will be retrieved from DB only if it is not available in
        cache and cache will be filled with data for future retrievals.

        Args:
            kwargs: Dictionary containing primary key name to value mapping.
                Only one primary key is supported here.

        Returns:
            Object stored with the given primary key.
        """
        key_name = kwargs.keys()[0]
        value = kwargs[key_name]
        data = REDIS_CLIENT.get(value)
        if not data:
            LOGGER.info('Fetching DB for product ID: %s.', value)
            data = cls.get(**kwargs)
            REDIS_CLIENT.set(value, pickle.dumps(data))
        else:
            data = pickle.loads(data)
        return data
Пример #13
0
    def get(self, product_id):  # pylint: disable=no-self-use
        """Gets a product information by its product ID.

        Args:
            product_id: Unique ID of the product.

        Returns:
            A dictionary containing product info as JSON string.
        """
        LOGGER.info('Recieved GET request for product ID: %s', product_id)
        try:
            data = products.ProductsDetails.cached_get(product_id=product_id)
        except products.ProductsDetails.DoesNotExist:
            message = 'No data found with product ID %s.' % product_id
            LOGGER.error(message)
            return {'success': False, 'msg': message}
        except Exception as error:
            message = ('Error while fetching product ID %s: %s' %
                       (product_id, error.message))
            LOGGER.error(message)
            return {'success': False, 'msg': message}
        return {'msg': data.product_json}
Пример #14
0
    def delete(self, product_id):  #pylint: disable=no-self-use
        """Deletes a product information from DB.

        Args:
            product_id: Unique ID of the product.

        Returns:
            A dictionary containing success message.
        """
        LOGGER.info('Received DELETE request for product ID: %s', product_id)
        try:
            products.ProductsDetails.cached_delete(product_id=product_id)
        except products.ProductsDetails.DoesNotExist:
            message = 'No data found with product ID %s.' % product_id
            LOGGER.error(message)
            # Return '500' with 'no data found' message.
            return {'success': False, 'msg': message}, INTERNAL_ERROR
        except Exception as error:  # pylint: disable=broad-except
            message = ('Error while deleting product ID %s: %s' %
                       (product_id, error.message))
            LOGGER.error(message)
            return {'success': False, 'msg': message}, INTERNAL_ERROR
        return {'success': True, 'msg': 'Data deleted successfully.'}
Пример #15
0
        bottle.TEMPLATE_PATH.insert(
            0, '/home/umeshbhaskaran/r_demo/bottle/rackspace_app/templates')
        self.route()

    def route(self):  # pylint: disable=no-self-use
        """
        Method to define dynamic routing with appropriate callbacks for
        RESTFULL service methods GET, POST and DELETE
        """

        APP.route('/rackspace/bottle/api/v1.0/products', \
                  method="GET", callback=Products().get)
        APP.route('/rackspace/bottle/api/v1.0/product/<product_id>', \
                  method="GET", callback=Product().get)
        APP.route('/rackspace/bottle/api/v1.0/product/<product_id>', \
                  method="POST", callback=Product().post)
        APP.route('/rackspace/bottle/api/v1.0/product/<product_id>', \
                  method="DELETE", callback=Product().delete)
        APP.route('/static/<filename:path>', callback=Product().static)
        APP.route('/index.html', callback=Product().index)

    def start(self):  # pylint: disable=no-self-use
        """Implements method to run the in-built http server."""
        APP.run(host=APP.config.SERVER_IP, debug=APP.config.DEBUG)


if __name__ == '__main__':
    LOGGER.info('Starting Server & database connections...')
    db.Database().run()
    Server().start()
Пример #16
0
"""Rackspace demo application."""

import os

from rackspace_app import APP, API, db, LOGGER
from rackspace_app.endpoints import product_api
from flask import render_template


# Add all available API URls and endpoints here.
API.add_resource(
        product_api.Product,
        '/rackspace/flask/api/v1.0/product/<string:product_id>')
API.add_resource(
        product_api.Products, '/rackspace/flask/api/v1.0/products')


@APP.route('/index')
def main():
    return render_template('index.html')

@APP.route('/static/<path:path>')
def static_server():
    return APP.send_static_file(os.path.join('static', path))


if __name__ == '__main__':
    LOGGER.info('Starting Server...')
    db.Database().run()  # Runs Cassandra database server.
    APP.run(host=APP.config['SERVER_IP'], debug=APP.config['DEBUG'])
Пример #17
0
    def __init__(self):
        bottle.TEMPLATE_PATH.insert(0, '/home/umeshbhaskaran/r_demo/bottle/rackspace_app/templates')
        self.route()

    def route(self):  # pylint: disable=no-self-use
        """
        Method to define dynamic routing with appropriate callbacks for
        RESTFULL service methods GET, POST and DELETE
        """

        APP.route('/rackspace/bottle/api/v1.0/products', \
                  method="GET", callback=Products().get)
        APP.route('/rackspace/bottle/api/v1.0/product/<product_id>', \
                  method="GET", callback=Product().get)
        APP.route('/rackspace/bottle/api/v1.0/product/<product_id>', \
                  method="POST", callback=Product().post)
        APP.route('/rackspace/bottle/api/v1.0/product/<product_id>', \
                  method="DELETE", callback=Product().delete)
        APP.route('/static/<filename:path>', callback=Product().static)
        APP.route('/index.html', callback=Product().index)

    def start(self):  # pylint: disable=no-self-use
        """Implements method to run the in-built http server."""
        APP.run(host=APP.config.SERVER_IP, debug=APP.config.DEBUG)

if __name__ == '__main__':
    LOGGER.info('Starting Server & database connections...')
    db.Database().run()
    Server().start()