def create_task(project_key): form = TaskForm(request.form) project = Project.get_project(project_key) if project is None: abort(404) current_user_id = get_user(request, project_key) if current_user_id is None: return redirect(url_for('who_are_you', project_key=project_key)) choices = [(p.id, p.name) for p in project.people] form.assigned_to.choices = choices if request.method == 'POST' and form.validate(): title = form.title.data description = form.description.data priority = form.priority.data assigned_to = form.assigned_to.data Task.new(project.key, title, priority, current_user_id, assigned_to, description) flash("Your task was created") project.touch() return redirect('/project/' + project_key) else: assigned_to = current_user_id form.assigned_to.default = current_user_id form.process() return render_template('edit_task.html', form=form, project=project, assigned_to=assigned_to)
def execute(self): t = Task(self.name) if self.should_be_active: t.activate() session.add(t) session.commit() print "Added task %d." % t.id
def test_task_process_rule(capsys): task = Task('./tests/music', '.*\.mp3') rule = Rule(Artist='Metallica') task.add_rule(rule) task.process_rules() out, err = capsys.readouterr() assert out == 'Update some.mp3. Set Artist to Metallica\n'
def make_task(script): parsed_script = script_parser.parseString(open(script).read()) data = parsed_script and parsed_script[0] or {} task = Task(root_dir=data['root_dir'], file_mask=data.get('mask')) for rule in data['rules']: task.add_rule(Rule(**rule)) return task
def save_task(): new_task = Task(request.form['title']) #string from dict notes = request.form['notes'] #string from dict new_task.notes = notes #object new_task with attribute notes model.add(new_task) model.save_all() # return "Saved, theoretically" return redirect(url_for("home"))
def addTask(phone, url, periods, sendDateTimeList, smsType, smsSender): task = Task(phone=phone, url=url, periods=map( int, periods.split(';')), sendDateTimeList=[datetime.strptime(dateString.strip(), settings.TIMEFORMAT) for dateString in sendDateTimeList.split(';') if dateString.strip()], smsType=smsType.strip(), smsSender=smsSender.strip()) task.put()
def log_tasks(user, subject, body): details = {'user': user} date = parse_date(subject) if date: details['date'] = date - timedelta(hours=user.timezone) for task in parse_body(body): details['description'] = task Task.create(**details)
def post(self): task = Task(name=self.request.get('name'), done=self.request.get('done'), progress=int(self.request.get('progress')), questKey=ndb.Key(Quest, int(self.request.get('questId')))) task.put() task = task.to_dct() self.response.write(task['id'])
def create_task(name , script_group_id , server_group_id) : try : session = Session() new_task = Task(script_group_id , server_group_id , name) task_id = new_task.save_return_id() if task_id <= 0 : return {"status":-1 , "val":None } return {"status":0 , "val":task_id} except Exception ,msginfo : return {"status":-1 , "val":msginfo}
def post(self): name = self.request.get("name") url = self.request.get("url") if (not name or not url): self.response.out.write("name and url required") return # name and url ok new_task = Task(name = name, url = url.strip()) new_task.put() #self.response.out.write('<p>Task added OK</p><p><a href="/">back</a></p>') self.redirect("/list")
def create_task(): print 'Creating a new task:' sparql_endpoint = raw_input('Source SPARQL endpoint: ') graph = raw_input('Named graph from Virtuoso in which data is going to be stored: ') task = Task() task.endpoint = sparql_endpoint task.graph = graph task.offset = 0 task.start_time = datetime.now() session.add(task) session.commit() print 'Launching task...' launch_task.delay(task.id)
def test_delete_item(self): j = JSon(config.backend_json['filename']) t = Task('new task') t.id = 3 t.category_id=1 key = 'Task.3' j.delete_item(t) j.commit() self.assertNotIn(key, j.data.keys())
def test_encoder(self): p = Project('test') p.id = 1 c = Category('test') c.id = 2 c.project_id = p.id t = Task('test') t.id = 3 t.category_id = c.id self.assertIsNotNone(json.dumps(p, cls=ModelEncoder)) self.assertIsNotNone(json.dumps(c, cls=ModelEncoder)) self.assertIsNotNone(json.dumps(t, cls=ModelEncoder))
def p_task(self, p): '''task : with in rule_list | in rule_list''' if len(p) == 4: _, file_mask, root_dir, rules = p else: _, root_dir, rules = p file_mask = None task = Task(root_dir, file_mask) for rule in rules: task.add_rule(rule) p[0] = task
def incomplete_tasks(): if 'username' not in session: return redirect(url_for('login')) else: if request.method == 'POST': try: user = User.get(User.name == session['username'][0]) except model.DoesNotExist: user = None Task.update(performed=datetime.now(), performed_by=user).where( Task.id == request.form['task_id']).execute() return render_template('incomplete.jinja2', tasks=Task.select().where( Task.performed.is_null()))
def get(self): from google.appengine.api import taskqueue tasks = Task.all().fetch(1000) for task in tasks: if task.enabled: taskqueue.add(url='/work', method="GET", params={"key": task.key()}) self.response.out.write('Queued all tasks complete.')
def add_task(): try: current_user = get_jwt_identity() print(current_user) user = User.find_by_email(current_user) # print(user.user_id) # user = User.query.filter_by(email=current_user).all() user_id = user.user_id task_name = request.form['task'] task_description = request.form['description'] print(task_name, task_description) new_task = Task(user_id=user_id, task_name=task_name, task_description=task_description, created_on=datetime.now(), complete_by=datetime.now()) db.session.add(new_task) db.session.commit() # tasks = Task.query.filter_by(user_id = user_id).all() return redirect("/tasks") except: return {'message': 'Something went wrong'}, 500
def get_all_direct_subtasks(domain_identifier, root_task=None, limit=100, user_identifier=None): """ Returns all direct subtasks of a |root_task| in the given domain. If no |root_task| is specified, then all root tasks of the domain will be returned. This function returns at most |limit| tasks. Args: domain_identifier: The domain identifier string root_task: An instance of the Task model limit: The maximum number of tasks that will be returned user_identifier: Optional user identifier. If provided, the tasks will be sorted on their active state for that user. Returns: A list of at most |limit| task instances of the domain, who are all direct descendants of |root_task|, or are all root task if no specific |root_task| is specified. The tasks are ordered on completion state, and if a |user_identifier| is provided, also on active state. """ query = Task.all().\ ancestor(Domain.key_from_name(domain_identifier)).\ filter('parent_task = ', root_task) tasks = query.fetch(limit) _sort_tasks(tasks, user_identifier=user_identifier) return tasks
def get(self, *args, **kwargs): """ order: p, s, t default desc p_, s_, t_ - asc """ # get args status = self.get_args('s') or self.get_cookie('status', 'unsolved') order = self.get_args('o') or self.get_cookie('order', 'p') # _o - desc, o_ - asc page = self.get_args('p', 1) # 记录状态 self.set_cookie('status', status) self.set_cookie('order', order) self.set_cookie('cur_auth', str(self.auth.id)) # set order_by if order not in self._order.keys(): order = 'p' order_by = self._order.get(order) page = int(page) pros = Auth.find_user_projects(uid=self.user.id) where = dict( uid=self.user.id, pid=self.pid, status=status ) if status != 'assigned': tasks, num = Task.find_project_tasks( page=page, order_by=order_by, get_num=True, **where) paginator = Paginator(page, num, Task._per_page) else: tasks = Task.assigned_tasks( user_id=self.user.id, order_by=order_by, pid=self.pid, ) paginator = None unread_num = Message.unread_num(user_id=self.user.id) return self.render( 'task-home.html', cur_pro=self.auth, pros=pros, tasks=tasks, status=status, order=order, page=page, paginator=paginator, unread_num=unread_num)
def txn(): task = api.get_task(domain_identifier, task_identifier) if not task: logging.error("Task '%s/%s' does not exist", domain_identifier, task_identifier) return index = TaskIndex.get_by_key_name(task_identifier, parent=task) if not index: index = TaskIndex(parent=task, key_name=task_identifier) # Get all subtasks. The ancestor queries are strongly # consistent, so when propagating upwards through the # hierarchy the changes are reflected. subtasks = list(Task.all().ancestor(domain_key).filter("parent_task =", task.key())) if not subtasks: # atomic task task.derived_completed = task.completed task.derived_size = 1 task.derived_atomic_task_count = 1 task.derived_has_open_tasks = task.open() assignee_identifier = task.assignee_identifier() if assignee_identifier: index.assignees = [assignee_identifier] if not DEV_SERVER: # Uses a multi entity group transaction to get the name # of the assignee. This is cached in the record for # quick descriptions. assignee = api.get_user(assignee_identifier) name = assignee.name if assignee else "<Missing>" else: name = "temp" task.derived_assignees[task.assignee_identifier()] = { "id": task.assignee_identifier(), "name": name, "completed": int(task.is_completed()), "all": 1, } else: # composite task task.derived_completed = all(t.is_completed() for t in subtasks) task.derived_size = 1 + sum(t.derived_size for t in subtasks) task.derived_atomic_task_count = sum(t.atomic_task_count() for t in subtasks) task.derived_has_open_tasks = any(t.has_open_tasks() for t in subtasks) # Compute derived assignees, and sum the total of all # their assigned and completed subtasks. assignees = {} for subtask in subtasks: subtask_assignees = subtask.derived_assignees for id, record in subtask_assignees.iteritems(): if not id in assignees: assignees[id] = {"id": id, "name": record["name"], "completed": 0, "all": 0} assignees[id]["completed"] += record["completed"] assignees[id]["all"] += record["all"] task.derived_assignees = assignees index.assignees = list(assignees.iterkeys()) task.put() index.completed = task.is_completed() index.has_open_tasks = task.has_open_tasks() index.atomic = task.atomic() index.put() # Propagate further upwards if task.parent_task_identifier(): UpdateTaskCompletion.enqueue(domain_identifier, task.parent_task_identifier(), transactional=True)
def get_task(domain, task): """Gets a task in a domain. Args: domain: The domain identifier task: The task key id or name. Can either be an int or a string. Returns: A task instance or None if no task exists. """ domain_key = Domain.key_from_name(domain) try: task_id = int(task) return Task.get_by_id(task_id, parent=domain_key) except ValueError: return Task.get_by_key_name(task, parent=domain_key)
def addRecord(**args): session = connectdb() cat = session.query(Catagory).filter_by(name=args['cat']) if cat.all(): catobj = cat.one() else: catobj = Catagory(args['cat']) taskobj = Task(args['task']) taskobj.cat = catobj # if True: # session.add(task) # date = args['date'].today() record = Record(args['date'], args['start_time'], args['big_or_not']) record.task = taskobj session.merge(record) # cat and task will save/update automatically and cascade due to the session's default setting? my_db_commit(session) session.close()
def get(self, *args, **kwargs): tid = kwargs.get('tid') mode = kwargs.get('mode') if not tid: raise HTTPError(404) p_users = Auth.find_project_users(pid=self.pid) self.p_users = [{'id': auth.user_id, 'name': auth.user_name} for auth in p_users] self.json_p_users = json.dumps(self.p_users) task = Task.get(id=tid) if not mode: # 任务详细信息 # get comment task_comments = Comment.find(task_id=task.id, order_by='created') # get change log task_logs = TaskLog.find(task_id=task.id, order_by='created desc') # focus focus = TaskFocus.check_focus(task_id=task.id, user_id=self.user.id) return self.render('task.html', task=task, auth=self.auth, logs=task_logs, comments=task_comments, focus=focus) if mode == 'solve': # 标记解决任务 if not task.is_done: task.status = Task._status_solved task.save() TaskLog.new( task_id=task.id, desc=json.dumps([]), note=u'标记为解决', updater_id=self.user.id, updater_name=self.user.name, ) return self.redirect('/%s/%s/%s' % (self.pid, 'task', task.id)) if mode == 'edit': # 编辑任务 # 用户列表去除已经分配的用户 users = [u for u in self.p_users if u['id'] not in task.assigned_ids] json_p_users = json.dumps(users) task_data = task.dictify() task_data['assigneds'] = json.dumps(task.assigned_users) return self.render( 'task-new.html', task=task_data, auth=self.auth, json_users=json_p_users, statuses=self.statuses, types=self.types, priorities=self.priorities, errors={}, update=True) if mode == 'focus': # 关注任务 TaskFocus.focus( task=task, user=self.user, pid=self.pid, pname=self.auth.project_name, ) return self.redirect('/%s/%s/%s' % (self.pid, 'task', task.id))
def txn(): query = Task.all().ancestor(Domain.key_from_name(domain)).\ filter('number_of_subtasks =', 0).\ filter('completed =', False).\ filter('assignee =', None).\ order('-time') return _group_tasks(query.fetch(50), complete_hierarchy=True, domain=domain)
def get(self): template_values = { 'tasks': Task.all(), 'urls': URL.all(), 'settings': settings, 'datetime_now': datetime.now(pytz.timezone(settings.TIMEZONE)).strftime(settings.TIMEFORMAT) } template = JINJA_ENVIRONMENT.get_template('templates/index.html') self.response.write(template.render(template_values))
def get(self): tasks = Task.all().fetch(1000) timedelta = datetime.timedelta(hours = 8) for task in tasks: task = mod_task(task) template_values = { "tasks": tasks, } self.response.out.write(template.render("template/list.tpl.html", template_values))
def txn(): # Actual test in the datastore to see if the task is atomic, # as it is a computed property. query = Task.all().\ ancestor(domain_key).\ filter('parent_task =', task_key) subtask = query.get() if not subtask: # atomic workers.UpdateTaskCompletion.enqueue(task.domain_identifier(), task.identifier())
def read_tasks(user): try: week = int(request.query.get("w", 0)) except: week = 0 current = datetime.now().replace(**ROUND_HOUR) - timedelta(week * ONE_WEEK) start = current - timedelta(current.weekday()) end = start + timedelta(ONE_WEEK) tasks = Task.select().where(Task.date > start, Task.date <= end) return template.render("read_tasks.tpl", tasks=tasks, start=start, week=week, user=user, link="/admin/tasks")
def _create_task(self): name = str(self.ui.textName.text()) description = str(self.ui.textDesc.text()) priority = int(str(self.ui.comboPrio.currentText())) #datetime qdate = self.ui.dateEdit.date() qtime = self.ui.timeEdit.time() end = time.mktime([qdate.year(), qdate.month(), qdate.day(), qtime.hour(), qtime.minute(), 0, 0, 0, 0]) tags = str(self.ui.textTags.text()).split(',') tags = [model.Tag(t) for t in tags] t = Task(name, description, end, priority, False, None, tags) if self.create: model.manager.create(t) else: t.identifier = self._identifier model.manager.modify(t) self._add_tags(tags) self._clear_components()
def txn(): super_task = None if parent_task: super_task = get_task(domain, parent_task) if not super_task: raise ValueError("Parent task does not exist") task = Task(parent=Domain.key_from_name(domain), description=description, user=user, context=user.default_context_key(), parent_task=super_task, level=super_task.level + 1 if super_task else 0) if super_task: super_task.number_of_subtasks = super_task.number_of_subtasks + 1 super_task.increment_incomplete_subtasks() super_task.put() if assignee: task.baked_assignee_description = assignee.name task.put() return task
def create_project_task(self, project, category, name): if project is None: print('Invalid project') return None cat = self.get_category(project, category) if cat is None: cat = self.create_project_category(project, category) if self.backend.item_exists(Task, {'name': name, 'category_id': cat.id}): print('Task already exists') return task = Task(name) task.category_id = cat.id self.backend.add_item(task) self.backend.commit() return task
def txn(): level = root_task.hierarchy_level() + 1 if root_task else 0 query = TaskIndex.all(keys_only=True).\ ancestor(Domain.key_from_name(domain_identifier)).\ filter('assignees =', user.identifier()).\ filter('level =', level) if root_task: query.filter('hierarchy =', root_task.identifier()) fetched = query.fetch(limit) tasks = Task.get([key.parent() for key in fetched]) return tasks
def get(self): for task in Task.all(): for sendDateTime in list(task.sendDateTimeList): try: if self.tz.localize(sendDateTime) < datetime.now(self.tz) and self._sendSMS(task): task.sendDateTimeList.remove(sendDateTime) except Exception, e: logging.error(e) if task.sendDateTimeList: task.put() else: task.delete()