Exemplo n.º 1
0
def handle_tasks():
    if request.method == "POST":
        request_body = request.get_json()
        if 'title' in request_body and 'description' in request_body and 'completed_at' in request_body:
            new_task = Task(title=request_body["title"],
                            description=request_body["description"],
                            completed_at=request_body["completed_at"])
            db.session.add(new_task)
            db.session.commit()

            response = {"task": new_task.task_response()}
            return jsonify(response), 201

        else:
            return make_response({"details": "Invalid data"}, 400)

    elif request.method == "GET":
        sort_by_title = request.args.get("sort")
        if sort_by_title == "asc":
            tasks = Task.query.order_by(Task.title.asc())
        elif sort_by_title == "desc":
            tasks = Task.query.order_by(Task.title.desc())

        else:
            tasks = Task.query.all()

        tasks_response = []
        for task in tasks:
            tasks_response.append(task.task_response())
        return jsonify(tasks_response), 200
Exemplo n.º 2
0
    def test_13_complete_task_history_product_retailer(self):
        """ Test Price History Product Retailer
        """
        print(">>>>>", "Test Price History Product Retailer")
        # Import celery task
        from app.celery_app import main_task
        from app.models.history_product import Product

        # Filters for the task
        params = {
            "item_uuid": "fd960578-71ae-463e-84d5-0e451d184597",
            "retailer": "walmart"
        }

        celery_task = main_task.apply_async(args=(Product.start_retailer_task,
                                                  params))
        print("Submitted Task: ", celery_task.id)
        # Get the task from the celery task
        time.sleep(2)
        task = Task(celery_task.id)
        print('Created task instance!')

        # Check result of task
        while task.is_running():
            print("Waiting for task to finish")
            print(task.task_id)
            print(task.progress)
            print(task.status)
            time.sleep(1)

        prog = task.status['progress']
        print("Final progress: {}".format(prog))
        print("Result keys: {} ".format(list(task.result.keys())))
        self.assertEqual(prog, 100)
Exemplo n.º 3
0
def create():
    if not authenticated(session):
        abort(403)
    else:
        id_folder = int(request.form.get("id_folder"))
        task_name = request.form.get("task_name")

        if(id_folder == None) or (id_folder == ""):
            flash("The folder must have an id!", category="error")
            return redirect(request.referrer)
        if(task_name == None) or (task_name == ""):
            flash("The task must have a name!", category="error")
            return redirect(request.referrer)
        conn = connection()
        
        if User.has_permision_to_open_folder(conn, session['user']['id'], id_folder):
            if Task.exists(conn, id_folder, task_name):
                flash("The task already exists!", category="error")
                return redirect(request.referrer)
            else:
                try:
                    Task.create(conn, id_folder, task_name)
                    flash("One task has been added!", category="success")
                except:
                    flash("There was an error adding your task", category="error")
        else:
            flash("You can't access that folder!", category="error")
        return redirect(request.referrer)
Exemplo n.º 4
0
def githubCallback():
    if 'code' not in request.args:
        return '', 500

    # Fetch user from GitHub OAuth and store in session
    github = GitHub(GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET)
    access_token = github.get_token(request.args['code'])

    if access_token is None:
        flash('Could not authorize your request. Please try again.', 'danger')
        return '', 404

    user = User.find_or_create_from_token(access_token)

    session['access_token'] = access_token
    session['user_id'] = user.id

    # Transfer tasks in session to user database
    if 'tasks' in session:
        for task in session['tasks']:
            user_id = session['user_id']
            task_desc = task['description']
            Task.add_task(task_desc, user_id)

        session.pop('tasks', None)

    return redirect(url_for('home.index'))
Exemplo n.º 5
0
    def test_11_complete_task_count_by_retailer_engine(self):
        """ Test count by retailer engine
        """
        print(">>>>>", "Test Count by retailer engine")
        # Import celery task
        from app.celery_app import main_task
        from app.models.history_product import Product

        # Filters for the task
        params = {"date": "2019-05-24 19:17:06", "retailer": "walmart"}

        celery_task = main_task.apply_async(
            args=(Product.count_by_retailer_engine_task, params))
        print("Submitted Task: ", celery_task.id)
        # Get the task from the celery task
        time.sleep(2)
        task = Task(celery_task.id)
        print('Created task instance!')

        # Check result of task
        while task.is_running():
            print("Waiting for task to finish")
            print(task.task_id)
            print(task.progress)
            print(task.status)
            time.sleep(1)

        prog = task.status['progress']
        print("Final progress: {}".format(prog))
        print("Result keys: {} ".format(list(task.result.keys())))
        self.assertEqual(prog, 100)
Exemplo n.º 6
0
def test_complete_task_does_nothing_when_task_is_already_completed():
    completed_at = date(2020, 12, 31)
    task = Task(name="Foo", completed_at=completed_at)

    task.complete(at=date(2021, 1, 17))

    assert task.completed_at == completed_at
Exemplo n.º 7
0
def handle_tasks():
    if request.method == "GET":
        direction = request.args.get("sort")
        if direction == "asc":
            tasks = Task.query.order_by(asc("title"))
        elif direction == "desc":
            tasks = Task.query.order_by(desc("title"))
        else:
            tasks = Task.query.all()

        tasks_response = [task.to_dict() for task in tasks]

        return jsonify(tasks_response)

    elif request.method == "POST":
        request_body = request.get_json()
        try:
            new_task = Task(title=request_body["title"],
                            description=request_body["description"],
                            completed_at=request_body["completed_at"])
        except KeyError:
            return make_response({"details": "Invalid data"}, 400)

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

        return make_response({"task": new_task.to_dict()}, 201)
Exemplo n.º 8
0
def upload():
    file = request.files['file']
    ALLOWED_EXTENSIONS = set(['xls', 'xlsx'])
    if file:
        if '.' in file.filename and file.filename.rsplit(
                '.', 1)[1] not in ALLOWED_EXTENSIONS:
            raise FileTypeError()
        else:
            dirpath = os.path.join(current_app.root_path, 'upload')
            dirpath = dirpath.replace('\\', '/')
            now = datetime.datetime.now().strftime('%Y-%m-%d')
            path = dirpath + r'/task' + now + '.xls'
            file.save(path)
            #解析excel
            deal_excel = dealBatchExcel(path)
            task_name, task_url, task_description = deal_excel.get_task()
            task = Task.query.filter_by(name=task_name).all()
            #如果上传文件中的task不存在,则新增一个task
            if not task:
                task = Task()
                task.add_task(task_name, task_description, task_url)
            task = Task.query.filter_by(name=task_name).first_or_404()
            deal_excel.add_task_case(task.id)

    return jsonify(task)
Exemplo n.º 9
0
def task_cancel(task_id):
    """ Endpoint to consult tasks status by task_id
    """
    logger.info("Cancelling task ...")
    task = Task(task_id)
    if not task.status:
        raise AppError("task_error", "Task not found!")
    try:
        logger.info("Getting result")
        celery_task = celery_app.AsyncResult(task_id)
    except Exception as e:
        logger.error(e)
    if celery_task.state == 'SUCCESS' or celery_task.state == 'FAILURE':
        return jsonify(task.status)
    # Celery status
    try:
        task.progress = -1
        revoke(task_id, terminate=True)
    except Exception as e:
        logger.error(e)
    logger.debug(task.status)
    logger.debug(celery_task.state)
    status = task.status
    status['celery_status'] = celery_task.state

    return jsonify(status)
Exemplo n.º 10
0
def create():

    # Login-less logic
    if not 'access_token' in session:
        if not 'tasks' in session:
            session['tasks'] = []
        elif len(session['tasks']) == 5:
            flash(
                "Wanna create more? Login with your Github Account first, will Ya?",
                'info')
            return redirect(url_for('home.index'))

        if request.form['task-desc']:
            task_id = len(session['tasks'])  # To be used for temporary task_id
            task = {}
            task['id'] = task_id
            task['create_date'] = date.today()
            task['description'] = request.form['task-desc']
            session['tasks'].append(task)
            # Session won't be written in the response unless modified is set to True when modifying nested objects
            session.modified = True
            return redirect(url_for('home.index'))
        else:
            flash('A task can\'t be blank, boss!', 'info')
            return redirect(url_for('home.index'))

    # Logged in logic
    if request.form['task-desc']:
        task_desc = request.form['task-desc']
        user_id = g.user.id
        Task.add_task(task_desc, user_id)
        return redirect(url_for('home.index'))
    else:
        flash('A task can\'t be blank, boss!', 'info')
        return redirect(url_for('home.index'))
Exemplo n.º 11
0
def preprocessing_upload_mongodb():
    file = request.files.get('file')
    json_file = file.read()
    con = json.loads(json_file)
    task_id = con['task_id']
    print(task_id)
    col = mongo.db['%s' % str(task_id)]

    # 插入到mongodb中,这里需要将detail值做优化,只保存里面的prop_id和prop_value,prop_id作为键,prop_value作为值

    preprocess = PreprocessingCollection()
    d1 = preprocess.fill(con['details'], task_id)
    # print(d1)
    # 保存格式:task_details_id:{prop_id:prop_value}
    res = col.insert_one(d1)

    # 在task表中增加一个字段,插入完成之后,将值改为1,
    with db.auto_commit():
        task = Task().query.filter_by(id=task_id).first()
        task.is_preprocess = 1
    # print('inserted_id:%s' % (res.inserted_id))
    # find_res = col.find_one({"_id": res.inserted_id})
    #
    # item = find_res['4593']
    # for k,v in item.items():
    #     print('%s:%s' % (k, v))
    # for k, v in item.items():
    #     print('%s:%s'%(k,v))
    return 'success'
Exemplo n.º 12
0
def handle_tasks():

    if request.method == "POST":
        request_body = request.get_json()

        if "title" not in request_body or "description" not in request_body or "completed_at" not in request_body:
            return ({"details": "Invalid data"}, 400)
        else:
            task = Task(title=request_body["title"],
                        description=request_body["description"],
                        completed_at=request_body["completed_at"])
            db.session.add(task)
            db.session.commit()

            return make_response({"task": task.to_json()}, 201)
    else:
        title_sort_query = request.args.get("sort")
        if title_sort_query == "desc":
            tasks = Task.query.order_by(Task.title.desc())
        elif title_sort_query == "asc":
            tasks = Task.query.order_by(Task.title.asc())
        else:
            tasks = Task.query.all()

        tasks_response = []
        for task in tasks:
            tasks_response.append(task.to_json())

        return jsonify(tasks_response)
Exemplo n.º 13
0
def tasks():

    if request.method == "GET":
        task_order = request.args.get("sort")
        if task_order == None:
            tasks = Task.query.all()  # get all items in list
        elif task_order == "asc":  #to sort by ascending
            tasks = Task.query.order_by(asc(Task.title))
        elif task_order == "desc":  #to sort by descending
            tasks = Task.query.order_by(desc(Task.title))

        tasks_response = []
        for task in tasks:
            tasks_response.append(task.display_tasks())
        return jsonify(tasks_response)

    else:
        request_body = request.get_json()
        if "title" not in request_body or "description" not in request_body or "completed_at" not in request_body:
            return make_response(jsonify({"details": "Invalid data"}), 400)

        task = Task(title=request_body["title"],
                    description=request_body["description"],
                    completed_at=request_body["completed_at"])

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

        return jsonify({"task": task.display_tasks()}), 201
Exemplo n.º 14
0
    def patch(self, task_id):
        """
        Update a single task
        """

        # To do check if user is admin
        schema = TaskSchema(partial=True)

        update_data = request.get_json()

        validated_update_data, errors = schema.load(update_data)

        if errors:
            return dict(status="fail", message=errors), 400

        task = Task.get_by_id(task_id)

        if not task:
            return dict(status="fail", message=f"Task with id {task_id} not found"), 404

        updated_task = Task.update(task, **validated_update_data)

        if not updated_task:
            return dict(status='fail', message='Internal Server Error'), 500

        return dict(status="success", message="Task updated successfully"), 200
Exemplo n.º 15
0
def create_task():
    form = TaskForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            if allowed_file(form.library.data.filename):

                user_lib_filename = secure_filename(unicode(form.library.data.filename))

                new_task = Task(
                    creator_id = current_user.user_id,
                    title = form.title.data,
                    description = form.description.data,
                    status = 'Waiting for members',
                    lib_filename = user_lib_filename)

                user_lib_filename = \
                    str(current_user.user_id) + '_' + \
                    str(Task.query.order_by(desc(Task.task_id)).first().task_id + 1) + '_.' +  \
                    user_lib_filename;

                new_task.lib_filename = user_lib_filename

                user_lib_save_path = os.path.join(flask_app.root_path, flask_app.config['UPLOAD_FOLDER'], user_lib_filename)
                form.library.data.save(user_lib_save_path)


                app_db.session.add(new_task)
                app_db.session.commit()
                return redirect(url_for('tasks'))
            else:
                flash("Filename is not allowed")
        else:
            flash(form.errors)
    return render_template('create_task.html', title='Create Task', form=form)
Exemplo n.º 16
0
def deal_tasks():
    if request.method == "GET":
        sort_query = request.args.get("sort")  #<- handles second wave 2
        if sort_query == "desc":
            tasks = Task.query.order_by(Task.title.desc()).all()
        else:
            tasks = Task.query.order_by(
                Task.title).all()  #<- handles first wave 2
        tasks_response = []
        for task in tasks:
            tasks_response.append(task.to_json())
        return jsonify(tasks_response)

    elif request.method == "POST":
        request_body = request.get_json()

        if "title" in request_body and "description" in request_body and "completed_at" in request_body:
            new_task = Task(title=request_body["title"],
                            description=request_body["description"],
                            completed_at=request_body["completed_at"])

            db.session.add(new_task)
            db.session.commit()
            return make_response({"task": new_task.to_json()}, 201)
        else:
            return jsonify({"details": "Invalid data"}), 400
Exemplo n.º 17
0
    def test_08_fail_task_price_map_decorator(self):
        """ Test Map task without filters
        """
        print(">>>>", "Test Map task without filters")
        # Import celery task
        from app.celery_app import main_task
        from app.models.geo_mapa import Map

        # Filters for the task -> missing filters
        params = {
            "retailers": {
                "walmart": "Walmart",
                "superama": "Superama"
            },
            "date_start": "2019-01-10",
            "date_end": "2019-01-13",
            "interval": "day"
        }
        celery_task = main_task.apply_async(args=(Map.start_task, params))
        task = Task(celery_task.id)
        print("Submitted Task: ", celery_task.id)
        # Check result of task
        while task.is_running():
            time.sleep(1)

        prog = task.status['progress']
        print("Final progress: {}".format(prog))
        print("Result keys: {} ".format(list(task.result.keys())))

        self.assertEqual(prog, -1)
Exemplo n.º 18
0
def labeler_task():
    """
    标注员任务界面
    :return:
    """
    page = request.args.get('page')
    rows = request.args.get('pagerows')
    user = request.args.get('nickname')
    # 先查找是否有返工数据,如果有的话,不查询redis缓存
    if redis_client.get('task_list_%s_%s_%s' % (user, page, rows)):
        return redis_client.get('task_list_%s_%s_%s' % (user, page, rows))
    print('获取新的任务列表')
    # 任务数量
    tasks = Task.get_undone_task(page, rows)
    undone_task_count = Task.get_undone_task_count()
    labeler_task = LabelTaskCollection()
    now_time = int(time.time())
    today_start_time = now_time - (now_time - time.timezone) % 86400
    rework_data = True if Rework().get_rework_data(user) else ''
    labeler_task.fill(undone_task_count, tasks, user, today_start_time,
                      rework_data)

    # task.get('already_count') =Ta a
    # labeltaskviewmodel = LabelTaskViewModel()

    # 此处还差已完成数量、当前用户标注量、当前用户框数三个信息。
    redis_client.set('task_list_%s_%s_%s' % (user, page, rows),
                     json.dumps(labeler_task, default=lambda o: o.__dict__))
    return json.dumps(labeler_task, default=lambda o: o.__dict__)
Exemplo n.º 19
0
def update():
    if not authenticated(session):
        abort(403)
    else:
        id_task = int(request.form.get("id_task"))
        id_folder = int(request.form.get("id_folder"))
        task_name = request.form.get("task_name")

        if(id_task == None) or (id_task == ""):
            flash("The task must have an id!", category="error")
            return redirect(request.referrer)
        if(id_folder == None) or (id_folder == ""):
            flash("The folder must have an id!", category="error")
            return redirect(request.referrer)
        if(task_name == None) or (task_name == ""):
            flash("The task must have a name!", category="error")
            return redirect(request.referrer)
        conn = connection()
        
        if Task.exists(conn, id_folder, task_name):
            flash("The task already exists!", category="error")
        else:
            try:
                Task.update(conn, id_task, task_name)
                flash("The task was updated!", category="success")
            except:
                flash("There was an error editing your task", category="error")
        
        return redirect(request.referrer)
Exemplo n.º 20
0
def tasks():

    if request.method == "GET":
        task_order = request.args.get("sort")
        if task_order == None:
            tasks = Task.query.all(
            )  # Task is the model and query is a class method (query is getting all task)
        elif task_order == "asc":
            tasks = Task.query.order_by(asc(Task.title))
        elif task_order == "desc":
            tasks = Task.query.order_by(desc(Task.title))

        tasks_response = []
        for task in tasks:

            tasks_response.append(task.to_json())

        return jsonify(tasks_response)
    # using the "PUT" to add a new task
    else:
        request_body = request.get_json()
        if "title" not in request_body or "description" not in request_body or "completed_at" not in request_body:
            return make_response(jsonify({"details": "Invalid data"}), 400)

        task = Task(title=request_body["title"],
                    description=request_body["description"],
                    completed_at=request_body["completed_at"])

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

        return jsonify({"task": task.to_json()}), 201
Exemplo n.º 21
0
def test_complete_task_sets_completed_at():
    task = Task(name="Foo")
    now = date(2020, 12, 31)

    task.complete(at=now)

    assert task.completed_at is not None
    assert task.completed_at == now
Exemplo n.º 22
0
def add_Task():
    form = TaskForm().validate_for_api()
    if Task.is_name_exist(form.name.data):
        raise RepeatFailed()
    else:
        task = Task()
        task.add_task(form.name.data,form.description.data,form.request_header.data)

    return Success()
Exemplo n.º 23
0
def create_new_task():
    new_task_data = request.get_json()
    if new_task_data.keys() >= {"title", "description", "completed_at"}:
        new_task = Task(**new_task_data)
        db.session.add(new_task)
        db.session.commit()
        return {"task": new_task.task_to_json()}, 201
    else:
        return {"details": "Invalid data"}, 400
Exemplo n.º 24
0
 def post(self):
     parser = reqparse.RequestParser()
     parser.add_argument('text')
     parser.add_argument('title')
     args = parser.parse_args()
     task = Task(title=args.title, text=args.text)
     db.session.add(task)
     db.session.commit()
     return {"status": "ok", "task": task.to_dict()}, 200
Exemplo n.º 25
0
 def test_get_task_filtering_invalid_method_argument(self):
     task1 = Task(title='title1', status='in_progress')
     task1.assign_user(1)
     db.session.add(task1)
     db.session.commit()
     res = self.client.get(self.ENDPOINT + '?status=wrong',
                           headers=self.auth_header)
     self.assert400(res)
     self.assertIn('status', res.json['message'])
Exemplo n.º 26
0
 def test_post_assign_to_not_existing_user(self):
     task1 = Task(title='title1', status='in_progress')
     task1.assign_user(1)
     db.session.add(task1)
     db.session.commit()
     res = self.client.post(self.ENDPOINT,
                            headers=self.auth_header,
                            data={'user_id': 100, 'task_id': 1})
     self.assert400(res)
Exemplo n.º 27
0
def three_tasks(app):
    db.session.add_all([
        Task(
            title="Water the garden 🌷", description="", completed_at=None),
        Task(
            title="Answer forgotten email 📧", description="", completed_at=None),
        Task(
            title="Pay my outstanding tickets 😭", description="", completed_at=None)
    ])
    db.session.commit()
Exemplo n.º 28
0
 def test_get_tasks_count_for_current_user(self):
     res = self.client.get(self.ENDPOINT, headers=self.auth_header)
     self.assert200(res)
     self.assertEqual(len(res.json['items']), 0)
     task1 = Task(title='title1', status='in_progress')
     task1.assign_user(1)
     db.session.add(task1)
     db.session.commit()
     res = self.client.get(self.ENDPOINT, headers=self.auth_header)
     self.assertEqual(len(res.json['items']), 1)
Exemplo n.º 29
0
 def test_01_save_task_status(self):
     """ Testing DB prices i
     """
     print(">>>> Testing create new task and save status")
     global task_id
     task = Task()
     task.status = dict(stage='STARTING', progress=1, msg='All set')
     # Save global task_id
     task_id = task.task_id
     self.assertTrue(task_id)
Exemplo n.º 30
0
 def test_post_assign_integrity_error(self):
     task1 = Task(title='title1', status='in_progress')
     task1.assign_user(1)
     db.session.add(task1)
     db.session.commit()
     res = self.client.post(self.ENDPOINT,
                            headers=self.auth_header,
                            data={'user_id': 1, 'task_id': 1})
     self.assert400(res)
     self.assertIn('Integrity', res.json['message'])
Exemplo n.º 31
0
 def test_delete_task(self):
     task = Task(title='title1', status='in_progress')
     task.assign_user(1)
     db.session.add(task)
     db.session.commit()
     self.assertEqual(Task.query.count(), 1)
     res = self.client.delete(self.ENDPOINT + '/1',
                              headers=self.auth_header)
     self.assertEqual(res.status_code, 204)
     self.assertEqual(Task.query.count(), 0)
Exemplo n.º 32
0
def add_task(data):
    """ 项目添加 """
    if Task.query.filter_by(task_id=data.get('task_id', None),
                            is_valid=True).first():
        return bad_request('定时任务ID已存在')
    data['created_at'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    task_data = Task()
    task_data.from_dict(data)
    db.session.add(task_data)
    db.session.commit()
Exemplo n.º 33
0
def delete_task():
    id = request.args.get("id")
    task = Task.query.filter_by(id=id).first()
    task.active = False

    try:
        Task.update()
        return jsonify({'result': "registro deletado com sucesso!"})
    except:
        return jsonify({'result': "Não foi possível deletar o registro!"})
Exemplo n.º 34
0
    def test_09_complete_task_price_historia_decorator(self):
        """ Test price Geo Historia Decorator
        """
        print(">>>>>", "Test price Geo Historia Decorator")
        # Import celery task
        from app.celery_app import main_task
        from app.models.geo_historia import Historia

        # Filters for the task
        params = {
            "filters": [{
                "item_uuid": "fd960578-71ae-463e-84d5-0e451d184597"
            }, {
                "item_uuid": "7f177768-cd76-45e4-92ac-9bab4ec8d8b3"
            }, {
                "item_uuid": "63aa59b6-04a7-45ed-99df-8f6d1403c4de"
            }, {
                "item_uuid": "facdc537-d80f-447e-9d6e-0266e0e9d082"
            }, {
                "retailer": "walmart"
            }],
            "retailers": {
                "walmart": "Walmart",
                "superama": "Superama"
            },
            "date_start":
            "2019-05-19",
            "date_end":
            "2019-05-21",
            "interval":
            "day"
        }

        celery_task = main_task.apply_async(args=(Historia.filters_task,
                                                  params))
        print("Submitted Task: ", celery_task.id)
        # Get the task from the celery task
        time.sleep(2)
        task = Task(celery_task.id)
        print('Created task instance!')

        # Check result of task
        while task.is_running():
            print("Waiting for task to finish")
            print(task.task_id)
            print(task.progress)
            print(task.status)
            time.sleep(1)

        prog = task.status['progress']
        print("Final progress: {}".format(prog))
        print("Result keys: {} ".format(list(task.result.keys())))

        self.assertEqual(prog, 100)
Exemplo n.º 35
0
 def post(self):
     args = post_task.parse_args()
     task = Task(**args)
     task.assign_user(current_app.user.id)
     try:
         db.session.add(task)
         db.session.commit()
     except DataError as e:
         db.session.rollback()
         abort(400, str(e))
     return task, 201
Exemplo n.º 36
0
def create_task():
    request_body = request.get_json()
    if "title" in request_body and "description" in request_body and "completed_at" in request_body:
        new_task = Task(title=request_body["title"],
                        description=request_body["description"],
                        completed_at=request_body["completed_at"])
        db.session.add(new_task)
        db.session.commit()
        return jsonify({"task": new_task.to_json()}), 201
    else:
        return make_response({"details": "Invalid data"}, 400)
Exemplo n.º 37
0
def post_task():
    form_data = request.get_json()
    if "title" not in form_data\
            or "description" not in form_data\
                or "completed_at" not in form_data:
        return ({"details": "Invalid data"}, 400)
    new_task = Task(title=form_data["title"],
                    description=form_data["description"],
                    completed_at=form_data["completed_at"])
    db.session.add(new_task)
    db.session.commit()
    return {"task": new_task.task_dict()}, 201
Exemplo n.º 38
0
 def test_get_tasks_count_for_other_user(self):
     task1 = Task(title='title1', status='in_progress')
     task1.assign_user(1)
     db.session.add(task1)
     db.session.commit()
     user2 = User(name='user2', email='*****@*****.**')
     user2.password = hashlib.md5('1').hexdigest()
     db.session.add(user2)
     db.session.commit()
     token = self.login('user2', '1').json['token']
     res = self.client.get(self.ENDPOINT, headers={'token': token})
     self.assertEqual(len(res.json['items']), 0)
Exemplo n.º 39
0
 def test_get_assigned(self):
     task1 = Task(title='title1', status='in_progress')
     task1.assign_user(1)
     db.session.add(task1)
     db.session.commit()
     res = self.client.get(self.ENDPOINT + '/1', headers=self.auth_header)
     self.assert200(res)
     self.assertEqual(res.json['id'], 1)
     self.assertEqual(res.json['status'], 'in_progress')
     self.assertEqual(res.json['title'], 'title1')
     self.assertEqual(res.json['users'], '[1]')
     self.assertIn('2016', res.json['created_at'])
     self.assertIn('2016', res.json['updated_at'])
Exemplo n.º 40
0
 def test_post_assign_valid(self):
     task1 = Task(title='title1', status='in_progress')
     task1.assign_user(1)
     db.session.add(task1)
     db.session.commit()
     user2 = User(name='user2', email='*****@*****.**')
     user2.password = hashlib.md5('1').hexdigest()
     db.session.add(user2)
     db.session.commit()
     res = self.client.post(self.ENDPOINT,
                            headers=self.auth_header,
                            data={'user_id': 2, 'task_id': 1})
     self.assertEqual(res.status_code, 201)
Exemplo n.º 41
0
 def test_put_task_with_no_status(self):
     task = Task(title='title1', status='in_progress')
     task.assign_user(1)
     db.session.add(task)
     db.session.commit()
     res = self.client.get(self.ENDPOINT + '/1', headers=self.auth_header)
     self.assert200(res)
     self.assertEqual(res.json['status'], 'in_progress')
     self.assertEqual(Task.query.get(1).status, 'in_progress')
     res = self.client.put(self.ENDPOINT + '/1',
                           headers=self.auth_header)
     self.assert400(res)
     self.assertEqual(Task.query.get(1).status, 'in_progress')
Exemplo n.º 42
0
 def test_put_user_task(self):
     task1 = Task(title='title1', status='in_progress')
     task1.assign_user(1)
     db.session.add(task1)
     db.session.commit()
     self.assertEqual(Task.query.get(1).status, 'in_progress')
     res = self.client.get(self.ENDPOINT + '/1', headers=self.auth_header)
     self.assert200(res)
     res = self.client.put(self.ENDPOINT + '/1',
                           headers=self.auth_header,
                           data={'status': 'completed'})
     self.assert200(res)
     self.assertEqual(Task.query.get(1).status, 'completed')
Exemplo n.º 43
0
 def test_get_task_fields_default(self):
     task1 = Task(title='title1', status='in_progress')
     task1.assign_user(1)
     db.session.add(task1)
     db.session.commit()
     res = self.client.get(self.ENDPOINT, headers=self.auth_header)
     self.assertDictEqual(res.json, {'limit': 20,
                                     'offset': 0,
                                     'items': [{'title': 'title1',
                                                'status': 'in_progress',
                                                'id': 1,
                                                'users': '[1]'}],
                                     'total': 1,
                                     'user': 1})
Exemplo n.º 44
0
 def test_get_forbidden(self):
     task1 = Task(title='title1', status='in_progress')
     task1.assign_user(1)
     db.session.add(task1)
     db.session.commit()
     res = self.client.get(self.ENDPOINT + '/1', headers=self.auth_header)
     self.assert200(res)
     user2 = User(name='user2', email='*****@*****.**')
     user2.password = hashlib.md5('1').hexdigest()
     db.session.add(user2)
     db.session.commit()
     token = self.login('user2', '1').json['token']
     res = self.client.get(self.ENDPOINT + '/1', headers={'token': token})
     self.assert403(res)
Exemplo n.º 45
0
 def test_post_not_assigned_task(self):
     task1 = Task(title='title1', status='in_progress')
     task1.assign_user(1)
     db.session.add(task1)
     db.session.commit()
     user2 = User(name='user2', email='*****@*****.**')
     user2.password = hashlib.md5('1').hexdigest()
     db.session.add(user2)
     db.session.commit()
     token_for_2_user = self.login('user2', '1').json['token']
     res = self.client.post(self.ENDPOINT,
                            headers={'token': token_for_2_user},
                            data={'user_id': 2, 'task_id': 1})
     self.assert403(res)
Exemplo n.º 46
0
 def test_post_assign_not_valid_fields(self):
     DATA = {
         'user_id': '1',
         'task_id': '1'
     }
     task1 = Task(title='title1', status='in_progress')
     task1.assign_user(1)
     db.session.add(task1)
     db.session.commit()
     for key in DATA.keys():
         params = DATA.copy()
         del params[key]
         self.assert400(self.client.post(self.ENDPOINT,
                                         headers=self.auth_header,
                                         data=params))
Exemplo n.º 47
0
 def flush(self):
     task = Task.task(self.request.get('id'))
     task.update(self.request.POST)
     task.complete = True
     task.save()
     
     self.render_text('OK')
Exemplo n.º 48
0
 def test_put_other_user_task(self):
     task1 = Task(title='title1', status='in_progress')
     task1.assign_user(1)
     db.session.add(task1)
     db.session.commit()
     self.assertEqual(Task.query.get(1).status, 'in_progress')
     res = self.client.get(self.ENDPOINT + '/1', headers=self.auth_header)
     self.assert200(res)
     user2 = User(name='user2', email='*****@*****.**')
     user2.password = hashlib.md5('1').hexdigest()
     db.session.add(user2)
     db.session.commit()
     token = self.login('user2', '1').json['token']
     res = self.client.put(self.ENDPOINT + '/1',
                           headers={'token': token},
                           data={'status': 'completed'})
     self.assert403(res)
     self.assertEqual(Task.query.get(1).status, 'in_progress')
Exemplo n.º 49
0
 def test_get_task_fields_offset_limit(self):
     for i in range(30):
         task1 = Task(title='title' + str(i), status='in_progress')
         task1.assign_user(1)
         db.session.add(task1)
     db.session.commit()
     res = self.client.get(self.ENDPOINT, headers=self.auth_header)
     self.assertEqual(res.json['limit'], 20)
     self.assertEqual(res.json['offset'], 0)
     self.assertEqual(len(res.json['items']), 20)
     self.assertEqual(res.json['items'][0]['id'], 1)
     self.assertEqual(res.json['total'], 30)
     self.assertEqual(res.json['user'], 1)
     res = self.client.get(self.ENDPOINT + '?offset=10&limit=5',
                           headers=self.auth_header)
     self.assertEqual(res.json['limit'], 5)
     self.assertEqual(res.json['offset'], 10)
     self.assertEqual(len(res.json['items']), 5)
     self.assertEqual(res.json['items'][0]['id'], 11)
     self.assertEqual(res.json['total'], 30)
     self.assertEqual(res.json['user'], 1)
Exemplo n.º 50
0
 def post(self):
     user = g.user
     wetness = request.form.get('wetness', type=float)
     temperature = request.form.get('temperature', type=float)
     lightness = request.form.get('lightness', type=float)
     flower_id = request.form.get('flower_id', type=int)
     flower = Flower.get(flower_id)
     flower.process_statistics(wetness, temperature, lightness)
     task = Task.pick_one(user)
     if task:
         task.mark_done()
         return task.to_dict(user)
     return API_SUCCESS
Exemplo n.º 51
0
    def test_get_task_valid_filtering(self):
        task1 = Task(title='title1', status='in_progress')
        task1.assign_user(1)
        task2 = Task(title='title2', status='completed')
        task2.assign_user(1)
        db.session.add(task1)
        db.session.add(task2)
        db.session.commit()
        res = self.client.get(self.ENDPOINT,
                              headers=self.auth_header)
        self.assert200(res)
        self.assertEqual(len(res.json['items']), 2)
        res = self.client.get(self.ENDPOINT + '?status=in_progress',
                              headers=self.auth_header)
        self.assert200(res)
        self.assertEqual(len(res.json['items']), 1)
        self.assertEqual(res.json['items'][0]['status'], 'in_progress')

        res = self.client.get(self.ENDPOINT + '?status=completed',
                              headers=self.auth_header)
        self.assert200(res)
        self.assertEqual(len(res.json['items']), 1)
        self.assertEqual(res.json['items'][0]['status'], 'completed')
Exemplo n.º 52
0
 def get_my_tasks():
     me = UserSvc.get_current_user()
     if 'Manager' in me._class_name():
         pass
     return Task.get_all_user_tasks(me)
Exemplo n.º 53
0
 def observation_done(selling_partner_key):
     Task.mark_as_complete_by_user('Observation', selling_partner_key)
Exemplo n.º 54
0
 def review_done(assessment_key):
     Task.mark_as_complete_by_assessment('Review', assessment_key)
Exemplo n.º 55
0
 def self_assessment_done():
     me = UserSvc.get_current_user(key_only=True)
     Task.mark_as_complete_by_user('SelfAssessment', me)