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" })
def handle_todo(self, message): raw, content = self.get_content(message) for todo_text in [s.lstrip(" -").strip() for s in content.split("\n")]: todo = ToDo(author='Julian', category=message.subject.lower(), content=todo_text) todo.put()
def setUp(self): app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['DEBUG'] = False self.app = app.test_client() DATABASE.connect() DATABASE.create_tables([User, ToDo], safe=True) try: self.user1 = User.create_user( username='******', email='*****@*****.**', password='******' ) except: pass try: with open('mock/todos.json') as mocktodos: json_reader = json.load(mocktodos) for todo in json_reader: ToDo.create( created_by=1, **todo ) except Exception as err: print(err) pass
def create(self, validated_data): """ Create and return a new ToDo instance, given the validated data. """ todo = ToDo() todo.text = validated_data.get('text', todo.text) todo.updated_by = validated_data.get('updated_by', todo.updated_by) todo.updated_at = utc.localize(datetime.utcnow()) return 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')
def get(self): enforce_key(self) todos = [t.to_dict() for t in ToDo.all().order('-creation_time')] self.response.headers['Content-Type'] = "application/json" self.response.headers['Content-Disposition'] = ( "attachment; filename=todos.json") self.response.out.write(json.dumps(todos))
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"))
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
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
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')
def post(self): enforce_key(self) rawEntries = self.request.get("entries") entries = json.loads(rawEntries) for e in Entry.all(): e.delete() for e in entries: newEntry = Entry() newEntry.from_json(e) newEntry.put() rawTodos = self.request.get("todos") todos = json.loads(rawTodos) for t in ToDo.all(): t.delete() for t in todos: newToDo = ToDo() newToDo.from_json(t) newToDo.put() self.response.out.write("Backup successfuly restored.")
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)
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)
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
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 get(self): todos = defaultdict(list) for t in ToDo.all().filter('done_time =', None).order('-creation_time'): todos[t.category].append(t) for t in ToDo.all().filter('done_time >', datetime.datetime.now() - datetime.timedelta(days=7)): todos[t.category].append(t) body_text = "" for category, items in todos.iteritems(): body_text += "<h2>%s</h2>\n<ul class='todo'>" % category for t in items: if t.done_time: body_text += "\t<li class='done'>%s</li>\n" % t.content else: body_text += "\t<a href='/todo/finish/%s'><li>%s</li></a>\n" % ( t.key(), t.content) body_text += "</ul>" self.response.out.write(indexTemplate.render({ 'title': 'To-Do', 'body': body_text, 'active_page': 'todo' }))
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', {})
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)
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)
def lambda_handler(event, context): """ crud lambda application... """ db = config("MONGO_DB") host = config("MONGO_HOST") conn = mongoengine.connect(host=host, db=db) headers = { "Content-Type": "application/json", "Access-Allow-Credentials": "false", "Access-Control-Allow-Headers": "Content-Type", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "POST,GET,PUT,DELETE,OPTIONS", "Access-Control-Max-Age": "86400", } method = event["httpMethod"] path = event["path"] filter_paths = [ "/get_by_status", "/get_by_owner", "/get_by_list", "/get_by_user", "/get_by_access" ] status = {"get": 200, "post": 200, "put": 200, "delete": 200} body = event["body"] f = json.loads(body) if body else {} querystring_parameters = (event["queryStringParameters"] if event["queryStringParameters"] else {}) if method == "OPTIONS": return {"statusCode": 204, "headers": headers} if path in filter_paths: return filters.lambda_handler(event, context) if path == "/todolist" or path == "/add_user": return app_todolist.lambda_handler(event, context) if method == "GET": if "id" in querystring_parameters.keys(): message = (ToDo.objects( id=ObjectId(querystring_parameters["id"])).first().serialize()) else: message = [i.serialize() for i in ToDo.objects.all()] if method == "POST": try: deadline = [int(i) for i in f["deadline"].split("-")] deadline = date(year=deadline[0], month=deadline[1], day=deadline[2]) ToDo.objects.create( name=f["name"], description=f["description"], owner=f["owner"], todolist=f["todolist"], assignment=f["assignment"], created_at=datetime.now(), last_update={ "user": f["owner"], "date": datetime.now() }, deadline=deadline, notification=deadline - timedelta(days=3), attachments=f["attachments"], status=None, ).save() message = [ToDo.objects(name=f["name"]).first().serialize()] except (ValidationError, KeyError): return { "statusCode": 500, "headers": headers, "body": json.dumps("Invalid request body"), } elif method == "PUT": try: _id = ObjectId(querystring_parameters["id"]) obj = ToDo.objects(id=_id).first() d = obj.last_update # d["user"] = f["user"] d["date"] = datetime.now() # f.pop("user") f["last_update"] = d obj.update(**f) d["todo"] = str(obj.pk) ToDoList.objects(id=ObjectId(obj.todolist)).update(last_update=d) obj = ToDo.objects(id=_id).first() message = obj.serialize() except (ValidationError, KeyError) as e: return { "statusCode": 500, "headers": headers, "body": json.dumps(e) } elif method == "DELETE": _id = ObjectId(querystring_parameters["id"]) ToDo.objects(id=_id).first().delete() message = "Object deleted successfully" return { "headers": headers, "statusCode": status[method.lower()], "body": json.dumps(message), }
def lambda_handler(event, context): """ crud lambda application... """ headers = { "Content-Type": "application/json", "Access-Allow-Credentials": "false", "Access-Control-Allow-Headers": "Content-Type", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "POST,GET,PUT,DELETE,OPTIONS", "Access-Control-Max-Age": "86400", } filters = { "/get_by_list": "todolist", "/get_by_owner": "owner", "/get_by_status": "status", "/get_by_user": "******", "/get_by_access": "access", } path = event["path"] querystring_parameters = event["queryStringParameters"] query_filter = querystring_parameters[filters[path]] if filters[path] == "todolist": queryset = ToDo.objects(todolist=query_filter).all() elif filters[path] == "owner": owner = query_filter.lower() if "list" in querystring_parameters.keys(): list_mode = querystring_parameters["list"].lower() == "true" queryset = (ToDoList.objects(owner=owner).all() if list_mode else ToDo.objects(owner=owner).all()) else: queryset = list(ToDoList.objects(owner=owner).all()) + list( ToDo.objects(owner=owner).all()) elif filters[path] == "user": queryset = ToDoList.objects(owner=query_filter).all() tmp = ToDoList.objects.all() contrib = list( filter( lambda x: query_filter in x.access["contributors"] or query_filter in x.access["readers"], tmp, )) queryset = list(queryset) + contrib elif filters[path] == "access": raw_data = ToDoList.objects.all( ) # raw_data é a coleção de todos as listas username = querystring_parameters["username"].lower( ) # username é um param que passamos if query_filter == "all": processed_data = { "reader": [ todolist.serialize() for todolist in list( filter( lambda x: username in x.access["readers"], raw_data, )) ], "contributor": [ todolist.serialize() for todolist in list( filter( lambda x: username in x.access["contributors"], raw_data, )) ], } else: processed_data = [ x.serialize() for x in list( # se o parametro for qualquer outra coisa, ele vai procurar dentro de access pelo nome no param filter( lambda x: username in x.access[ query_filter ], # isso diminui o tamanho da prog e tb deixa aberto pra novas roles, caso aconteça raw_data, )) ] return {"statusCode": 200, "headers": headers, "body": processed_data} else: status = query_filter.lower() if "list" in querystring_parameters.keys(): list_mode = querystring_parameters["list"].lower() == "true" queryset = (ToDoList.objects(status=status).all() if list_mode else ToDo.objects(status=status).all()) else: queryset = list(ToDoList.objects(status=status).all()) + list( ToDo.objects(status=status).all()) queryset = [x.serialize() for x in queryset] return { "statusCode": 200, "headers": headers, "body": json.dumps(queryset, ), }
def get(self, key): t = ToDo.get(key) t.done_time = datetime.datetime.now() t.put() self.redirect('/todo?refresh')