def post(self, name): data = Task.parse.parse_args() project = ProjectModel.query.filter_by(uuid=data['uuid']).first() if project: if project.created_by_id == get_jwt_identity(): # owner if TaskModel.find_by_name(name): return { "TaskAlreadyExistsError": { "message": "Task with given name alredy exists.", "status": 401 } } task = TaskModel(name, data['task_desc'], data["uuid"]) task.save_to_db() project = ProjectModel.find_by_id(data['uuid']) project.task_id = task project.save_to_db() return {"Message": "Task Added...", "status": 200} else: return { "UnauthorizedError": { "message": "Project Owner can only create task.", "status": 401 } } return { "ProjectNotExistsError": { "message": "Project with given id doesn't exists", "status": 400 } }
def post(self): parser = reqparse.RequestParser() parser.add_argument('description', type=str, required=True, help="Field description cannot be empty") parser.add_argument( 'start_date', type=lambda x: dt.datetime.strptime(x, "%Y-%m-%d %H:%M:%S"), required=True, help="Field due_date cannot be empty") parser.add_argument( 'end_date', type=lambda x: dt.datetime.strptime(x, "%Y-%m-%d %H:%M:%S"), required=True, help="Field due_date cannot be empty") parser.add_argument('owner_id', type=int, required=True, help="Field owner_id cannot be empty") payload = parser.parse_args() task = TaskModel(payload['description'], payload['start_date'], payload['end_date'], False, payload['owner_id']) task.save() return { 'message': 'Task created without issues', 'record': task.json() }, 201
def post(self): data = Task.parser.parse_args() try: TaskModel.save_to_db(data) except: return {"Message": "An error occured while adding task to the db"} return {"Message": "Task sucessfully added"}
def _processTasks(self, hostsType, job): ''' ''' resultCode, resultMessage = True, "" for device in self._hosts: task = TaskModel(job.id, device.id, "NEW", {}) task.save_to_db(commit=False) return resultCode, resultMessage
def post(self): args = TaskAPI.parser.parse_args() task = TaskModel(**args) try: task.save_to_db() except: return {"message": "An error occurred creating the task."}, 500 return task.json(), 201
def get(self, id=None): queryData = request.args.to_dict() if id: task = TaskModel.findById(id) if task: return task.json(), 201 else: return {'message': 'task not found'}, 404 tasks = TaskModel.find(**queryData) return {'tasks': list(map(lambda x: x.json(), tasks))}, 200
def post(self): content = request.get_json() task = TaskModel(content["task"]) try: task.save_to_db() except: return {"message": "An error occurred inserting the item."}, 500 return task.json(), 201
def post(self, name): if TaskModel.find_by_name(name) is not None: return {'message': f"Task named {name} already existe."} data = Task.parser.parse_args() task = {'name': name, 'text': data['text']} TaskModel.insrt(task) return task, 201
def _processTasks(self, job_id, hosts): ''' ''' resultCode, resultMessage = True, "" for deviceName in hosts: device = DeviceModel.find_by_name(deviceName) task = TaskModel(job_id, device.id) task.save_to_db(commit=True) return resultCode, resultMessage
def get(cls, task_id: str = None): if task_id: task = TaskModel.find_by_id(task_id) if not task: return {"message": "Task not found"}, 404 return task_schema.dump(task), 200 tasks = TaskModel.fetch_all() return task_list_schema.dump(tasks), 200
def get(self, id=None): queryData = request.args.to_dict() if id: result = TaskModel.findByJob_Id(id) if result: return {'result': result.json()} else: return {'message': 'job not found'}, 404 results = TaskModel.find(**queryData) return {'result': list(map(lambda x: x.json(), results))}
def fetch_job(self): ''' 获取超过当前时间戳的需要触发的一批任务 :return: ''' tasks = TaskModel.query_task_to_trigger() if tasks: TaskModel.execute( 'update task set exec_status = 1 where trigger_time<{} and exec_status = 0' .format(int(time.time()))) return tasks
def _processTasks(self, hostsType): ''' ''' resultCode, resultMessage = True, "" if self.job.agent_type == "configuration_sender" and hostsType == "hostsConfiguration": self.buildCommand() else: for device in self._hosts: task = TaskModel(self.job.id, device.id, "NEW", {}) task.save_to_db(commit=False) return resultCode, resultMessage
def post(self, name=None): data = json.loads(request.data) compliance_execution = ComplianceExecutionModel( data.get("compliance_id")) compliance_element_list = ComplianceElementModel.find( **{"compliance_id": data.get("compliance_id")}) compliance = ComplianceReportModel.find_by_id( data.get("compliance_id")) try: compliance_execution.save_to_db() except: return { "error": "An error occurred creating the compliance_execution." }, 500 for element in compliance_element_list: for job in element.job_templates: job_dict = job.json() del job_dict["id"] cipher_suite = Fernet(KEY) job = JobModel(**job_dict) job.compliance_execution_id = compliance_execution.id job.login = compliance.login job.password = compliance.password job.use_enable_password = compliance.use_enable_password job.enable_password = compliance.enable_password job.is_validated = compliance.is_validated job.use_device_credentials = compliance.use_device_credentials job.device_count = len(compliance.host_list) job.save_to_db() print(data.get("compliance_id")) print(compliance.host_list) resultCode, resultMessage = self._processHosts( compliance.hostsType, compliance.host_list) if not resultCode: return { "error": "An error occurred inserting the job. " + resultMessage }, 500 resultCode, resultMessage = self._processTasks( compliance.host_list, job) if not resultCode: return { "error": "An error occurred inserting the job. " + resultMessage }, 500 TaskModel.commit() JobModel.commit() job.sendJob(job.id) print('job sent') print(job.id) return compliance_execution.json(), 201
def post(self): data = Task.parser.parse_args() if 'name' not in data or 'description' not in data or 'deadline' not in data: return {'message': 'invalid json sent in body'}, 400 task = TaskModel(data['name'], data['description'], data['deadline'], current_identity.first().id) try: task.save_to_db() except: return {'message': 'error occurred while inserting task'}, 500 return task.json(), 201
def post(self): """create task""" data = Task.parser.parse_args() if data['description'] not in {"", None}: task = TaskModel(data['description']) else: return {"message": "A task must have a description."} try: task.save_to_db() except: return {'message': "An error occurred inserting the bill."}, 500 return task.json(), 201
def get(cls, last_fetch=None): user = get_jwt_identity() if user: return { "tasks": [task.json() for task in TaskModel.find_all_existing()] } last_fetch = last_fetch if last_fetch is not None else cls.parser.parse_args( )["last_fetch"] if DEBUG: return { "new": [task.json() for task in TaskModel.find_new(last_fetch)], "deleted": [task.json() for task in TaskModel.find_deleted(last_fetch)], "updated": [task.json() for task in TaskModel.find_updated(last_fetch)], "all": [task.json() for task in TaskModel.find_all()] } return { "new": [task.json() for task in TaskModel.find_new(last_fetch)], "deleted": [task.json() for task in TaskModel.find_deleted(last_fetch)], "updated": [task.json() for task in TaskModel.find_updated(last_fetch)] }
def post(cls): data = parser.parse_args() try: task = TaskModel(**data) task.save_to_db() except IntegrityError as e: return {"database_exception": str(e)}, 400 except Exception as e: return { "message": "Internal error occurred during insertion." }, 500 return task.json(), 201
def buildCommand(self): for deviceName in self.job.parameters["hostsConfiguration"]: device = DeviceModel.find_by_name(deviceName) if not device: device = DeviceModel(deviceName, deviceClass=1) try: device.save_to_db(commit=False) except: resultCode, resultMessage = False, "An error occurred inserting the device." command = Environment().from_string( self.job.parameters["remoteCommand"]).render( self.job.parameters["hostsConfiguration"][deviceName]) task = TaskModel(self.job.id, device.id) task.parameters["command"] = command task.save_to_db(commit=False) return command
def patch(cls, task_id: int): json = request.get_json() # Check if the task exists task = TaskModel.find_by_id(task_id) if not task: return generate_message_json(HttpStatusCode.NOT_FOUND.value, TASK_NOT_FOUND) # Check if client is trying to edit readonly fields readonly = {"id", "category_id"} keys = json.keys() forbidden = readonly & keys if forbidden: return generate_message_json( HttpStatusCode.BAD_REQUEST.value, FIELD_CANNOT_BE_EDITED.format(str(forbidden)[1:-1]), ) # Check if the client specified non existing attrs try: check_attr(json.keys(), task) for key, value in json.items(): setattr(task, key, value) task.save_to_db() # Persist chages to db return task_schema.dump(task), HttpStatusCode.OK.value except AttributeError as ae: return generate_message_json(HttpStatusCode.BAD_REQUEST.value, str(ae)) except SQLAlchemyError as se: return generate_message_json(HttpStatusCode.BAD_REQUEST.value, str(se))
def get(cls, task_id: int): task = TaskModel.find_by_id(task_id) if task: return task_schema.dump(task), HttpStatusCode.OK.value return generate_message_json(HttpStatusCode.NOT_FOUND.value, TASK_NOT_FOUND)
def put(self, task_id): """update fields: -is_done -assignee_id --- currently logged in user""" data = Task.updating_parser.parse_args() task = TaskModel.find_by_id(task_id) if task is None: return {'message': "Task with id {} doesn't exist".format(task_id)} elif task.assignee_id is None: user = UserModel.find_by_id(current_identity.id) # assigning currently logged user to task task.assignee_id = user.id task.assignee_name = user.username elif data['is_done'] is not None: user = UserModel.find_by_id(current_identity.id) if task.assignee_id == user.id: # updating is_done field task.is_done = data['is_done'] else: return {'message': 'You are not assigned to this task'}, 400 else: return {'message': 'You are not assigned to this task'}, 400 try: task.save_to_db() except: return {'message': "An error occurred inserting the task."}, 500 return task.json(), 201
def delete(self, id): task = TaskModel.find_by_id(id) if task: task.delete_from_db() return {'message': 'Task deleted'}
def delete(self, name): task = TaskModel.find_by_name(name) if task is None: return {'message': 'Task not found!'}, 404 else: task.delete_from_db() return {'message': 'Task deleted.'}
def put(self, _id, owner): parser = reqparse.RequestParser() parser.add_argument('description', type=str, required=False) parser.add_argument( 'start_date', type=lambda x: dt.datetime.strptime(x, "%Y-%m-%d %H:%M:%S"), required=False) parser.add_argument( 'end_date', type=lambda x: dt.datetime.strptime(x, "%Y-%m-%d %H:%M:%S"), required=False) parser.add_argument('completed', type=bool, required=False) task = TaskModel.find_by_id(_id, owner) if task: payload = parser.parse_args() if payload['description']: task.description = payload['description'] if payload['start_date']: task.start_date = payload['start_date'] if payload['end_date']: task.end_date = payload['end_date'] if payload['completed'] is not None: task.completed = payload['completed'] task.save() return { 'message': f'Task {_id} changed.', 'record': task.json() }, 201 else: return {'message': f'Task {_id} not found - owner : {owner}'}, 404
def get(self, _id, owner): task = TaskModel.find_by_id(_id, owner) if task: return task.json() else: return {'message': f'Task {_id} not found - owner : {owner}'}, 404
def get(self, _id): task = TaskModel.find_by_id(_id, current_identity.id) if task and current_identity.id != task.user_id: return {"message": "Not authorized to view this content"}, 401 if task: return task.json() return {"message": "Task not found."}, 404
def get(self): return { 'tasks': [ task.json() for task in TaskModel.find_by_user_id( current_identity.first().id).all() ] }
def delete(self, _id): task = TaskModel.find_by_id(_id) if task: task.delete_from_db() return {'message': 'Task deleted'} return {'message': "There is no task with id '{}'".format(_id)}, 400
def get(cls, task_id:int): task = TaskModel.find_by_id(task_id) if not task: return {"message": f"Task with taskID {task_id} is not found"}, 404 return task_schema.dump(task), 200
#-*- coding:utf-8 -*- from models.task import TaskModel from models.idea import IdeaModel task_pool = TaskModel("memento.db") task_pool.create_table() idea_pool = IdeaModel("memento.db") idea_pool.create_table()