def handle_worker(message): data = json.loads(message.get('data', '{}')) if data.get('direction') != __name__: return action = data.get('action') result = {} if action == ACTION_REGISTER: try: worker = Worker(name=data['name'], pin=data['pin']) except WorkerExists: result = errors.get(errors.WORKER_EXISTS) else: worker.release() workers.append(worker) result = { 'action': action, 'name': data['name'], 'worker_id': worker._id, 'direction': 'workers' } print '{} joined'.format(data['name']) elif action == ACTION_UNREGISTER: try: worker = Worker(data['worker_id'], pin=data['pin']) except WorkerNotFound: result = errors.get(errors.WORKER_NOT_FOUND) else: worker.unregister() result = { 'action': action, 'worker_id': worker._id, 'direction': 'workers' } for w in filter(lambda x: x.name == worker.name, workers): workers.remove(w) print '{} left'.format(worker.name) if result: config.get('storage').publish(Worker.CHANNEL, json.dumps(result))
def post(self): """Authenticate and get token""" username = self.get_argument('username') password = self.get_argument('password') try: user = User.logon(username, password) except UserNotFound: data = errors.get(errors.INVALID_LOGIN) else: token = utils.get_token() session = { 'username': username, 'token': token } db.sessions.insert(session) data = { 'username': username, 'is_staff': user.is_staff, 'token': token } self.finish(data)
def wrapper(handler): user = _get_auth_user(handler.request.headers.get('Authorization')) if user is not None: handler.user = user return f(handler) else: handler.finish(errors.get(errors.LOGIN_REQUIRED))
def post(self): """Create user""" username = self.get_argument('username').strip() password = self.get_argument('password').strip() is_staff = True if self.get_argument('is_staff') == '1' else False try: User.create(username, password, is_staff) except UsernameExists: data = errors.get(errors.USERNAME_EXISTS) except UnicodeEncodeError: data = errors.get(errors.BAD_PASSWORD) else: data = { 'status': 'ok' } self.finish(data)
def handle_task(message): data = json.loads(message.get('data', '{}')) action = data.get('action') if action == ACTION_RESULT: try: worker = Worker(data['worker_id'], pin=data['pin']) except WorkerNotFound: result = errors.get(errors.WORKER_NOT_FOUND) else: worker.end_task(data['result'])
def post(self): """Register task""" body = json.loads(self.request.body) if body.get('data') is not None: priority = body.get('priority', Task.PRIORITY_NORMAL) if priority in Task.PRIORITIES: task = Task.create(data=body['data'], priority=priority) data = { 'status': 'ok', 'task_id': task._id } else: data = errors.get(errors.INCORRECT_PRIORITY) else: data = errors.get(errors.TASK_NO_DATA) self.finish(data)
def get(self, task_id): """Task result""" try: task = Task(task_id) except TaskNotFound: data = errors.get(TASK_NOT_FOUND) else: data = { 'status': 'ok', 'result': task.result } self.finish(data)