Example #1
0
    def post(self, request, *args, **kwargs):
        #pdb.set_trace()
        django_statsd.incr('api.upload.bill.file.for.user')
        django_statsd.start('api.upload.bill.file.time.taken')
        try:
            #pdb.set_trace()
            value = check_file_type(request.data['url'].content_type)
            size = request.data['url'].size
            md5_hash = str(calculate_md5(request.data['url']))
            #pdb.set_trace()
            if value == "invalid":
                django_statsd.stop('api.upload.bill.file.time.taken')
                logger.error("Allowed file types pdf, png, jpg or jpeg")
                return Response("Allowed file types pdf, png, jpg or jpeg",
                                status=status.HTTP_400_BAD_REQUEST)

            bill = Bills.objects.get(id=kwargs['id'])

        except Bills.DoesNotExist:
            django_statsd.stop('api.upload.bill.file.time.taken')
            logger.error("bill with the id: %s does not exists", kwargs['id'])
            return Response(status=status.HTTP_404_NOT_FOUND)

        if bill.owner_id != request.user:
            django_statsd.stop('api.upload.bill.file.time.taken')
            logger.error("bill for the user : %s does not exists",
                         request.user)
            return Response(status=status.HTTP_404_NOT_FOUND)

        if bill.attachment is not None:
            django_statsd.stop('api.upload.bill.file.time.taken')
            logger.error("Bill  %s already exists, please delete it first",
                         kwargs['id'])
            return Response("Bill already exists, please delete it first",
                            status=status.HTTP_400_BAD_REQUEST)

        bill_file = BillFile()

        file_serializer = FileSerializer(bill_file, data=request.data)
        if file_serializer.is_valid():
            django_statsd.start('api.post.bill.file.db.time.taken')
            file = file_serializer.save()
            django_statsd.stop('api.post.bill.file.db.time.taken')
            file.size = size
            file.file_name = request.data['url'].name
            file.md5_hash = md5_hash

            file.save()

            data = load_bill_file_data(file)
            bill.attachment = file
            bill.save()
            logger.info("Bill file with the id: %s has been uploaded", file.id)
            django_statsd.stop('api.upload.bill.file.time.taken')
            return Response(data, status=status.HTTP_201_CREATED)
        else:
            django_statsd.stop('api.upload.bill.file.time.taken')
            logger.error("something bad has happened", file_serializer.errors)
            return Response(file_serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Example #2
0
def create_bill_view(request):
    try:
        account = UserAccount.objects.get(email_address=request.user)

        bill = Bills(owner_id=account)

    except Bills.DoesNotExist:
        logger.error("bill with the id: %s does not exists", bill.id)
        return Response(status=status.HTTP_404_NOT_FOUND)

    except UserAccount.DoesNotExist:
        logger.error("user with the id: %s does not exists", account.id)
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'POST':
        django_statsd.start('api.create.bill.time.taken')
        django_statsd.incr('api.create.bill.for.user')
        serializer = CreateBillSerializer(context=bill, data=request.data)
        data = {}
        if serializer.is_valid():
            django_statsd.start('api.post.bill.db.query.time')
            bill = serializer.save()
            django_statsd.stop('api.post.bill.db.query.time')
            data = load_bill_data_for_user(bill)
            django_statsd.stop('api.create.bill.time.taken')
            logger.info("bill with the id: %s has been created", bill.id)
            return Response(data, status=status.HTTP_201_CREATED)
        logger.error("Something bad has happened: ", serializer.errors)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #3
0
def get_bills_view(request):

    if request.method == 'GET':
        django_statsd.incr('api.get.bills.for.user')
        django_statsd.start('api.get.bills.time.taken')
        try:

            user = UserAccount.objects.get(email_address=request.user)

        except UserAccount.DoesNotExist:
            django_statsd.stop('api.get.bills.time.taken')
            logger.error("user with the id: %s doesn't exist", user.id)
            return Response(status=status.HTTP_404_NOT_FOUND)

        try:
            django_statsd.start('api.get.bills.db.time.taken')
            bills = Bills.objects.all().filter(owner_id=user.id)
            django_statsd.stop('api.get.bills.db.time.taken')

            if not bills:
                django_statsd.stop('api.get.bills.time.taken')
                logger.error("bills for the user id: %s does not exists",
                             user.id)
                return Response(status=status.HTTP_404_NOT_FOUND)
        except Bills.DoesNotExist:
            logger.error("bills for the user id: %s does not exists", user.id)
            return Response(status=status.HTTP_404_NOT_FOUND)

        serializer = BillSerializer(bills, many=True)
        logger.info("bills for the user id: %s has been retrieved", user.id)
        django_statsd.stop('api.get.bills.time.taken')
        return Response(serializer.data)
Example #4
0
def registration_view(request):
    if request.method == 'POST':

        django_statsd.incr('api.registerUser')
        django_statsd.start('api.registerUser.time.taken')
        serializer = RegistrationSerializer(data=request.data)
        data = {}
        if serializer.is_valid():
            django_statsd.start('api.registerUser.db')
            account = serializer.save()
            django_statsd.stop('api.registerUser.db')
            data['response'] = 'successfully registered new user.'
            data['uuid_id'] = account.uuid_id
            data['email'] = account.email
            data['first_name'] = account.first_name
            data['last_name'] = account.last_name
            data['account_created'] = account.account_created
            data['account_updated'] = account.account_updated
            logger.info("POST: User Created with uuid: %s", account.uuid_id)
            django_statsd.stop('api.registerUser.time.taken')
            return Response(data, status=status.HTTP_201_CREATED)

        logger.error("ERROR: Something Happened: %s", serializer.errors)
        django_statsd.stop('api.registerUser.time.taken')
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #5
0
def registration_view(request):

    if request.method == 'POST':

        django_statsd.incr('api.registration.user.count')

        django_statsd.start('api.registration.user.time.taken')

        serializer = RegistrationSerializer(data=request.data)
        data = {}
        if serializer.is_valid():
            django_statsd.start('api.registration.db.query.time')
            account = serializer.save()
            django_statsd.stop('api.registration.db.query.time')
            data['id'] = account.id
            data['first_name']= account.first_name
            data['last_name'] = account.last_name
            data['email_address'] = account.email_address
            data['account_created'] = account.account_created
            data['account_updated'] = account.account_updated
            logger.info("User has been created with the id: %s", account.id)
            django_statsd.stop('api.registration.user.time.taken')
            return Response(data, status=status.HTTP_201_CREATED)
        logger.error("Something bad has happened: %s", serializer.errors)
        django_statsd.stop('api.registration.user.time.taken')
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #6
0
    def _request(cls,
                 url,
                 post_data=None,
                 timeout=REQUEST_TIMEOUT,
                 attempts=REQUEST_ATTEMPTS):
        '''
        request the given url and parse it as json
        urllib2 raises errors on different status codes so use a try except
        '''
        logger.info('requesting url %s with post data %s', url, post_data)
        post_request = (post_data is not None or 'method=post' in url)

        if post_request and facebook_settings.FACEBOOK_READ_ONLY:
            response = dict(id=123456789)
            return response

        opener = urllib2.build_opener()
        opener.addheaders = [('User-agent', 'Open Facebook Python')]
        # give it a few shots, connection is buggy at times

        path = url.split('?', 1)[0].rsplit('/', 1)[-1].replace('.', '_')
        while attempts:
            response_file = None
            encoded_params = encode_params(post_data) if post_data else None
            post_string = (urllib.urlencode(encoded_params)
                           if post_data else None)
            try:
                if django_statsd:
                    django_statsd.start('facebook.%s' % path)

                try:
                    # For older python versions you could leave out the timeout
                    # response_file = opener.open(url, post_string)
                    response_file = opener.open(url,
                                                post_string,
                                                timeout=timeout)
                except (urllib2.HTTPError, ), e:
                    # Facebook sents error codes for many of their flows
                    # we still want the json to allow for proper handling
                    logger.warn('FB request, error type %s, code %s', type(e),
                                getattr(e, 'code', None))
                    if hasattr(e, 'code') and e.code == 500:

                        raise urllib2.URLError('Facebook is down')
                    if 'http error' in str(e).lower():
                        response_file = e
                    else:
                        raise
                response = response_file.read().decode('utf8')
                break
            except (urllib2.HTTPError, urllib2.URLError, ssl.SSLError), e:
                #These are often temporary errors, so we will retry before failing
                error_format = 'Facebook encountered a timeout or error %s'
                logger.warn(error_format, unicode(e))
                attempts -= 1
                if not attempts:
                    #if we have no more attempts actually raise the error
                    raise facebook_exceptions.convert_unreachable_exception(e)
Example #7
0
    def _request(cls, url, post_data=None, timeout=REQUEST_TIMEOUT,
                 attempts=REQUEST_ATTEMPTS):
        '''
        request the given url and parse it as json
        urllib2 raises errors on different status codes so use a try except
        '''
        logger.info('requesting url %s with post data %s', url, post_data)
        post_request = (post_data is not None or 'method=post' in url)

        if post_request and facebook_settings.FACEBOOK_READ_ONLY:
            logger.info('running in readonly mode')
            response = dict(id=123456789, setting_read_only=True)
            return response

        opener = urllib2.build_opener()
        opener.addheaders = [('User-agent', 'Open Facebook Python')]
        # give it a few shots, connection is buggy at times

        path = url.split('?', 1)[0].rsplit('/', 1)[-1].replace('.', '_')
        while attempts:
            response_file = None
            encoded_params = encode_params(post_data) if post_data else None
            post_string = (urllib.urlencode(encoded_params)
                           if post_data else None)
            try:
                if django_statsd:
                    django_statsd.start('facebook.%s' % path)

                try:
                    # For older python versions you could leave out the timeout
                    # response_file = opener.open(url, post_string)
                    response_file = opener.open(url, post_string,
                                                timeout=timeout)
                except (urllib2.HTTPError,), e:
                    # Facebook sents error codes for many of their flows
                    # we still want the json to allow for proper handling
                    logger.warn('FB request, error type %s, code %s',
                                type(e), getattr(e, 'code', None))
                    if hasattr(e, 'code') and e.code == 500:

                        raise urllib2.URLError('Facebook is down')
                    if 'http error' in str(e).lower():
                        response_file = e
                    else:
                        raise
                response = response_file.read().decode('utf8')
                break
            except (urllib2.HTTPError, urllib2.URLError, ssl.SSLError), e:
                #These are often temporary errors, so we will retry before failing
                error_format = 'Facebook encountered a timeout or error %s'
                logger.warn(error_format, unicode(e))
                attempts -= 1
                if not attempts:
                    #if we have no more attempts actually raise the error
                    raise facebook_exceptions.convert_unreachable_exception(e)
Example #8
0
def api_get_delete_file_view(request, uuid_bill_id, uuid_file_id):
    try:
        bill = Bill.objects.get(uuid_bill_id=uuid_bill_id)
        django_statsd.start('api.getFile.DB')
        file = File.objects.get(uuid_file_id=uuid_file_id)
        django_statsd.stop('api.getFile.DB')
    except (Bill.DoesNotExist, File.DoesNotExist):
        logger.error("Bill or File doesn't exist")
        django_statsd.stop('api.getFile.DB')
        return Response({'response': "Bill or File doesn't exist."},
                        status=status.HTTP_404_NOT_FOUND)

    if bill.owner_id != request.user:
        logger.error("User You doesn't have permissions")
        return Response(
            {
                'response':
                "You don't have permissions to get/update/delete that bill."
            },
            status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        django_statsd.incr('api.getFile')
        django_statsd.start('api.getFile.time.taken')
        serializer = FileGetSerializer(file)
        logger.info("GET: Uploaded File")
        django_statsd.stop('api.getFile.time.taken')
        return Response(serializer.data)

    elif request.method == 'DELETE':
        django_statsd.incr('api.deleteFile')
        django_statsd.start('api.deleteFile.time.taken')

        if 'S3_BUCKET_NAME' in os.environ:
            django_statsd.start('s3.deleteFile.time.taken')
            file.url.delete(save=False)
            django_statsd.stop('s3.deleteFile.time.taken')
        else:
            file_path = 'bill/{file_id}-{filename}'.format(
                file_id=str(file.uuid_file_id), filename=file.file_name)
            os.remove(os.path.join(settings.MEDIA_ROOT, file_path))

        django_statsd.start('api.deleteFile.DB')
        operation = file.delete()
        django_statsd.stop('api.deleteFile.DB')

        data = {}
        if operation:
            data['response'] = 'successfully deleted the file.'
            logger.info("DELETE: Delete Uploaded File")
            django_statsd.stop('api.deleteFile.time.taken')
            return Response(data=data, status=status.HTTP_204_NO_CONTENT)
Example #9
0
    def delete(self, request, *args, **kwargs):

        try:
            #pdb.set_trace()
            django_statsd.start('api.delete.uploaded.bill.file.time.taken')
            django_statsd.incr('api.delete.bill.file.for.user')

            bill = Bills.objects.get(id=kwargs['id'])
            bill_file = BillFile.objects.get(id=kwargs['bill_file_id'])

            if bill.owner_id != request.user:
                logger.error("bill for the user id: %s does not exists",
                             bill.owner_id)
                django_statsd.stop('api.delete.uploaded.bill.file.time.taken')
                return Response(status=status.HTTP_404_NOT_FOUND)
            BillFile.objects.filter(id=kwargs['bill_file_id']).delete()
            if 'DB_HOST' in os.environ:
                bill_file.url.delete(save=False)
            else:
                try:
                    os.remove(
                        os.path.join(settings.MEDIA_ROOT,
                                     bill_file.url.name.split('/')[1]))

                except FileNotFoundError:
                    django_statsd.stop(
                        'api.delete.uploaded.bill.file.time.taken')
                    return Response(
                        "File not found or has been manually deleted",
                        status=status.HTTP_400_BAD_REQUEST)
            django_statsd.start('api.get.bill.file.db.time.taken')
            BillFile.objects.filter(id=bill_file.id).delete()
            django_statsd.stop('api.get.bill.file.db.time.taken')
            django_statsd.stop('api.delete.uploaded.bill.file.time.taken')
            return Response(status=status.HTTP_204_NO_CONTENT)
        except FileNotFoundError:
            django_statsd.stop('api.delete.uploaded.bill.file.time.taken')
            logger.error("bill file with the id: %s does not exists",
                         kwargs['bill_file_id'])
            return Response(status=status.HTTP_400_BAD_REQUEST)
        except Bills.DoesNotExist:
            logger.error("bill with the id: %s does not exists", kwargs['id'])
            django_statsd.stop('api.delete.uploaded.bill.file.time.taken')
            return Response(status=status.HTTP_404_NOT_FOUND)

        except BillFile.DoesNotExist:
            logger.error("bill with the id: %s does not exists",
                         kwargs['bill_file_id'])
            django_statsd.stop('api.delete.uploaded.bill.file.time.taken')
            return Response("File not found",
                            status=status.HTTP_400_BAD_REQUEST)
Example #10
0
    def _request(cls,
                 url,
                 post_data=None,
                 timeout=REQUEST_TIMEOUT,
                 attempts=REQUEST_ATTEMPTS):
        '''
        request the given url and parse it as json
        urllib2 raises errors on different status codes so use a try except
        '''
        logger.info('requesting url %s with post data %s', url, post_data)
        post_request = (post_data is not None or 'method=post' in url)

        if post_request and facebook_settings.FACEBOOK_READ_ONLY:
            response = dict(id=123456789)
            return response

        opener = urllib2.build_opener()
        opener.addheaders = [('User-agent', 'Open Facebook Python')]
        # give it a few shots, connection is buggy at times

        path = url.split('?', 1)[0].rsplit('/', 1)[-1].replace('.', '_')
        while attempts:
            response_file = None
            encoded_params = encode_params(post_data) if post_data else None
            post_string = (urllib.urlencode(encoded_params)
                           if post_data else None)
            try:
                if django_statsd:
                    django_statsd.start('facebook.%s' % path)

                try:
                    # For older python versions you could leave out the timeout
                    # response_file = opener.open(url, post_string)
                    response_file = opener.open(url,
                                                post_string,
                                                timeout=timeout)
                except (urllib2.HTTPError, ), e:
                    # catch the silly status code errors
                    if 'http error' in str(e).lower():
                        response_file = e
                    else:
                        raise
                response = response_file.read().decode('utf8')
                break
            except (urllib2.HTTPError, urllib2.URLError), e:
                logger.warn('facebook encountered a timeout or error %s',
                            unicode(e))
                attempts -= 1
                if not attempts:
                    raise
Example #11
0
    def _request(cls, url, post_data=None, timeout=REQUEST_TIMEOUT, attempts=REQUEST_ATTEMPTS):
        """
        request the given url and parse it as json
        urllib2 raises errors on different status codes so use a try except
        """
        logger.info("requesting url %s with post data %s", url, post_data)
        post_request = post_data is not None or "method=post" in url

        if post_request and facebook_settings.FACEBOOK_READ_ONLY:
            response = dict(id=123456789)
            return response

        opener = urllib2.build_opener()
        opener.addheaders = [("User-agent", "Open Facebook Python")]
        # give it a few shots, connection is buggy at times

        path = url.split("?", 1)[0].rsplit("/", 1)[-1].replace(".", "_")
        while attempts:
            response_file = None
            encoded_params = encode_params(post_data) if post_data else None
            post_string = urllib.urlencode(encoded_params) if post_data else None
            try:
                if django_statsd:
                    django_statsd.start("facebook.%s" % path)

                try:
                    # For older python versions you could leave out the timeout
                    # response_file = opener.open(url, post_string)
                    response_file = opener.open(url, post_string, timeout=timeout)
                except (urllib2.HTTPError,), e:
                    # Facebook sents error codes for many of their flows
                    # we still want the json to allow for proper handling
                    if hasattr(e, "code") and e.code == 500:

                        raise urllib2.URLError("Facebook is down")
                    if "http error" in str(e).lower():
                        response_file = e
                    else:
                        raise
                response = response_file.read().decode("utf8")
                break
            except (urllib2.HTTPError, urllib2.URLError, ssl.SSLError), e:
                # These are often temporary errors, so we will retry before failing
                error_format = "Facebook encountered a timeout or error %s"
                logger.warn(error_format, unicode(e))
                attempts -= 1
                if not attempts:
                    # if we have no more attempts actually raise the error
                    raise facebook_exceptions.convert_unreachable_exception(e)
Example #12
0
    def _request(cls, url, post_data=None, timeout=REQUEST_TIMEOUT,
                 attempts=REQUEST_ATTEMPTS):
        '''
        request the given url and parse it as json
        urllib2 raises errors on different status codes so use a try except
        '''
        logger.info('requesting url %s with post data %s', url, post_data)
        post_request = (post_data is not None or 'method=post' in url)

        if post_request and facebook_settings.FACEBOOK_READ_ONLY:
            response = dict(id=123456789)
            return response

        opener = urllib2.build_opener()
        opener.addheaders = [('User-agent', 'Open Facebook Python')]
        # give it a few shots, connection is buggy at times

        path = url.split('?', 1)[0].rsplit('/', 1)[-1].replace('.', '_')
        while attempts:
            response_file = None
            encoded_params = encode_params(post_data) if post_data else None
            post_string = (urllib.urlencode(encoded_params)
                           if post_data else None)
            try:
                if django_statsd:
                    django_statsd.start('facebook.%s' % path)

                try:
                    # For older python versions you could leave out the timeout
                    # response_file = opener.open(url, post_string)
                    response_file = opener.open(url, post_string,
                                                timeout=timeout)
                except (urllib2.HTTPError,), e:
                    # catch the silly status code errors
                    if 'http error' in str(e).lower():
                        response_file = e
                    else:
                        raise
                response = response_file.read().decode('utf8')
                break
            except (urllib2.HTTPError, urllib2.URLError), e:
                logger.warn('facebook encountered a timeout or error %s',
                            unicode(e))
                attempts -= 1
                if not attempts:
                    raise
Example #13
0
def api_get_all_bills_view(request):
    try:
        django_statsd.start('api.getAllBills.DB')
        account_user = Account.objects.get(email=request.user)
        bill = Bill.objects.all().filter(owner_id=account_user.uuid_id)
        django_statsd.stop('api.getAllBills.DB')
    except Bill.DoesNotExist:
        logger.error("Bill Doesn't Exist")
        django_statsd.stop('api.getAllBills.DB')
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        django_statsd.incr('api.getAllBills')
        django_statsd.start('api.getAllBills.time.taken')
        serializer = BillGetSerializer(bill, many=True)
        logger.info("GET: All Bills for User with uuid: %s", account_user.uuid_id)
        django_statsd.stop('api.getAllBills.time.taken')
        return Response(serializer.data)
    def _request(cls, url, post_data=None, timeout=REQUEST_TIMEOUT,
                 attempts=REQUEST_ATTEMPTS):
        """Perform a HTTP request to the given URL and parse it as JSON.
        
        ``urllib2`` raises errors on different status codes so we
        use a ``try .. except`` clause here.
        """
        logger.info('requesting url %s with post data %s', url, post_data)
        opener = urllib2.build_opener()
        opener.addheaders = [('User-agent', 'Open Facebook Python')]
        # give it a few shots, connection is buggy at times

        encoded_params = encode_params(post_data) if post_data else None
        post_string = (urllib.urlencode(encoded_params) if post_data else None)

        if django_statsd:
            _statsd_path = url.split('?', 1)[0].rsplit('/', 1)[-1].replace('.', '_')
            _statsd_id = "facebook.%s" % _statsd_path
        
        while attempts:
            response_file = None
            try:
                if django_statsd:
                    django_statsd.start(_statsd_id)
                try:
                    ## For older Python versions you could leave out
                    ## the timeout
                    #response_file = opener.open(url, post_string)
                    response_file = opener.open(url, post_string, timeout=timeout)
                except (urllib2.HTTPError,), e:
                    ## Catch the silly status code errors
                    if 'http error' in str(e).lower():
                        response_file = e
                    else:
                        raise
                response = response_file.read().decode('utf8')
                break
            except (urllib2.HTTPError, urllib2.URLError), e:
                logger.warn('Facebook Graph API request: error or timeout: %s', unicode(e))
                attempts -= 1
                if attempts <= 0:
                    ## Maximum number of attempts reached, stop retrying 
                    raise
Example #15
0
    def get(self, request, *args, **kwargs):
        django_statsd.incr('api.get.bill.file.for.user')
        django_statsd.start('api.get.uploaded.bill.file.time.taken')
        try:
            django_statsd.start('api.get.bill.file.db.time.taken')
            bill = Bills.objects.get(id=kwargs['id'])
            django_statsd.start('api.get.bill.file.db.time.taken')

            bill_file = BillFile.objects.get(id=kwargs['bill_file_id'])

        except Bills.DoesNotExist:
            django_statsd.stop('api.get.uploaded.bill.file.time.taken')
            logger.error("bill with the id: %s does not exists", bill.id)
            return Response(status=status.HTTP_404_NOT_FOUND)

        except BillFile.DoesNotExist:
            logger.error("bill file with the id: %s does not exists",
                         bill_file.id)
            django_statsd.stop('api.get.uploaded.bill.file.time.taken')
            return Response(status=status.HTTP_404_NOT_FOUND)

        if bill.owner_id != request.user:
            logger.error("bill for the user id: %s does not exists",
                         bill.owner_id)
            django_statsd.stop('api.get.uploaded.bill.file.time.taken')
            return Response(status=status.HTTP_404_NOT_FOUND)

        #serializer = BillFileSerializer(bill_file)
        data = load_bill_file_data(bill_file)
        logger.info("bill file with the id: %s has been retrieved",
                    bill_file.id)
        django_statsd.stop('api.get.uploaded.bill.file.time.taken')
        return Response(data)
Example #16
0
def api_create_bill_view(request):
    bill_post = Bill(owner_id=request.user)
    account_user = Account.objects.get(email=request.user)

    if request.method == 'POST':
        django_statsd.incr('api.createBill')
        django_statsd.start('api.createBill.time.taken')
        serializer = BillSerializer(bill_post, data=request.data)
        data = {}
        if serializer.is_valid():

            categories_list = serializer.validated_data['categories']
            if len(categories_list) != len(set(categories_list)):
                return Response({'response': "Categories must be unique."},
                                status=status.HTTP_400_BAD_REQUEST)
            django_statsd.start('api.createBill.db')
            bill = serializer.save()
            django_statsd.stop('api.createBill.db')
            data['response'] = 'successfully added a new bill.'
            data['uuid_bill_id'] = bill.uuid_bill_id
            data['created_ts'] = bill.created_ts
            data['updated_ts'] = bill.updated_ts
            data['owner_id'] = account_user.uuid_id
            data['vendor'] = bill.vendor
            data['bill_date'] = bill.bill_date
            data['due_date'] = bill.due_date
            data['amount_due'] = bill.amount_due
            data['categories'] = bill.categories
            data['payment_status'] = bill.payment_status
            logger.info("POST: Added Bill")
            django_statsd.stop('api.createBill.time.taken')
            return Response(data, status=status.HTTP_201_CREATED)

        logger.error("ERROR: Something Happened: %s", serializer.errors)
        django_statsd.stop('api.createBill.time.taken')
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #17
0
def api_detail_get_put_view(request):
    try:
        django_statsd.start('api.getUser.DB')
        account = Account.objects.get(email=request.user)
        django_statsd.stop('api.getUser.DB')
    except Account.DoesNotExist:
        logger.error("User Doesn't Exist")
        django_statsd.stop('api.getUser.DB')
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':

        django_statsd.incr('api.getUser')
        django_statsd.start('api.getUser.time.taken')
        serializer = UserSerializer(account)
        logger.info("GET: User with uuid: %s", account.uuid_id)
        django_statsd.stop('api.getUser.time.taken')
        return Response(serializer.data)

    elif request.method == 'PUT':

        django_statsd.incr('api.putUser')
        django_statsd.start('api.putUser.time.taken')
        serializer = UserSerializer2(account, data=request.data)

        data = {}
        if serializer.is_valid():
            django_statsd.start('api.putUser.DB')
            serializer.save()
            django_statsd.stop('api.putUser.DB')
            data['response'] = 'successfully updated.'
            logger.info("PUT: User with uuid: %s", account.uuid_id)
            django_statsd.stop('api.putUser.time.taken')
            return Response(data=data, status=status.HTTP_204_NO_CONTENT)

        logger.error("ERROR: Something Happened: %s", serializer.errors)
        django_statsd.stop('api.putUser.time.taken')
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #18
0
def update_user_view(request):


    try:
        django_statsd.start('api.get.user.db.query.time')
        account = UserAccount.objects.get(email_address=request.user)
        django_statsd.stop('api.get.user.db.query.time')

    except UserAccount.DoesNotExist:
        logger.error("User with the account id: %s does not exists", account.id)
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'PUT':
        django_statsd.start('api.update.user.time.taken')
        django_statsd.incr('api.update.user')
        serializer = UserUpdateSerializer(account, data=request.data)
        data = {}
        if serializer.is_valid():
            django_statsd.start('api.update.user.db.query.time')
            serializer.save()
            django_statsd.stop('api.update.user.db.query.time')
            django_statsd.stop('api.update.user.time.taken')
            logger.info("User has been updated with the id: %s", account.id)
            return Response(status=status.HTTP_204_NO_CONTENT)
        django_statsd.stop('api.update.user.time.taken')
        logger.error("Something bad has happened: %s", serializer.errors)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    if request.method == 'GET':
        django_statsd.incr('api.get.user')
        django_statsd.start('api.get.user.time.taken')
        print(account)
        serializer = UserSerializer(account)
        logger.info("User has been retrieved with the id: %s", account.id)
        django_statsd.stop('api.get.user.time.taken')
        return Response(serializer.data)
Example #19
0
def start_statsd(path):
    '''
    Simple wrapper to save some typing
    '''
    if django_statsd:
        django_statsd.start(path)
Example #20
0
def api_get_put_delete_bill_view(request, uuid_bill_id):
    account_user = Account.objects.get(email=request.user)

    try:
        django_statsd.start('api.getBill.DB')
        bill = Bill.objects.get(uuid_bill_id=uuid_bill_id)

        if bill.attachment is not None:
            file = File.objects.get(uuid_file_id=bill.attachment.uuid_file_id)
        django_statsd.stop('api.getBill.DB')

    except Bill.DoesNotExist:
        logger.error("Bill Doesn't Exist")
        django_statsd.stop('api.getBill.DB')
        return Response({'response': "Bill doesn't exist."},
                        status=status.HTTP_404_NOT_FOUND)

    if bill.owner_id != request.user:
        logger.error("User Doesn't have permissions")
        return Response({'response': "You don't have permissions to get/update/delete that bill."},
                        status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        django_statsd.incr('api.getBill')
        django_statsd.start('api.getBill.time.taken')
        serializer = BillGetSerializer(bill)
        django_statsd.stop('api.getBill.time.taken')
        return Response(serializer.data)

    elif request.method == 'PUT':
        django_statsd.incr('api.putBill')
        django_statsd.start('api.putBill.time.taken')
        serializer = BillSerializer(bill, data=request.data)
        data = {}
        if serializer.is_valid():
            categories_list = serializer.validated_data['categories']
            if len(categories_list) != len(set(categories_list)):
                return Response({'response': "Categories must be unique."},
                                status=status.HTTP_400_BAD_REQUEST)
            django_statsd.start('api.putBill.DB')
            serializer.save()
            django_statsd.stop('api.putBill.DB')
            data['response'] = 'successfully updated a new bill.'
            data['uuid_bill_id'] = bill.uuid_bill_id
            data['created_ts'] = bill.created_ts
            data['updated_ts'] = bill.updated_ts
            data['owner_id'] = account_user.uuid_id
            data['vendor'] = bill.vendor
            data['bill_date'] = bill.bill_date
            data['due_date'] = bill.due_date
            data['amount_due'] = bill.amount_due
            data['categories'] = bill.categories
            data['payment_status'] = bill.payment_status
            logger.info("PUT: Update Bill for User")
            django_statsd.stop('api.putBill.time.taken')
            return Response(data=data, status=status.HTTP_200_OK)

        logger.error("ERROR: Something Happened: %s", serializer.errors)
        django_statsd.stop('api.putBill.time.taken')
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        django_statsd.incr('api.deleteBill')
        django_statsd.start('api.deleteBill.time.taken')

        if bill.attachment is not None:
            if 'S3_BUCKET_NAME' in os.environ:
                django_statsd.start('s3.deleteBill.File.time.taken')
                bill.attachment.url.delete(save=False)
                django_statsd.stop('s3.deleteBill.File.time.taken')
            else:
                file_path = 'bill/{file_id}-{filename}'.format(
                    file_id=str(file.uuid_file_id), filename=file.file_name
                )
                os.remove(os.path.join(settings.MEDIA_ROOT, file_path))

        django_statsd.start('api.deleteBill.DB')
        operation = bill.delete()
        django_statsd.stop('api.deleteBill.DB')
        data = {}
        if operation:
            data['response'] = 'successfully deleted a new bill.'
            logger.info("DELETE: Bill deleted")
            django_statsd.stop('api.deleteBill.time.taken')
            return Response(data=data, status=status.HTTP_204_NO_CONTENT)
Example #21
0
def manage_user_bill_by_id(request, id):

    bill = None
    try:
        django_statsd.start('api.get.bill.db.query.time.taken')
        bill = Bills.objects.get(id=id)
        django_statsd.stop('api.get.bill.db.query.time.taken')

    except Bills.DoesNotExist:
        logger.error("bill with the id: %s does not exists", id)
        django_statsd.stop('api.get.bill.db.query.time.taken')
        return Response(status=status.HTTP_404_NOT_FOUND)

    if bill.owner_id != request.user:
        logger.error("bill for the owner with id: %s does not exists",
                     bill.owner_id)
        django_statsd.stop('api.get.bill.db.query.time.taken')
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        django_statsd.start('api.get.bill.by.id.time.taken')
        django_statsd.incr('api.get.bill.by.id.count')
        serializer = BillSerializer(bill)
        django_statsd.stop('api.get.bill.by.id.time.taken')
        logger.info("bill has been created with the id: %s", bill.id)
        return Response(serializer.data)

    if request.method == 'DELETE':
        django_statsd.incr('api.delete.bill.by.id.count')
        django_statsd.start('api.delete.bill.by.id.time.taken')
        #pdb.set_trace()
        try:

            bill_file = bill.attachment
            if bill_file:
                if 'DB_HOST' in os.environ:
                    django_statsd.start('api.delete.bill.file.s3.query.time')
                    bill_file.url.delete(save=False)
                    django_statsd.stop('api.delete.bill.file.s3.query.time')
                else:
                    try:
                        os.remove(
                            os.path.join(settings.MEDIA_ROOT,
                                         bill_file.url.name.split('/')[1]))
                    except FileNotFoundError:
                        logger.error(
                            "bill with id: %s has been manually deleted",
                            bill.id)
                        django_statsd.stop('api.delete.bill.by.id.time.taken')
                        return Response(
                            "File not found or has been manually deleted",
                            status=status.HTTP_400_BAD_REQUEST)

                BillFile.objects.filter(id=bill_file.id).delete()

        except:
            django_statsd.stop('api.delete.bill.by.id.time.taken')
            logger.error("bad data in db", )
            return Response("bad data in db",
                            status=status.HTTP_400_BAD_REQUEST)

        django_statsd.start('api.delete.bill.file.db.query.time')
        Bills.objects.filter(id=id).delete()
        django_statsd.stop('api.delete.bill.file.db.query.time')
        logger.info("bill with the id: %s has been deleted", bill.id)
        django_statsd.stop('api.delete.bill.by.id.time.taken')
        return Response(status=status.HTTP_204_NO_CONTENT)

    if request.method == 'PUT':
        django_statsd.start('api.update.bill.by.id.time.taken')
        django_statsd.incr('api.update.bill.by.id.count')
        serializer = BillUpdateSerializer(bill, data=request.data)
        data = {}
        if serializer.is_valid():
            django_statsd.start('api.update.bill.file.db.query.time')
            bill = serializer.save()
            django_statsd.stop('api.update.bill.file.db.query.time')
            data = load_bill_data_for_user(bill)
            django_statsd.stop('api.update.bill.by.id.time.taken')
            logger.info("bill with the id: %s has been updated", bill.id)
            return Response(data=data, status=status.HTTP_204_NO_CONTENT)
        django_statsd.stop('api.update.bill.by.id.time.taken')
        logger.error("Something bad has happened: ", serializer.errors)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #22
0
 def connect(self, *args, **kwargs):
     django_statsd.start('url.%s' % self._get_host_name())
     return origHTTPConnection.connect(self, *args, **kwargs)
Example #23
0
 def connect(self, *args, **kwargs):
     django_statsd.start("url.%s" % self._get_host_name())
     return origHTTPConnection.connect(self, *args, **kwargs)
Example #24
0
def api_upload_file_view(request, uuid_bill_id):
    request_file_name = request.data['url'].name
    request_file_md5 = calculate_md5(request.data['url'])
    request_file_size = request.data['url'].size

    try:
        bill_obj = Bill.objects.get(uuid_bill_id=uuid_bill_id)
    except Bill.DoesNotExist:
        logger.error("Bill Doesn't Exist")
        return Response({'response': "Bill doesn't exist."},
                        status=status.HTTP_404_NOT_FOUND)

    if bill_obj.owner_id != request.user:
        logger.error("User Doesn't have permissions")
        return Response(
            {
                'response':
                "You don't have permissions to get/update/delete that bill."
            },
            status=status.HTTP_404_NOT_FOUND)

    if bill_obj.attachment is not None:
        logger.error("Bill already has an attachment")
        return Response({'response': "Bill already has an attachment."},
                        status=status.HTTP_400_BAD_REQUEST)

    if not request_file_name.lower().endswith(
        ('.png', '.jpg', '.jpeg', '.pdf')):
        logger.error("Bill has to be pdf, png, jpg or jpeg")
        return Response(
            {'response': "Bill already has to be pdf, png, jpg or jpeg."},
            status=status.HTTP_400_BAD_REQUEST)

    if request.method == 'POST':
        django_statsd.incr('api.createFile')
        django_statsd.start('api.createFile.time.taken')
        serializer = FilePostSerializer(data=request.data)
        data = {}
        if serializer.is_valid():
            django_statsd.start('api.createFile.DB')
            file = serializer.save()
            file.file_name = request_file_name
            file.file_size = request_file_size
            file.md5_sum = request_file_md5
            file.save()
            bill_obj.attachment = file
            bill_obj.save()
            django_statsd.stop('api.createFile.DB')

            data['response'] = 'successfully added a new file.'
            data['file_name'] = file.file_name
            data['id'] = file.uuid_file_id

            if 'S3_BUCKET_NAME' in os.environ:
                data['url'] = str(file.url.url.split('?')[0])
            else:
                data['url'] = str(file.url)
            data['upload_date'] = file.upload_date
            logger.info("POST: Upload File")
            django_statsd.stop('api.createFile.time.taken')
            return Response(data, status=status.HTTP_201_CREATED)

        logger.error("ERROR: Something Happened: %s", serializer.errors)
        django_statsd.stop('api.createFile.time.taken')
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)