Esempio n. 1
0
 def post(self):
     parse = reqparse.RequestParser()
     parse.add_argument('name',type=str, required=True)
     parse.add_argument('classifer',type=str, required=True)
     args = parse.parse_args()
     task = Task(name=args["name"],classifer=args["classifer"])
     tasks = Task.query.all()
     try :
         task.save_to_db()  
         return {'success':"true"},201
     except : 
         return marshal( tasks,task_field), 403
Esempio n. 2
0
def start_timer(request):
    if request.is_ajax():
    	try:
           company = Company.objects.get(name = request.POST['client'].title() )
        except Company.DoesNotExist:
            company = Company( name = request.POST['client'].title(), created = datetime.now(), user_id = request.user.id)
            company.save()

        task = Task(user_id = request.user.id, company_id = company.id, task_name = request.POST['taskName'], time_spent = '00:00:00')
        task.save()
        to_json = { "task_id" : task.id}
        return HttpResponse( simplejson.dumps(to_json), mimetype = 'application/json')
Esempio n. 3
0
def user(username):

    user = User.query.filter_by(username=username).first_or_404()
    
    form = TaskForm()
    if form.validate_on_submit() and username == current_user.username:
        title=form.task_title.data
        description=form.task_description.data
        task = Task(
            title=form.task_title.data,
            description=form.task_description.data,
            done = form.done.data,
            creator_id = current_user.id
        )
        db.session.add(task)
        db.session.commit()
        flash("Added task, hopefully.")
        return redirect(url_for('main.user', username=current_user.username))

    page = request.args.get('page', 1, type=int)

    user_tasks = user.tasks
    
    if user.username != current_user.username:
        return render_template('user.html', user=user, tasks=user_tasks)
    return render_template('user.html', user=user, tasks=user_tasks, form=form)
Esempio n. 4
0
def create_team_task(id):
    team = Team.query.get_or_404(id)

    form = TeamTaskForm()
    if form.validate_on_submit() and request.method=="POST":

        t = Task(
            title = form.title.data,
            description = form.description.data,
            done=False,
            creator_id=current_user.id,
            position="yellow",
            priority=False,
            board=1,
            is_team_task=True
        )
        db.session.add(t)
        db.session.flush()
        team_task = team.create_team_task(t)

        db.session.add(team_task)
        db.session.commit()

        flash('Created a new task for your team!')
        return redirect(url_for('main.team_tasks_uusi', id=team.id, team=team), code=307)
    
    return render_template('_modal.html', id=team.id, form=form, endpoint="main.create_team_task", title="Create task", team=team, teksti="Create task")
Esempio n. 5
0
def task_post():
    text = request.form.get('text')
    date = request.form.get('date')
    date_format = datetime.strptime(date, '%Y-%m-%d %H:%M')

    db.session.add(Task(text=text, date=date_format))
    db.session.commit()
    return jsonify()
Esempio n. 6
0
def add_task(title, date):
    #Filtering tasks data to check whether task is already present or not
    task = Task.query.filter_by(title=title, date_posted=date).first()
    #If not already present, add task to the database
    if not task:
        new_task = Task(title=title, date_posted=date)
        db.session.add(new_task)
        db.session.commit()
    tasks = Task.query.all()
    return str(tasks)
Esempio n. 7
0
def created():
    form = TaskForm()
    if request.method == "POST":
        if form.validate_on_submit():
            new_task = Task(description=form.description.data)
            print(new_task.complete)
            db.session.add(new_task)
            db.session.commit()
            return redirect(url_for('home'))
    return render_template('add.html', title="Create a Task", form=form)
Esempio n. 8
0
    def get_board_choices(self):
        """ Generates a list of tuples for board choices """
        # Task.boards() gives us the values we need, but in the wrong
        # order (board name, board id), we want them as (board id, board name)
        boards_dict = {y: x for x, y in Task.boards().items()}
        # print("Boards dict: ", boards_dict)

        # Now we can generate a list of choices for the selectfield
        # and have the current board as the default choice
        list = [(k, v) for k, v in boards_dict.items()]
        return list
Esempio n. 9
0
 def setUp(self):  # Pre test
     date_raw = datetime.today()
     date = date_raw.strftime("%Y-%m-%d")
     self.date_string = str(date).encode("ascii")
     db.create_all()
     test_list = Checklist(name="TestList")
     self.test_list_id = 1
     db.session.add(test_list)
     db.session.commit()
     test_task = Task(name="TestTask", list_id="1")
     db.session.add(test_task)
     db.session.commit()
Esempio n. 10
0
    def post(self):
        """ Create a new task """
        r = request.get_json(force=True)
        #print("Current_user: "******"Tehtävä id: ", t.id)

        return t.to_json()
Esempio n. 11
0
def editList(list_name):

    if not listExists(list_name):
        return redirect(url_for("home"))

    list_id = getListId(list_name)

    message = "Add tasks!"
    error_text = ""

    task_input = TaskForm()
    if request.method == "POST" and task_input.validate_on_submit():
        new_task = Task(name=task_input.user_input.data, list_id=list_id)
        db.session.add(new_task)
        db.session.commit()
        task_input.user_input.data = ""
        message = "task added!"
    else:
        if task_input.user_input.errors:
            error_text = task_input.user_input.errors[0]

    # Read
    task_details = {}
    for item in Task.query.all():
        task_details[item.name] = [item.date_done]

    # Display config:

    done_tasks = doneTaskNames(list_id=list_id)
    non_done_tasks = notDoneTaskNames(list_id=list_id)

    if len(done_tasks) == 0:
        done_tasks_exists = False
    else:
        done_tasks_exists = True
    if len(non_done_tasks) == 0:
        non_done_tasks_exists = False
    else:
        non_done_tasks_exists = True

    return render_template("edit_list.html",
                           list_name=list_name,
                           non_done_tasks_exists=non_done_tasks_exists,
                           non_done_tasks=non_done_tasks,
                           form=task_input,
                           task_details=task_details,
                           done_tasks_exists=done_tasks_exists,
                           done_tasks=done_tasks,
                           message=message,
                           error_text=error_text)
Esempio n. 12
0
def tasks(request, db):
    if request == "POST":
        task_content = request.form['content']
        new_task = Task(content=task_content)
        try:
            db.session.add(new_task)
            db.session.commit()
            return redirect('/task')
        except:
            return "There was an issue assing your task"
    else:
        u_tasks = Task.query.filter_by(completed=0).all()
        c_tasks = Task.query.filter_by(completed=1).all()
        return render_template('task.html', u_tasks=u_tasks, c_tasks=c_tasks)
Esempio n. 13
0
def create_task(project_id):
    project = Project.query.get(project_id)
    form = TaskForm()
    form.assignee_id.choices = project.users
    if request.method == 'POST':
        assignee_id = int(request.form.get('members'))
        new_task = Task(project_id, form.subject.data, form.description.data,
                        current_user.id, assignee_id, Status.to_do.name)

        db.session.add(new_task)
        db.session.commit()
        return redirect(url_for('project.show_project', project_id=project_id))
    return render_template('task/creating.html',
                           title='Creating task',
                           form=form)
Esempio n. 14
0
def index():
    if request.method == 'POST':
        task_content = request.form['content']
        new_task = Task(content=task_content)

        try:
            db.session.add(new_task)
            db.session.commit()
            return redirect('/')
        except:
            return 'There was an issue adding your task'

    else:
        tasks = Task.query.order_by(Task.date_created).all()
        return render_template('index.html', tasks=tasks)
Esempio n. 15
0
    def post(self):
        """ API endpoint used to create tasks """
        data = request.get_json(force=True)
        user = g.current_user

        #print("Current_user: "******"user", user)

        task = Task.query.filter_by(id=data[id]).first()

        User.verify_auth_token()

        if task is not None:
            task.position = data['position']
            task.priority = data['priority']
            db.session.commit()
            return jsonify({
                'id': task.id,
                'title': task.title,
                'description': task.description,
                'priority': task.priority,
                'position': task.position
            })

        print("Task apin saama post: ", data)

        t = Task(
            title=data['title'],
            description=data['description'],
            position=data['position'],
            priority=data['priority'],
            created=datetime.utcnow()
            # TODO: lisää kun olet lisännyt teitokantaan kentän
            # priority = data['priority]
        )
        db.session.add(t)
        db.session.commit()

        t = Task.query.filter_by(created=t.created).first()

        return jsonify({
            'id': t.id,
            'title': t.title,
            'description': t.description,
            'priority': t.priority,
            'position': t.position
        })
Esempio n. 16
0
 def test_user_tasks_relationship(self):
     """ Tests that user's tasks can be found
     using the sqlalchemy relationship. """
     u = User(username="******", email="*****@*****.**")
     u.set_password("Kissa")
     db.session.add(u)
     #print("u.id: ", u.id)
     db.session.commit()
     t = Task(title="tTehtävä",
              description="Tehtävä kuvaus",
              creator_id=u.id)
     db.session.add(t)
     db.session.commit()
     self.assertIn(t, u.tasks)
     l = u.tasks.copy()
     tehtava = l.pop()
     self.assertEqual(tehtava.title, "tTehtävä")
Esempio n. 17
0
        def apply_async(self, args=None, kwargs=None, **options):
            with app.app_context():
                task = DBTask.get(self.name, kwargs["key"], enabled=True, will_raise=True)
                lock_key = self.get_key(args, kwargs)
                self.init_opts(task, options)
                if not self.is_retrying:
                    try:
                        self.once_backend.raise_or_lock(lock_key, timeout=self.timeout)
                        self.revoke_pending(task)
                        kwargs["id"] = self.init_handler(task, lock_key).id
                    except AlreadyQueued as e:
                        if self.graceful:
                            return self.reject_eager(lock_key, e)
                        raise e

                async_result = super(QueueOnce, self).apply_async(args, kwargs, **options)
                async_result.lock_key = lock_key
                return async_result
Esempio n. 18
0
def dashboard():
    tasks = Task.query.all()
    if request.method == "POST":
        print(Task.find_by_id(1).json())
        if tasks == None:
            tasks = ["錯誤"]
    user = User.query.order_by(User.username).first()
    sensor = Sensor.query.all()
    time = [ids.time.strftime("%Y-%m-%d %H:%M:%S") for ids in sensor]
    sensor_id = [ids.sensor_id for ids in sensor]
    counter_sensor = Counter(sensor_id)
    return render_template('iot/iot.html',
                           user=user,
                           tasks=tasks,
                           time=time,
                           sensor=sensor,
                           sensor_id=list(counter_sensor.keys()),
                           sensor_id_count=list(counter_sensor.values()))
Esempio n. 19
0
    def __init__(self, team_id, task, user, *args, **kwargs):
        super(TeamTaskFormEdit, self).__init__(*args, **kwargs)
        lista = []

        team = Team.query.filter_by(id=team_id).first()

        team_members = team.team_members
        team_task = TeamTask.query.filter_by(task_id=task.id).first()

        # Lista pohjana muille osuuksille
        lista3 = []

        for i in team_members:
            if team_task.doing is not None and team_task.doing == i.team_member_id:
                lista3.insert(0,
                              (i.team_member_id, i.team_member_user.username))

            else:
                lista3.append((i.team_member_id, i.team_member_user.username))

        # If task not assigned to anyone, set None as default in the field
        if team_task.doing is None:
            lista3.insert(0, (0, "None"))
        else:
            lista3.append((0, "None"))

        if not user.can_team(team_id, TeamPermission.ASSIGN_TASKS):
            if team_task.doing is None:
                lista3 = [(0, "None"), (user.id, user.username)]
            else:
                if team_task.doing is not None and team_task.doing != user.get_team_member_object(
                        team.id).id:
                    team_member = TeamMember.query.filter_by(
                        id=team_task.doing).first()
                    lista3 = [(team_member.team_member_id,
                               team_member.team_member_user.username)]
                else:
                    lista3 = [(user.id, user.username), (0, "None")]

        self.assign_to_choices.choices = lista3

        # Find the team_task that corresponds to the task object
        team_task = TeamTask.query.filter_by(task_id=task.id).first()
        # Get the team_member curerntly doing the task

        # If someone is already doing/assigned the task, we need to
        # set them as the default choice in the form.
        if team_task.doing is not None:
            team_member = TeamMember.query.filter_by(
                id=team_task.doing).first()

        lista2 = []
        for item in Task.boards().items():
            lista2.append((item[1], item[0]))
        board_choices = self.get_board_choices()
        default_value = self.get_default_value_for_board_choices(
            task, board_choices)
        board_choices_default_first = self.get_board_choices_with_default_first(
            default_value, board_choices)

        self.board_choices.choices = board_choices_default_first
Esempio n. 20
0
def create_app(config_class=Config):
    """ Initializes the core application """
    app = Flask(__name__, instance_relative_config=False)
    app.config.from_object(config_class)
    # app.config.from_object('config.DevConfig')
    # app.config['DEBUG'] = True
    # app.debug = True

    #if os.environ.get('DYNO'):
    #    app.config.from_object('config.HerokuConfig')
    # if app.config['SSL_REDIRECT']:
    #     from flask_sslify import SSLify
    #     sllify = SSLify(app)

    # if 'DYNO' in os.environ.get('DYNO'): # only trigger SSLify if the app is running on Heroku
    #     from flask_sslify import SSLify
    #     sslify = SSLify(app)

    db.init_app(app)
    migrate.init_app(app, db)
    login_manager.init_app(app)
    bootstrap.init_app(app)
    moment.init_app(app)
    mail.init_app(app)
    pagedown.init_app(app)

    # if app.config['SSL_REDIRECT']:
    #     from flask_sslify import SSLify
    #     sllify = SSLify(app)

    #if os.environ.get('DYNO'):
    #    app.config['SERVER_NAME'] = 'example.com'

    from application.errors import bp as errors_bp
    app.register_blueprint(errors_bp)
    from application.auth import bp as auth_bp
    app.register_blueprint(auth_bp, url_prefix="/auth")
    from application.main import bp as main_bp
    app.register_blueprint(main_bp)
    from application.api import bp as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix='/api_blueprint/v1')

    # Esimerkki: https://stackoverflow.com/questions/60549530/pytest-assertionerror-view-function-mapping-is-overwriting-an-existing-endpoin

    from application.api import get_blueprint

    api_bp_restful = get_blueprint()
    api = Api(api_bp_restful)

    from application.api.resources import AuthAPI, TaskListAPI, TaskCheckAPI, TaskAPI
    api.add_resource(AuthAPI, '/auth/tokens', endpoint='tokens')
    api.add_resource(TaskListAPI, '/tasks', endpoint='tasks')
    api.add_resource(TaskCheckAPI,
                     '/task_check/<int:id>',
                     endpoint='task_check')
    api.add_resource(TaskAPI, '/task/<int:id>', endpoint='task')

    app.register_blueprint(api_bp_restful, url_prefix="/api/v1")

    with app.app_context():
        #db.create_all()
        #from .db import init_db, init_db_command
        #init_db()
        #init_db()

        from application import models

        db.create_all()
        from application.models import Role
        Role.insert_roles()

        from application.models import TeamRole
        TeamRole.insert_roles()

        from application.models import Task
        Task.insert_boards()

        # Register blueprints
        # See https://hackersandslackers.com/flask-application-factory/

    return app
Esempio n. 21
0
 def setUp(self):
     db.create_all()
     test_task = Task(description="Test the flask app")
     db.session.add(test_task)
     db.session.commit()
Esempio n. 22
0
def insert_db():
    task = Task(name="富邦", classifer="理財")
    db.session.add(task)
    db.session.commit()
Esempio n. 23
0
 def get(self): 
     task = Task.find_by_id(1).json()
     return marshal(task,task_field)