Example #1
0
def modify_task(event, context):
    logging.info('event: {}'.format(event))

    try:
        body = get_body(event)
    except json.JSONDecodeError:
        return {
            'statusCode': 400,
            'body': json.dumps({'error': 'Bad parameter(s) in request'})
        }

    try:
        repo = TaskRepository()
        task = repo.get_task_by_task_id(body['task_id'])

        if task is None:
            return {
                'statusCode': 400,
                'body': json.dumps({'error': 'Entry not found'})
            }

        for key, value in body:
            setattr(task, key, value)

        repo.update_task(task)
        return {'statusCode': 200, 'body': json.dumps(task.__dict__)}
    except Exception as e:
        logging.error(e)
        return {
            'statusCode': 500,
            'body': json.dumps({'error': 'Internal Error: {}'.format(e)})
        }
Example #2
0
def delete_by_id(event, context):
    """
    Delete task by id
    """
    logging.info('event: {}'.format(event))

    params = get_path_parameters(event)

    try:
        repo = TaskRepository()
        task = repo.get_task_by_task_id(params['id'])
        if task is None:
            return {
                'statusCode': 400,
                'body': json.dumps({'error': 'Entry not found'})
            }

        repo.delete_task_by_task_id(task.task_id)
        return {'statusCode': 204}
    except Exception as e:
        logging.error(e)
        return {
            'statusCode': 500,
            'body': json.dumps({'error': 'Internal Error: {}'.format(e)})
        }
Example #3
0
def add_task(event, context):
    logging.info('event: {}'.format(event))

    try:
        body = get_body(event)
    except json.JSONDecodeError:
        return {
            'statusCode': 400,
            'body': json.dumps({'error': 'Bad parameter(s) in request'})
        }

    try:
        task = TaskModel(scheduled=body['scheduled'],
                         task_type=body['task_type'],
                         invoke_method=body['invoke_method'],
                         call_arn_url=body['call_arn_url'],
                         parameters=body['parameters'],
                         data=body['data'])

        repo = TaskRepository()
        repo.add_task(task)

        return {'statusCode': 200, 'body': json.dumps(task.__dict__)}
    except Exception as e:
        logging.error(e)
        return {
            'statusCode': 500,
            'body': json.dumps({'error': 'Internal Error: {}'.format(e)})
        }
def handler(event, context):
    logging.info('event: {}'.format(event))

    repo = TaskRepository()
    pending_tasks = repo.get_pending_tasks()

    for task in pending_tasks:
        if task.invoke_method == 'REST':
            logging.info("Invoke REST API: {}".format(task.call_arn_url))
            requests.post(task.call_arn_url,
                          data=json.loads(task.data),
                          headers={'Content-type': 'application/json'})
            task.invoked = True

        elif task.invoke_method == 'SNS':
            logging.info("Publish SNS notification: {}".format(
                task.call_arn_url))
            sns = boto3.client('sns', region_name=os.environ['REGION'])
            try:
                sns.publish(TopicArn=task.call_arn_url,
                            Message=task.parameters)
            except ClientError:
                logging.error('Invalid ARN: {}'.format(task.call_arn_url))
            task.invoked = True

        else:
            logging.error('Unknown Task: {}'.format(task.task_id))
            task.active = False

        repo.update_task(task)
Example #5
0
def get_tasks(event, context):
    logging.info('event: {}'.format(event))
    params = get_query_parameters(event)

    try:
        repo = TaskRepository()

        if params is None:
            tasks = repo.get_all_tasks()
        elif 'type' in params:
            tasks = repo.get_tasks_by_task_type(params['type'])
        elif 'from' in params and 'to' in params:
            tasks = repo.get_tasks_by_created(params['from'], params['to'])
        else:
            return {
                'statusCode': 400,
                'body':
                json.dumps({'error': 'Bad parameter(s) in query string'})
            }

        items = []
        for task in tasks:
            items.append(task.__dict__)

        return {'statusCode': 200, 'body': json.dumps(items)}
    except Exception as e:
        logging.error(e)
        return {
            'statusCode': 500,
            'body': json.dumps({'error': 'Internal Error: {}'.format(e)})
        }
Example #6
0
    def tearDown(self):
        repo = TaskRepository()
        sql = 'DROP DATABASE {}'.format(os.environ['AURORA_DB_NAME'])
        repo._execute(sql)

        del os.environ['REGION']
        del os.environ['AURORA_DB_HOST']
        del os.environ['AURORA_DB_PORT']
        del os.environ['AURORA_DB_NAME']
        del os.environ['AURORA_DB_USER']
        del os.environ['AURORA_DB_PASSWORD']
Example #7
0
 def update_task(self, task_id=None):
     task = self.request.get("task")
     task_goal = self.request.get("task_goal")
     user = self.request.get("user")
     completed = False
     form_date = self.request.get("task_due_date").split('-')
     task_due_date = date(int(form_date[0]), int(form_date[1]),
                          int(form_date[2]))
     changes = Task(completed=completed,
                    user_first_name=user,
                    task=task,
                    task_goal=task_goal,
                    task_due_date=task_due_date)
     picked_task = TaskRepository.read(task_id)
     updated_task = TaskRepository.update(picked_task, changes)
     return self.redirect_to('task-list')
Example #8
0
    def test_task_manager_delete_task(self):
        task_id = uuid.uuid4()
        scheduled = datetime.datetime.utcnow()
        new_task = TaskModel(task_id, scheduled)

        repo = TaskRepository()
        created_task = repo.add_task(new_task)

        message = {'method': 'DELETE', 'body': {'id': created_task.task_id}}
        event = {'Records': [{'Sns': {'Message': json.dumps(message)}}]}

        passed = True
        try:
            task_manager(event, {})
        except:
            passed = False

        self.assertTrue(passed, 'Delete task through SNS failed.')
Example #9
0
    def test_task_manager_update_task(self):
        task_id = uuid.uuid4()
        scheduled = datetime.datetime.utcnow()
        new_task = TaskModel(task_id, scheduled)
        repo = TaskRepository()
        created_task = repo.add_task(new_task)

        created_task.call_arn_url = 'https://google.com'
        message = {'method': 'UPDATE', 'body': created_task.__dict__}
        event = {'Records': [{'Sns': {'Message': json.dumps(message)}}]}

        passed = True
        try:
            task_manager(event, {})
        except:
            passed = False

        self.assertTrue(passed, 'Update task through SNS failed.')
    def test_sns_task_executer(self):
        task_id = uuid.uuid4()
        task = TaskModel(
            task_id,
            scheduled=datetime.datetime.now(),
            task_type='send_gmail',
            invoke_method='SNS',
            call_arn_url='arn:aws:sns:us-east-1:00000000:test',
            data={},
        )
        repo = TaskRepository()
        repo.add_task(task)

        passed = True
        try:
            task_executer(event={}, context={})
        except:
            passed = False

        self.assertTrue(passed, 'Execute SNS task with CloudWatch failed.')
    def test_rest_task_executer(self):
        task_id = uuid.uuid4()
        task = TaskModel(
            task_id,
            scheduled=datetime.datetime.now(),
            task_type='send_gmail',
            invoke_method='REST',
            call_arn_url='https://serverless.com',
            data={},
        )
        repo = TaskRepository()
        repo.add_task(task)

        passed = True
        try:
            task_executer(event={}, context={})
        except:
            passed = False

        self.assertTrue(passed, 'Execute REST task with CloudWatch failed.')
Example #12
0
    def setUp(self):
        config_filepath = os.path.join(self.ROOT_PATH, 'config.test.json')

        with open(config_filepath, 'r') as fp:
            config = json.load(fp)

        os.environ['REGION'] = config['REGION']
        os.environ['AURORA_DB_HOST'] = config['AURORA_DB_HOST']
        os.environ['AURORA_DB_PORT'] = config['AURORA_DB_PORT']
        os.environ['AURORA_DB_NAME'] = config['AURORA_DB_NAME']
        os.environ['AURORA_DB_USER'] = config['AURORA_DB_USER']
        os.environ['AURORA_DB_PASSWORD'] = config['AURORA_DB_PASSWORD']
        repo = TaskRepository()
Example #13
0
def handler(event, context):
    logging.info('event: {}'.format(event))

    message = json.loads(event['Records'][0]['Sns']['Message'])
    method = message['method']
    body = message['body']

    repo = TaskRepository()
    if message['method'] == 'ADD':
        task = TaskModel(
            task_id=uuid.uuid4(),
            scheduled=datetime.datetime.strptime(body['scheduled'], '%Y-%m-%d %H:%M:%S'),
            task_type=body['task_type'],
            invoke_method=body['invoke_method'],
            call_arn_url=body['call_arn_url'],
            parameters=body['parameters'],
            data=body['data'])
        repo.add_task(task)

    elif method == 'UPDATE':
        task = repo.get_task_by_task_id(body['task_id'])

        if task is not None:
            for key, value in body.items():
                setattr(task, key, value)
            repo.update_task(task)
        else:
            logging.error('Entry not found')

    elif method == 'DELETE':
        task = repo.get_task_by_task_id(body['id'])
        if task is not None:
            repo.delete_task_by_task_id(task.task_id)
        else:
            logging.error('Entry not found')

    else:
        logging.error('Unknown method')
Example #14
0
 def create_post(self):
     task = self.request.get("task")
     task_goal = self.request.get("task_goal")
     user = self.request.get("user")
     completed = False
     form_date = self.request.get("task_due_date").split('-')
     task_due_date = date(int(form_date[0]), int(form_date[1]),
                          int(form_date[2]))
     new_task = TaskRepository.create(completed=completed,
                                      user_first_name=user,
                                      task=task,
                                      task_goal=task_goal,
                                      task_due_date=task_due_date)
     # adding lag for local development
     time.sleep(1)
     return self.redirect_to('task-list')
Example #15
0
 def get_update_task(self, task_id=None):
     existing_tasks = TaskRepository.read(task_id)
     return self.render_template("/task/task_edit.html",
                                 params={"task": existing_tasks})
Example #16
0
 def get(self):
     existing_tasks = TaskRepository.readAll()
     return self.render_template("/task/task_list.html",
                                 params={"taskList": existing_tasks})