Exemple #1
0
def update(username):
    user = User.query.filter_by(username=username).first()
    if not user:
        return jsonify({'error': 'User does not exist'}), 404

    request_body = request.json
    if type(request_body) != list or len(request_body) == 0:
        return jsonify({
            'error':
            'The request body must be an array with at least one task'
        }), 400

    for task in user.todos:
        task.query.delete()

    for task in request_body:
        todo = ToDo()
        todo.label = task['label']
        todo.done = task['done']
        todo.user_id = user.id
        db.session.add(todo)

    db.session.commit()

    return jsonify({
        "result":
        "A list with " + str(len(user.todos)) + " todos was succesfully saved"
    })
Exemple #2
0
def add_thing():
    if session['logged_in']:
        user = User.query.filter_by(name=session['user_name']).first()
        things = ToDo.query.filter_by(owner_id=user.id).all()
        if len(request.form['title']) > 0 and len(request.form['content']) > 0:
            new_thing = ToDo(owner_id=user.id,
                             title=request.form['title'],
                             content=request.form['content'])
            try:
                database.session.add(new_thing)
                database.session.commit()

                mycursor = db.mydb_u.cursor()
                mycursor.execute(
                    f"INSERT INTO `{user.name}` (todo_id, owner, title, content) VALUES (NULL, '{user.name}', '{new_thing.title}', '{new_thing.content}')"
                )
                db.mydb_u.commit()
                mycursor.close()

                return redirect(url_for("home.home"))
            except Exception:
                return render_template("database_error.html")
        else:
            error = "Cannot be empty"
            return render_template("profile.html",
                                   error=error,
                                   name=session['user_name'],
                                   things=things)
    else:
        return redirect(url_for("home.home"))
Exemple #3
0
def handle_todo():

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

        if body is None:
            raise APIException(
                "You need to specify the request body as a json object",
                status_code=400)
        if "label" not in body:
            raise APIException("You need to specify a todo", status_code=400)

        todo1 = ToDo(label=body["label"], done=body["false"])
        db.session.add(todo1)
        db.session.commit()

        return "Ok", 200

    #Get Request
    if request.method == "GET":

        all_todo = ToDo.query.all()
        all_todo = list(map(lambda x: x.serialize(), all_todo))
        return jsonify(all_todo), 200

    return "Invalid Method", 404
Exemple #4
0
    def post(self):
        data = request.get_json()

        todo = ToDo()
        todo.title = data.get('title')
        todo.notes = data.get('notes')
        todo.deadline = data.get('deadline')
        todo.tag = data.get('tag')

        todo.save()

        return 'Succeed to add task.', 201
Exemple #5
0
    def post(self):
        id = request.form['id']
        title = request.form['title']
        description = request.form['description']

        try:
            new_todo = ToDo(id, title, description)
            db.session.add(new_todo)
            db.session.commit()
        except exc.SQLAlchemyError:
            abort(400, description= f"An Todo Item with the ID, '{id}' already exists")

        return todo_schema.jsonify(new_todo)
Exemple #6
0
def tasks():
    '''
	tasks page
	this is where tasks are displayed
	this method also takes the info from
	update and updates the task information
	'''
    global loggedIn
    global username
    global taskToUpdate

    someUser = User.query.filter_by(username=username).first()

    # if not logged in, send user to login page
    if loggedIn == False:
        return redirect(url_for("login"))

    # there are 2 cases in which we obtain a POST method in
    # task: 1) we are adding a new task to our ToDo list and
    # 2) we are updating a post with new info
    if request.method == 'POST':
        if taskToUpdate == None:
            description = request.form['description']
            due_date = request.form['due_date']
            new_item = ToDo(description=description,
                            due_date=due_date,
                            username=username)
            db.session.add(new_item)
            db.session.commit()
        else:
            update_description = request.form['update_description']
            update_due_date = request.form['update_due_date']
            if update_description != "":
                taskToUpdate.description = update_description
                db.session.commit()

            if update_due_date != "":
                taskToUpdate.due_date = update_due_date
            db.session.merge(taskToUpdate)
            db.session.commit()
            taskToUpdate = None

    tasks = ToDo.query.filter_by(username=username, is_complete=0).all()
    completed_tasks = ToDo.query.filter_by(username=username,
                                           is_complete=1).all()

    return render_template("tasks.html",
                           name=someUser.name,
                           ToDoList=tasks,
                           CompletedList=completed_tasks)
Exemple #7
0
def addtodo():
    todo_title = request.form.get("todo_title")

    if todo_title:
        todo = ToDo(title=todo_title, user_id=session["user"].id)
        db.session.add(todo)
        db.session.commit()

        return jsonify({
            "id": todo.id,
            "title": todo.title,
            "status": "Completed" if todo.status == 1 else "Pending"
        })
    else:
        return "Title is required to add a ToDo"
def add_problem(request, patient_id):
    role = UserProfile.objects.get(user=request.user).role
    authenticated = True if (role == 'physician' or role == 'admin') else False
    if 'problem_name' in request.POST:
        problem = Problem(patient=User.objects.get(id=patient_id),
                          problem_name=request.POST['problem_name'],
                          concept_id=request.POST['concept_id'],
                          authenticated=authenticated)
        problem.save()
    elif 'goal' in request.POST:
        goal = Goal(patient=User.objects.get(id=patient_id),
                    goal=request.POST['goal'])
        goal.save()
    elif 'todo' in request.POST:
        # print 'todo'
        # print request.POST
        todo = ToDo(patient=User.objects.get(id=patient_id),
                    todo=request.POST['todo'])
        todo.save()
    return HttpResponse('added')
Exemple #9
0
def create_todo(req):
    if req.session.get('mail'):
        user = models.User.objects.filter(mail=req.session.get('mail')).first()
        if req.method == 'POST':
            tdf = ToDoForm(req.POST)
            if tdf.is_valid():
                title = tdf.cleaned_data['title']  # 获取form表单中的值
                content = tdf.cleaned_data['content']
                date = tdf.cleaned_data['date']
                todo = ToDo()
                todo.title = title
                todo.content = content
                todo.date = date
                todo.user = user
                todo.save()
                return HttpResponseRedirect('/todo_list/')
        else:
            return render(req, 'create_todo.html')
    else:
        return render_to_response('login.html', {})
Exemple #10
0
def add_todo():
    user_id = current_user.id
    task = request.form.get("task").strip()
    due_date_str = request.form.get("dueDate")

    due_date = dt.datetime.strptime(due_date_str, "%Y-%m-%d")

    new_todo = ToDo(task=task, user_id=user_id, due_date=due_date)
    db.session.add(new_todo)

    try:
        db.session.commit()
    except exc.SQLAlchemyError:
        return jsonify({"success": False})

    # Update user's todo order
    todo_order = json.loads(current_user.todo_order)
    todo_order.append(str(new_todo.id))
    current_user.todo_order = json.dumps(todo_order)

    try:
        db.session.commit()
    except exc.SQLAlchemyError:
        # If unable to update user table,
        # delete new todo, throw error to user
        db.session.delete(new_todo)
        db.session.commit()
        return jsonify({"success": False})

    return_data = {
        "success": True,
        "todo": {
            "id": new_todo.id,
            "task": new_todo.task,
            "dueDate": friendly_date(new_todo.due_date),
            "completed": new_todo.completed,
        },
    }

    return jsonify(return_data)
Exemple #11
0
def create_todo():
    error = False
    body = {}
    try:
        description = request.get_json()['description']
        list_id = request.get_json()['list_id']
        todo = ToDo(description=description, list_id=list_id)
        db.session.add(todo)
        db.session.commit()
        body['description'] = todo.description
    except:
        db.session.rollback()
        error = True


#        print(sys.exc_info())
    finally:
        db.session.close()
    if error:
        abort(400)
    else:
        return jsonify(body)
Exemple #12
0
def create(username):
    request_body = request.json
    if request_body != []:
        return jsonify({'error': 'Request body must be an empty array'}), 400

    user = User.query.filter_by(username=username).first()
    if user:
        return jsonify({'error': 'User already exists'}), 422

    user = User()
    user.username = username

    db.session.add(user)
    db.session.commit()

    todo = ToDo()
    todo.label = 'sample task'
    todo.done = False
    todo.user_id = user.id

    db.session.add(todo)
    db.session.commit()

    return jsonify({'result': 'ok'}), 201