Ejemplo n.º 1
0
def todolist():
    form = TaskForm()

    if form.validate_on_submit():
        # Get the data from the form, and add it to the database.
        new_task = Task()
        new_task.task_desc = form.task_desc.data
        new_task.task_status = form.task_status_completed.data

        db.session.add(new_task)
        db.session.commit()

        # Redirect to this handler - but without form submitted - gets a clear form.
        return redirect(url_for('main.todolist'))

    todo_list = db.session.query(Task).all()

    return render_template("main/todolist.html",
                           todo_list=todo_list,
                           form=form)
Ejemplo n.º 2
0
def index():
    # If viewing app as an anonymous user the user is shown default welcome page.
    if current_user.is_anonymous:
        return render_template('index.html', title='Home')

    form = TaskForm()
    # If TaskForm is submitted and validated a new task is added to user's to-do list.
    if form.validate_on_submit():
        task = Task(body=form.task.data, author=current_user)
        db.session.add(task)
        db.session.commit()
        flash(f'You added a to-do task, {current_user.username} ')
        ''' Redirect to index after POST request generated by a web form submission to avoid sumbitting duplicate posts. '''
        return redirect(url_for('index'))

    # Get user's sorting preference for their tasks to display in HTML template.
    user = User.query.filter_by(id=current_user.id).first()
    tasks = user.get_sorted_view_of_tasks()

    # Render personal index page.
    return render_template('index.html', title='Home', form=form, tasks=tasks)
Ejemplo n.º 3
0
def create_task():
    form = request.get_json()
    name = form.get('t_name', '')
    desc = form.get("t_desc", "")
    apis = form.get("t_apis", "")

    if not name or not apis:
        return jsonify({"code": 400, "msg": "参数错误"})

    # userId = get_jwt_identity()
    new_task = Task(t_name=name, t_desc=desc, t_apis=str(apis))

    try:
        new_task.create()
        return jsonify({"code": 201, "msg": "创建任务成功"})
    except Exception as e:
        db.session.rollback()
        print(e)
        return jsonify({"code": 400, "msg": str(e)})
    finally:
        db.session.close()
Ejemplo n.º 4
0
def send_email(subject, body, sender, recipients):

    task = Task(name=NameTask.sending_email.value)

    msg = Message(subject, sender=sender, recipients=recipients)
    msg.body = body

    # msg.html = html_body
    # if attachments:
    #     for attachment in attachments:
    #         msg.attach(*attachment)
    try:
        mail.send(msg)

        return "success"

    except Exception as e:

        logger_app.error("{}: {}".format(task.name, e))

        return "failure"
Ejemplo n.º 5
0
def pptmonitor_port():
    result = request.json
    time = parser.parse(result['time'])
    msg = result['msg']
    if msg == 'monitor':
        task = Task.query.get('pptmonitor_status_entry')
        if not task:
            return 'restart'
        dt = (datetime.now() - task.date)
        dt = dt.seconds // 60
        if dt > 30:  # if over 30minutes not hearing back, restart.
            return 'restart'
    else:
        task = Task.query.get('pptmonitor_status_entry') or Task(
            id='pptmonitor_status_entry')
        task.date = time
        task.name = msg
        db.session.add(task)
        db.session.commit()
    # return render_template('main/index.html', title='Home', follow_ppt=entries, greet=greet, linkentries=linkentries)
    return 'ok'
Ejemplo n.º 6
0
def new_task(category_id):
    if current_user.is_anonymous:
        return (redirect(url_for('cats.index')))
    form = NewTask()
    category = Category.query.get(category_id)
    nl = (('cancel', url_for('tsks.tasks', category_id=category_id)), )
    if form.validate_on_submit():
        task = Task(
            content=form.content.data,
            contributor_id=current_user.id,
            catid=category_id,
            timestamp=str(datetime.utcnow()),
        )
        insert_task(task)
        flash("Thanks for the new task!")
        return (redirect(url_for('tsks.tasks', category_id=category_id)))
    return render_template('new_task.html',
                           title='New Task',
                           form=form,
                           navbar_links=nl,
                           category=category)
Ejemplo n.º 7
0
def add_task():
    form = TaskForm(form_name='PickTask')
    form.client_id.choices = [(row.id, row.name) for row in Client.query.all()]
    form.project_id.choices = [(row.id, row.name)
                               for row in Project.query.all()]
    if request.method == 'GET':
        page = request.args.get('page', 1, type=int)
        pagination = current_user.my_tasks().order_by(
            Task.date.desc(), Task.task_ref.asc()).paginate(page, 4, False)
        tasks = pagination.items
        return render_template('tasks/add_task.html',
                               title='Add a task',
                               form=form,
                               tasks=tasks,
                               pagination=pagination)
    if current_user.can(Permission.WRITE) and form.validate_on_submit(
    ) and request.form['form_name'] == 'PickTask':
        task = Task(name=form.name.data,
                    client_id=form.client_id.data.id,
                    project_id=form.project_id.data.id,
                    user_task=current_user,
                    task_ref=form.task_ref.data,
                    duration=form.duration.data,
                    date=form.date.data,
                    rate=form.rate.data,
                    comment=form.comment.data,
                    currency_id=form.currency_id.data.id)
        db.session.add(task)
        db.session.commit()
        flash('Your task has been added!', 'success')
        return redirect(url_for('tasks.add_task'))
    page = request.args.get('page', 1, type=int)
    pagination = current_user.my_tasks().order_by(
        Task.date.desc(), Task.task_ref.asc()).paginate(page, 4, False)
    tasks = pagination.items
    return render_template('tasks/add_task.html',
                           title='Add a task',
                           form=form,
                           tasks=tasks,
                           pagination=pagination)
Ejemplo n.º 8
0
def add_task(request):
    if request.method == 'POST':
        form = AddTaskForm(request.POST)
        if form.is_valid():
            form.save(commit=False)
            name = form.cleaned_data.get('name')
            starttime = form.cleaned_data.get('starttime')
            location = form.cleaned_data.get('location')
            description = form.cleaned_data.get('description')
            reward = float(form.cleaned_data.get('reward'))
            owner = request.user
            task = Task(owner=owner,
                        name=name,
                        starttime=starttime,
                        location=location,
                        description=description,
                        reward=reward)
            task.save()
            return redirect('home')
    else:
        form = AddTaskForm()
    return render(request, "add_task.html", {'form': form})
Ejemplo n.º 9
0
def create_task(request):
    page_title = "Criar Tarefa"
    if request.method == "POST":
        task_form = TaskForm(request.POST)
        if task_form.is_valid():
            title = task_form.cleaned_data["title"]
            description = task_form.cleaned_data["description"]
            expiration_date = task_form.cleaned_data["expiration_date"]
            priority = task_form.cleaned_data["priority"]
            new_task = Task(title=title,
                            description=description,
                            expiration_date=expiration_date,
                            priority=priority,
                            user=request.user)
            task_service.create_task(new_task)
            return redirect('index_tasks')
    else:
        task_form = TaskForm()
    return render(request, 'tasks/task_form.html', {
        'task_form': task_form,
        'page_title': page_title
    })
Ejemplo n.º 10
0
def new_workout_post():
    pushups = request.form.get('pushups')
    comment = request.form.get('comment')
    title = request.form.get("title")
    pic = request.files['pic']
    if not pic:
        return 'No pic uploaded!', 400
    filename = secure_filename(pic.filename)
    mimetype = pic.mimetype
    if not filename or not mimetype:
        return 'Bad upload!', 400

   # img = Todo(img=pic.read(),title=title, name=filename, mimetype=mimetype)
    # new_todo = Todo(title=title, complete=False)

    task = Task(img=pic.read(),title=title, name=filename, mimetype=mimetype,pushups=pushups, comment=comment, author=current_user)
    db.session.add(task)
    db.session.commit()

    flash('Your task has been added!')

    return redirect(url_for('main.user_workouts'))
Ejemplo n.º 11
0
def add_task():
    json_data = request.get_json()

    title = json_data['title']
    description = json_data['description']
    priority = db.session.query(db.func.max(Task.priority)).scalar()
    print(priority)
    priority = 1 if priority == None else priority + 1
    end_date = json_data['end_date']
    complete = json_data['complete']

    task = Task(title=title,
                description=description,
                priority=priority,
                end_date=end_date,
                complete=complete)

    db.session.add(task)
    db.session.commit()

    return make_response(
        json.dumps({'message': 'Task created!'}, ensure_ascii=False), 200)
Ejemplo n.º 12
0
    def handle(self, *args, **options):
        now = date.today()
        default = now - relativedelta(years=5)

        try:
            given_date = datetime.strptime(options['date'], '%d/%m/%Y').date()
        except TypeError:
            given_date = default
            logger.warning(
                'No date was provided or it was provided but does not match the format (e.g. 19/05/2017)'
            )
            logger.warning('Default value of 5 years ago is chosen')

        try:
            today = date.today()

            command_name = "update_ted_5years"
            command = 'app.parsers.ted.process_daily_archive'

            while given_date < today:
                task_id = async_task(command, given_date)

                t = Task(
                    id=task_id,
                    args=command_name,
                    kwargs=f'given_date: {given_date}',
                    started=make_aware(datetime.now()),
                )
                t.save()

                given_date = given_date + timedelta(days=1)

        except Exception as e:
            logging.critical(e)

        return self.stdout.write(
            self.style.SUCCESS(
                f"Queued TED tenders updates (since {options['date'] or default})"
            ))
Ejemplo n.º 13
0
def index():
    articles = get_toi_feed()
    form = TaskForm()
    if form.validate_on_submit():
        task = Task(body=form.task.data, author=current_user)
        task.priority = dict1[form.priority.data]
        task.status = dict3[form.status.data]
        task.color = dict2[task.priority]
        db.session.add(task)
        db.session.commit()
        flash('Your task is now added!')
        return redirect(url_for('index'))
    page = request.args.get('page', 1, type=int)
    tasks = current_user.tasks.paginate(
        page, app.config['TASKS_PER_PAGE'], False)
    next_url = url_for('index', page=tasks.next_num) \
        if tasks.has_next else None
    prev_url = url_for('index', page=tasks.prev_num) \
        if tasks.has_prev else None
    return render_template('index.html', title='Home', articles=articles['NewsItem'],# form=form,
                           posts=tasks.items, next_url=next_url,
                           prev_url=prev_url)
Ejemplo n.º 14
0
def db_view():
    users = User.query.all()
    categories = Category.query.order_by('title')

    add_category_form = AddCategoryForm()
    add_task_form = AddTaskForm()
    add_task_form.category_id.choices = [(cat.id, cat.title) for cat in categories]

    if add_category_form.add_category_submit.data and add_category_form.validate_on_submit():
        category = Category(title=add_category_form.title.data,
                            description=add_category_form.description.data)
        db.session.add(category)
        db.session.commit()

        add_category_form = AddCategoryForm()
        add_task_form = AddTaskForm()
        categories = Category.query.order_by('title')
        add_task_form.category_id.choices = [(cat.id, cat.title) for cat in categories]
        return render_template('db_view.html', title='Database | gtRPG', users=users, categories=categories, add_category_form=add_category_form, add_task_form=add_task_form)
    elif add_task_form.add_task_submit.data and add_task_form.validate_on_submit():
        flash(f'form={add_task_form}')
        flash(f'{add_task_form.category_id.data}')

        category = Category.query.get(int(add_task_form.category_id.data))
        flash(f'{category}')

        task = Task(title=add_task_form.title.data,
                    description=add_task_form.description.data,
                    category=category)
        db.session.add(task)
        db.session.commit()

        add_category_form = AddCategoryForm()
        add_task_form = AddTaskForm()
        categories = Category.query.order_by('title')
        add_task_form.category_id.choices = [(cat.id, cat.title) for cat in categories]
        return render_template('db_view.html', title='Database | gtRPG', users=users, categories=categories, add_category_form=add_category_form, add_task_form=add_task_form)
    return render_template('db_view.html', title='Database | gtRPG', users=users, categories=categories, add_category_form=add_category_form, add_task_form=add_task_form)
Ejemplo n.º 15
0
def run(file):
    list = file.split('.')
    id = int(list[-1])
    #file_name = file.split('/')[-1]
    new_file = file[:-(len(list[-1]) + 1)]
    os.rename(file, new_file)
    pass
    #解析任务
    db.connect()
    try:
        task = Task.get(Task.finger == id)
    except:
        LOGR.debug('找不到对应任务:' + str(id))
        task = Task()
        task.finger = id
        task.name = ''
        task.dataType = '0'
        task.dir = ''
        task.username = ''
        task.password = ''
        task.target = ''
        task.port = ''
        task.tables = ''
        task.count = 0
        task.save()
        LOGR.info('发现新任务:' + str(id))
        exit(-1)
    #增加运行次数
    task.count = task.count + 1
    task.save()
    db.close()
    LOGR.info('开始任务:' + str(id) + ":" + task.name)
    result = putData(task, new_file)
    os.remove(new_file)
    if result:
        LOGR.info('任务执行完成:' + file)
    else:
        LOGR.info('任务执行失败:' + file)
Ejemplo n.º 16
0
def create_task():
    task_form = TaskForm()
    if not task_form.task_name.data:
        flash('please fill task name')
    else:
        #convert local datetime to UTC
        if task_form.task_due.data:
            task_due_local = get_localzone().localize(task_form.task_due.data,
                                                      is_dst=None)
            task_due_utc = task_due_local.astimezone(pytz.utc)
        else:
            task_due_utc = task_form.task_due.data
        if task_form.task_remind.data:
            task_remind_local = get_localzone().localize(
                task_form.task_remind.data, is_dst=None)
            task_remind_utc = task_remind_local.astimezone(pytz.utc)
        else:
            task_remind_utc = task_form.task_remind.data

        new_task = Task(task_name=task_form.task_name.data,
                        task_due=task_due_utc,
                        task_remind=task_remind_utc,
                        task_sent=task_sent,
                        user_id=current_user.get_id())
        db.session.add(new_task)
        db.session.commit()
        flash('yay! task is created successfully!')

        #check task_remind and send scheduled reminder by email
        if new_task.task_remind:
            if new_task.task_remind < datetime.utcnow().replace(
                    tzinfo=pytz.utc):
                flash('...but task reminder is past')
            else:
                send_email_reminder.apply_async(args=(new_task.task_id, ),
                                                eta=new_task.task_remind)
                flash('task reminder is also scheduled')
    return redirect(url_for('index'))
Ejemplo n.º 17
0
def seed_tasks():
    for i in range(500):
        fake_user_id = fake.pyint(min_value=16, max_value=100)
        user_role = User.query.get(fake_user_id).role
        task_type = ''

        if user_role == 'RN':
            task_type = 'Nurse visit'
        elif user_role == 'CNA':
            task_type = 'Home health aide visit'
        else:
            task_type = 'Therapy visit'

        new_task = Task(user_id=fake_user_id,
                        patient_id=fake.pyint(min_value=1, max_value=1000),
                        type=task_type,
                        scheduled_visit=datetime(
                            2022, fake.pyint(min_value=1, max_value=12),
                            fake.pyint(min_value=1, max_value=28)),
                        completed=fake.boolean(chance_of_getting_true=40))
        db.session.add(new_task)

    db.session.commit()
Ejemplo n.º 18
0
def add_task():
    subt_box = helpers.Box()
    notification = ''
    if request.method == 'POST':
        subt_box.import_request(request.form)
        if ('save' in request.form) and (len(subt_box.export_dict()['errors'])
                                         != []):
            print('>>> Saved!')
            new_task = Task(level=subt_box.export_json()['level'],
                            theme=subt_box.export_json()['theme'],
                            name=subt_box.export_json()['name'],
                            course=subt_box.export_json()['course'],
                            body=subt_box.export_json()['subs'])
            # print(new_task)
            db.session.add(new_task)
            db.session.commit()
            notification = 'Вы создали новое задание!'
            # print(subt_box.export_json())
    # print(subt_box.export_dict())
    return render_template('add_task.html',
                           title='Добавить задание',
                           subtasks=subt_box.export_dict(),
                           notification=notification)
Ejemplo n.º 19
0
def import_task():
    results = []
    if request.method == 'POST':
        task_file = request.files['task_file']
        data = pickle.load(task_file)
        taskinfo = data['taskinfo']
        taskdata = data['taskdata']
        task = Task(id=taskinfo['id'], mode=taskinfo['mode'], start_time=taskinfo['start_time'], \
                    end_time=taskinfo['end_time'],description=taskinfo['description'],laser_freq=taskinfo['laser_freq'], \
                    duration=taskinfo['duration'], resolution=taskinfo['resolution'], bin_length=taskinfo['bin_length'], \
                    data_num = taskinfo['data_num'], ver_start_angle=taskinfo['ver_start_angle'], \
                    ver_end_angle=taskinfo['ver_end_angle'], ver_step=taskinfo['ver_step'], \
                    hor_start_angle=taskinfo['hor_start_angle'], hor_end_angle=taskinfo['hor_end_angle'], \
                    hor_step=taskinfo['hor_step'], complete=taskinfo['complete'])
        db.session.merge(task)
        for i in range(len(taskdata)):
            task_dat = TaskData(task_id=taskdata[i]['task_id'],timestamp=taskdata[i]['timestamp'], \
                                longitude=taskdata[i]['longitude'],latitude=taskdata[i]['latitude'], \
                                altitude=taskdata[i]['altitude'],ver_angle=taskdata[i]['ver_angle'], \
                                hor_angle=taskdata[i]['hor_angle'],raw_A=taskdata[i]['raw_A'],raw_B=taskdata[i]['raw_B'])
            db.session.merge(task_dat)
        db.session.commit()
        return jsonify(result=results)
Ejemplo n.º 20
0
def task_add(project_id):
    if not current_user.is_anonymous:
        form = AddTaskForm()
        if form.validate_on_submit():
            order_value = Task.query.filter_by(project_id=project_id).count()
            task = Task(title=form.title.data,
                        project_id=project_id,
                        due_date=form.due_date.data,
                        completed=False,
                        order=order_value + 1)

            db.session.add(task)
            db.session.commit()

            flash('Project added successfully!')
            return redirect(url_for('project', project_id=project_id))

        project_list = Project.query.filter_by(user_id=current_user.id).all()
        return render_template('task_add.html',
                               form=form,
                               projects=project_list)

    return redirect(url_for('login'))
Ejemplo n.º 21
0
def update_task(id):
    # check whether payload is json
    if request.is_json:
        # Initialize vars to None
        title = description = status = None
        data = request.get_json(force=True)

        # Check if data exists in request
        if u'title' in data:
            title = data['title']
        if u'description' in data:
            description = data['description']
        if u'status' in data:
            status = data['status']

        # instantiate task model and send data to database
        task = Task()
        record = task.update_by_id(id, title=title, description=description, status=status)

        return task_schema.dump(record).data, 200
        # return jsonify({"message":"Task updated successfully"})
    else:
        return jsonify({"message": "Bad request body. JSON expected"}), 400
Ejemplo n.º 22
0
    def setUp(self):
        super().setUp()

        self.mitch = AppUser(phone_number=self.inviter_number,
                             username='******',
                             timezone=US_TIMEZONES['a'])
        self.db.session.add(self.mitch)

        self.exchange = Exchange(router=RouterNames.DID_YOU_DO_IT,
                                 outbound='Did you do it?',
                                 user=self.mitch)
        self.db.session.add(self.exchange)

        self.task = Task(description=self.description,
                         due_date=self.due_date,
                         active=True,
                         user=self.mitch,
                         exchange=self.exchange)
        self.db.session.add(self.task)

        self.db.session.commit()

        self.mitch = self.mitch.to_dict()
Ejemplo n.º 23
0
def task_prerun_handler(sender=None, task_id=None, task=None, **kwargs):
    run_task = Task.query.filter_by(task_id=task_id).first()
    if run_task:
        run_task.status = 'STARTED'
    else:
        info = sender.request
        run_task = Task(task_id=info.id,
                        task=task.name,
                        args=str(info.args),
                        kwargs=str(info.kwargs),
                        root_id=info.root_id,
                        parent_id=info.parent_id,
                        group=info.group,
                        eta=str(info.eta),
                        expires=str(info.expires),
                        retries=info.retries,
                        timelimit_soft=info.timelimit[0],
                        timelimit_hard=info.timelimit[1],
                        status='STARTED',
                        published_at=str(datetime.now()))
        db.session.add(run_task)
    run_task.begin = str(datetime.now())
    db.session.commit()
Ejemplo n.º 24
0
def task():
    form = TaskForm()
    if form.validate_on_submit():
        language = guess_language(form.name.data)
        if language == 'UNKNOWN' or len(language) > 5:
            language = ''
        task = Task(name=form.name.data, description=form.description.data, author=current_user,
                    language=language)
        db.session.add(task)
        db.session.commit()
        flash(_('Your task has been added!'))
        return redirect(url_for('main.task'))

    page = request.args.get('page', 1, type=int)
    tasks = current_user.owned_tasks().paginate(
        page, current_app.config['POSTS_PER_PAGE'], False)
    next_url = url_for('main.explore', page=tasks.next_num) \
        if tasks.has_next else None
    prev_url = url_for('main.explore', page=tasks.prev_num) \
        if tasks.has_prev else None
    return render_template('tasks.html', title='Tasks', form=form,
                                tasks=tasks.items, next_url=next_url,
                                prev_url=prev_url)
Ejemplo n.º 25
0
def render_create_task():
    if current_user.is_boss:
        form = TaskForm()
        executors = db.session.query(User).filter(
            User.is_boss.is_(False)).order_by(User.username).all()
        projects = db.session.query(Project).filter(
            Project.is_relevant.is_(True)).all()
        form.users.choices = [(executor.id, executor.username)
                              for executor in executors]
        form.project.choices = [(project.id, project.name)
                                for project in projects]
        if form.validate_on_submit():
            executors_lst = [
                db.session.query(User).get_or_404(executor_id)
                for executor_id in form.users.data
            ]
            deadline = form.deadline_date.data.strftime(
                "%Y-%m-%d") + ' ' + form.deadline_time.data.strftime(
                    "%H:%M:%S")
            deadline = datetime.strptime(deadline, "%Y-%m-%d %H:%M:%S")
            new_task = Task(name=form.name.data,
                            description=form.description.data,
                            deadline=deadline.astimezone(tzutc()),
                            author=current_user,
                            users=executors_lst,
                            priority=form.priority.data,
                            project=db.session.query(Project).get_or_404(
                                form.project.data))
            db.session.add(new_task)
            db.session.commit()
            return redirect(
                url_for('main.render_task_created', task_id=new_task.id))
        return render_template('create_task.html',
                               title="Создать задачу",
                               form=form)
    return abort(403)
Ejemplo n.º 26
0
def index():
    form = TaskForm()
    if form.validate_on_submit():
        task = Task(name=form.task.data, doer=current_user)
        db.session.add(task)
        db.session.commit()
        flash('Your task is added!')
        return redirect(url_for('index'))

    #getting days left
    weekdays = {
        0: 'Monday',
        1: 'Tuesday',
        2: 'Wednesday',
        3: 'Thursday',
        4: 'Friday',
        5: 'Saturday',
        6: 'Sunday'
    }
    today = datetime.date.today()
    weekday = datetime.date.weekday(today)
    days_left = 7 - weekday
    weekday = weekdays[weekday]
    #Getting all tasks for the current_user
    weekly_tasks = Task.query.filter(Task.user_id == current_user.id,
                                     Task.n_subtasks > 0)
    daily_tasks = Task.query.filter(Task.user_id == current_user.id,
                                    Task.n_subtasks == 0)
    return render_template('index.html',
                           title='Home',
                           today=today,
                           days_left=days_left,
                           weekday=weekday,
                           form=form,
                           daily_tasks=daily_tasks,
                           weekly_tasks=weekly_tasks)
Ejemplo n.º 27
0
def add_task():
    category = request.form['category']
    date = request.form['date']
    name = request.form['name']
    description = request.form['description']
    if not (category and date and name):
        flash("You didn't put in all of the values")
        return redirect(url_for('frontend.main'))
    category = Category.query.filter_by(name=request.form['category'], user=current_user).first()
    if category is None:
        flash("No category with that name")
        return redirect(url_for('frontend.main'))
    date2 = datetime.datetime.strptime(date, "%m/%d/%Y")
    tasks = db.session.query(db.func.max(Task.position)).filter_by(date=date2).scalar()
    position = 0
    if tasks == None:
        position = 1
    else:
        position = tasks + 1
    new_task = Task(name, category, description, date, current_user, position)
    db.session.add(new_task)
    db.session.commit()
    month = datetime.datetime.strptime(date, "%m/%d/%Y").strftime("%m")
    return redirect(url_for('frontend.main', month=month))
Ejemplo n.º 28
0
def add():
    form = TaskForm()
    milestones = Milestone.query.all()
    if not milestones:
        milestones = [create_default_milestone()]

    projects = Project.query.all()
    if not projects:
        projects = [create_default_project()]

    form.milestone.choices = [(m.id, m.name) for m in milestones]
    form.project.choices = [(p.id, p.name) for p in projects]

    if form.validate_on_submit():

        selected_milestone = Milestone.query.get(form.milestone.data)
        selected_project = Project.query.get(form.project.data)

        task = Task(name=form.name.data,
                    author=current_user,
                    description=form.name.data,
                    project=selected_project,
                    milestone=selected_milestone,
                    priority=form.priority.data,
                    group=form.group.data,
                    status=form.status.data,
                    created=datetime.utcnow(),
                    deadline=form.deadline.data,
                    schedule=form.schedule.data,
                    estimated=form.estimated.data,
                    actions=form.actions.data)
        db.session.add(task)
        db.session.commit()
        flash(_('Your task is saved'))
        return redirect(url_for('tasks.all'))
    return render_template('tasks/tasks.html', form=form)
Ejemplo n.º 29
0
def check_caches():
    isUpToDate = True
    try:
        print ('Checking cache versions')
        job = get_current_job()
        task = Task(id=job.get_id(), name='CacheCheck', description='Checking server caches for newer versions', complete=False, recreate=False)
        _set_task_progress(0)
        db.session.add(task)
        db.session.commit()
        
        print('cache task commited')
        #get headers Etag to check for cache version
        r_gloves = requests.get('https://bad-api-assignment.reaktor.com/v2/products/gloves')
        gloves_query = Caches.query.filter_by(name='Gloves').first()
        if r_gloves.headers['Etag'] != gloves_query.id:
            #it needs to be updated
            isUpToDate = False
            gloves_query.uptodate = False
        else:
            gloves_query.uptodate = True
            
        r_beanies = requests.get('https://bad-api-assignment.reaktor.com/v2/products/beanies')
        beanies_query = Caches.query.filter_by(name='Beanies').first()
        if r_beanies.headers['Etag'] != beanies_query.id:
            #it needs to be updated
            isUpToDate = False
            beanies_query.uptodate = False
        else:
            beanies_query.uptodate = True
            
        r_facemasks = requests.get('https://bad-api-assignment.reaktor.com/v2/products/facemasks')
        facemasks_query = Caches.query.filter_by(name='Facemasks').first()
        if r_facemasks.headers['Etag'] != facemasks_query.id:
            #it needs to be updated
            isUpToDate = False
            facemasks_query.uptodate = False
        else:
            facemasks_query.uptodate = True
            
        #forcing cachecheck to fail
        #facemasks_query.uptodate = False
        #isUpToDate = False
        
        print('cache products checked')
        manu_names = Manufacturer.query.all()
        #this is only checking for failed manufacturers, need to add all of the names to the list to be sure
        for manu in manu_names:
            print('checking cache for {}'.format(manu.name))
            url = 'https://bad-api-assignment.reaktor.com/v2/availability/' + manu.name
            m_request = requests.get(url)
            m_json = json.loads(m_request.text)
            
            if m_json['response'] != '[]':
                cache_query = Caches.query.filter_by(name=manu.name).first()
                if m_request.headers['Etag'] != cache_query.id:
                    #it needs to be updated
                    isUpToDate = False
                    cache_query.uptodate = False
                else:
                    cache_query.uptodate = True
        print('manufacturers checked')
        db.session.commit()
    except:
        print('Unhandled exception on checking caches')
       # _set_task_progress(100)
    finally:
        print('Finished checking caches')
        _set_task_progress(100)
        
        #isUpToDate = False #forcing cache check to fail
        
        if isUpToDate == False:
            print('There are new products available')
            #need to initialize the database again, but this should be voluntary?
            #create(True)
            task.recreate = True
            db.session.commit()
            cache = Caches.query.filter_by(uptodate=False).all()
            if cache:
                for item in cache:
                    print(item)
            #should be able to return the recreate value as a result of the job as well, which might have been easier/better
        else:
            print('Everything is up to date')
            caches()
Ejemplo n.º 30
0
def realgenerate_user_task(user):
    """
    Generate new task for a given user.

    This function assigns tasks to a given user and ensures that:

        1) datasets that are nearly annotated with the desired number of 
        datasets get priority
        2) users never are given more tasks than max_per_user
        3) users never get the same dataset twice

    """
    max_per_user = current_app.config["TASKS_MAX_PER_USER"]
    num_per_dataset = current_app.config["TASKS_NUM_PER_DATASET"]

    user_tasks = Task.query.filter_by(annotator_id=user.id).all()
    user_tasks = [t for t in user_tasks if not t.dataset.is_demo]

    # don't assign a new task if the user has assigned tasks
    not_done = [t for t in user_tasks if not t.done]
    if len(not_done) > 0:
        return None

    # don't assign a new task if the user has reached maximum
    n_user_tasks = len(user_tasks)
    if n_user_tasks >= max_per_user:
        return None

    # collect datasets that can be potentially assigned to the user
    potential_datasets = []
    for dataset in Dataset.query.filter_by(is_demo=False).all():
        dataset_tasks = Task.query.filter_by(dataset_id=dataset.id).all()

        # check that this dataset needs more annotations
        n_needed = num_per_dataset - len(dataset_tasks)

        # check that this dataset is not already assigned to the user
        task = Task.query.filter_by(dataset_id=dataset.id,
                                    annotator_id=user.id).first()
        if not task is None:
            continue
        potential_datasets.append((n_needed, dataset))

    # don't assign a dataset if there are no more datasets to annotate (user
    # has done all)
    if len(potential_datasets) == 0:
        return None

    # First try assigning a random dataset that still needs annotations
    dataset = None
    need_annotations = [d for n, d in potential_datasets if n > 0]

    # Weights are set to prioritize datasets that need fewer annotations to
    # reach our goal (num_per_dataset), with a small chance of selecting
    # another dataset.
    weights = [(num_per_dataset - n + 0.01) for n, d in potential_datasets
               if n > 0]
    if need_annotations:
        dataset = random.choices(need_annotations, weights=weights)[0]
    else:
        # if there are no such datasets, then this user is requesting
        # additional annotations after all datasets have our desired coverage
        # of num_per_dataset. Assign a random dataset that has the least excess
        # annotations (thus causing even distribution).
        max_nonpos = max((n for n, d in potential_datasets if n <= 0))
        extra = [d for n, d in potential_datasets if n == max_nonpos]
        if extra:
            dataset = random.choice(extra)

    if dataset is None:
        return None

    task = Task(annotator_id=user.id, dataset_id=dataset.id)
    return task