def postTodos(): # get body body = request.get_json() # instancia modelo Todos y se inicializa con el valor del body todo = Todos(body["label"], body["is_done"]) # guardar task en base datos todo.save() return jsonify(todo.serialize()), 200
def post_todos(): body = request.get_json() if 'done' not in body: return 'Invalid todo', 400 if 'label' not in body: return 'Invalid todo', 400 todo = Todos(done=body['done'], label=body['label']) db.session.add(todo) db.session.commit() return jsonify(todo.serialize()), 200
def create_todos(): response = request.get_json() if 'done' not in response: return 'Invalid', 400 if 'label' not in response: return 'Invalid', 400 row = Todos(done=response['done'], label=response['label']) db.session.add(row) db.session.commit() return jsonify(row.serialize()), 200
def todos(request, todo_id=None): """ GET: return all the Todos POST: create a new todo """ if request.method == 'GET': if todo_id: # find the specific todo and return it todo = Todos.objects.get(id=todo_id) return HttpResponse(status=200, content=jsonifyTodo(todo), mimetype='application/json') else: todos = Todos.objects.all() ret_data = [] for todo in todos: pretty_todo(todo) ret_data.append({ 'id': todo.id, 'title': todo.title, 'completed': todo.completed }) return HttpResponse(json.dumps(ret_data), mimetype='application/json') elif request.method == 'POST': # create a new todo data = json.loads(request.body) new_todo = Todos() new_todo.title = data['title'] new_todo.completed = ugly_completed(data['completed']) new_todo.save() return HttpResponse(status=201, content=jsonifyTodo(new_todo)) elif request.method == 'PUT': # mark the todo as completed data = json.loads(request.body) todo = Todos.objects.get(id=todo_id) todo.completed = ugly_completed(data['completed']) todo.save() return HttpResponse(status=200, content=jsonifyTodo(todo)) elif request.method == 'DELETE': # delete the todo todo = Todos.objects.get(id=todo_id) todo.delete() return HttpResponse(status=204)
def add_todo(): # recibir info del request request_body = request.get_json() print(request_body) if not request_body: return jsonify("El JSON no puede venir vacio"), 404 todo = Todos() todo.done = False todo.label = request_body['label'] # label=request_body["label"], done=False db.session.add(todo) db.session.commit() return jsonify("All good"), 200
def saveTodos(): if not request.is_json: abort(400, description="Missing JSON in request") current_user = get_jwt_identity() user = db.session.query(User).filter(User.email == current_user).first() if user: try: num_rows_deleted = db.session.query(Todos).filter( Todos.user_id == user.user_id).delete() content = request.get_json() for todo in content: todo_title = todo['todo_title'] todo_body = todo['todo_body'] completed = todo["completed"] created_at = todo["created_at"] completed_at = todo["completed_at"] todoModel = Todos(user_id=user.user_id, todo_title=todo_title, todo_body=todo_body, completed=completed, completed_at=completed_at, created_at=created_at) db.session.add(todoModel) db.session.commit() return jsonify({'message': 'Saved successfully', 'todo': content}) except Exception: abort(500) else: abort(401, description="You are not allowed to visit this page")
def handle_todos(): """ Create todos and retrieve all todoss """ # POST request 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 the label', status_code=400) if 'done' not in body: raise APIException('You need to specify the done', status_code=400) user1 = Todos(label=body['label'], done=body['done']) db.session.add(user1) db.session.commit() return "ok", 200 # GET request if request.method == 'GET': all_people = Todos.query.all() all_people = list(map(lambda x: x.serialize(), all_people)) return jsonify(all_people), 200 return "Invalid Method", 404
def post(self): try: #获取入参 args = json_decode(self.request.body) phone = args['phone'] todo = args['todo'] except: # 获取入参失败时,抛出错误码及错误信息 logger.info("NewTodoHandle: request argument incorrect") http_response(self, ERROR_CODE['1001'], 1001) return if len(phone) == 0 or len(todo) == 0: logger.debug("NewTodoHandle: request argument incorrect") http_response(self, ERROR_CODE['1001'], 1001) return #用户不存在,数据库表中插入用户信息 logger.debug("NewTodoHandle: insert db, todo: %s" % todo) create_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') add_todo = Todos(phone, todo, create_time) self.db.add(add_todo) self.db.commit() self.db.close() # 处理成功后,返回成功码“0”及成功信息“ok” logger.debug("NewTodoHandle: add successfully") http_response(self, ERROR_CODE['0'], 0)
def POST(self): data = web.data() todo = json.loads(data) # 转换成_order, order是数据库关键字, sqlite3报错 todo['_order'] = todo.pop('order') generated_id = Todos.create(**todo) return json.dumps({"id": generated_id})
def add_todos(): request_body = request.get_json() todos = Todos(done=request_body["done"],label=request_body["label"]) db.session.add(todos) db.session.commit() return jsonify("Se ha agregado correctamente"), 200
def handler(input1=None): if request.method == "GET": if input1 is not None: todos = Todos.query.filter_by(name=input1).first() if todos: return jsonify(todos.serialize()), 200 else: return jsonify({"msg": "Not Found"}), 404 else: todos = Todos.query.all() todos = list(map(lambda todos: todos.serialize(), todos)) return jsonify(todos), 200 if request.method == "POST": if not input1 or input1 == "": # si no llego un nombre o el nombre esta vacio return {"msg": "Field name is required"}, 400 # 422 todo = Todos() todo.name = input1 db.session.add(todo) db.session.commit() todos = Todos.query.all() todos = list(map(lambda todos: todos.serialize(), todos)) return jsonify(todos), 200 if request.method == "PUT": if not input1 or input1 == "": # si no llego un nombre o el nombre esta vacio return {"msg": "Field name is required"}, 400 # 422 todos = Todos.query.filter_by(name=input1).first() newName = request.json.get("newName") if not newName or newName == "": return {"msg": "newName missing"}, 400 todo.name = newName db.session.commit() return jsonify(todo.serialize()), 200 # 422 if request.method == "DELETE": if not input1 or input1 == "": # si no llego un nombre o el nombre esta vacio return {"msg": "Field name is required"}, 400 # 422 todos = Todos.query.filter_by(name=input1).first() if not todos: return {"msg": "Not Found"}, 400 db.session.delete(todos) db.session.commit() todos = Todos.query.all() todos = list(map(lambda todos: todos.serialize(), todos)) return jsonify(todos), 200
def handle_add(): body = request.get_json() todo = Todos(text=body['text']) db.session.add(todo) db.session.commit() return 'ok', 200
def post_todo(): request_body = request.get_json() fav = Todos(label=request_body["label"], done=request_body["done"]) db.session.add(fav) db.session.commit() return jsonify("Added!"), 200
def add_todo(): request_body = request.get_json() new_todo = Todos(todo=request_body["todo"]) db.session.add(new_todo) db.session.commit() return jsonify("La tarea fue agregada de manera satisfactoria"), 200
def updateTodo(id): #get todo guardado en base de datos con id='x' todo = Todos.getId(id) #get body nuevo para actualizar todo body = request.get_json() todo.updateTodo(body) #guardar todo updated en base datos todo.save() return jsonify(todo.serialize()), 200
def GET(self, todo_id=None): result = None todo = Todos.get_by_id(id=todo_id) result = { "id": todo.id, "title": todo.title, "order": todo._order, "done": todo.done == 1, } return json.dumps(result)
def create(hashid, todo): schema = TodosSchema() new_task = Todos(task=todo['task'], completed=todo['completed'], person_hash=hashid) db.session.add(new_task) db.session.commit() data = schema.dump(new_task) return data, 201
def GET(self): todos = [] itertodos = Todos.get_all() for todo in itertodos: todos.append({ "id": todo.id, "title": todo.title, "order": todo._order, "done": todo.done == 1, }) return json.dumps(todos)
def add_tod(): # recibir info del request request_body = request.get_json() print(request_body) tod = Todos(done=request_body["done"], label=request_body["label"]) db.session.add(tod) db.session.commit() return jsonify("All good"), 200
def handle_todo(): #GET if request == "GET": todo = Todos.query.all(todo_id) todoList = list(map(lambda x: x.serialize(), todo)) return jsonify(todo.serialize()), 200 #POST if request.method == "POST": body = request.get_json() todo = Todos(text=body['text']) db.session.add(todo) db.session.commit() response_body = { "status": "Successfully added.", "todo": todo.serialize(), "repr": repr(todo) } return jsonify(response_body), 205
def add_todo(): if request.method == 'POST': category = request.form['category'] description = request.form['description'] if category and (len(str(description).strip()) != 0): newTodo = Todos(member_username=current_user.username, category=category, description=description, completed=False) db.session.add(newTodo) db.session.commit() todos = getTodos() return redirect(url_for('todos', todos=todos)) else: flash('Please enter complete details', 'danger') return render_template('add_todo.html') else: return render_template('add_todo.html')
def POST(self): data = web.data() todo = json.loads(data) # 转换成_order, order是数据库关键字, sqlite3报错 todo['_order'] = todo.pop('order') Todos.create(**todo)
def add_todo(request): session = Session() todo = Todos(todo=request.todo, note=request.note, status=request.status) session.add(todo) session.commit() return todo
def getTodos(): #get todos los datos de la base de datos. tasks = Todos.get_all() # devuelve el array de elementos serializado return jsonify_array(tasks), 200
def DELETE(self, todo_id=None): Todos.delete(id=todo_id)
def deleteTodo(id): #get todo guardado en base de datos con id='x' todo = Todos.getId(id) todo.delete() return jsonify(todo.serialize()), 200
def PUT(self, todo_id=None): data = web.data() todo = json.loads(data) todo['_order'] = todo.pop('order') Todos.update(**todo)
def POST(self): data = web.data() todo = json.loads(data) todo['_order'] = todo.pop('order') Todos.create(**todo)
'person_hash': '6b21cf3f2043a0c0c7e2b02c792fe18e' }, { 'task': 'Determine location (note limitations)', 'completed': False, 'person_hash': '6b21cf3f2043a0c0c7e2b02c792fe18e' }, ] # Delete database file if it exists currently if os.path.exists('taskerdb.db'): os.remove('taskerdb.db') # Create the database db.create_all() # Add new data to the database for person in PEOPLE: p = Guard(hash_id=person['hash_id'], username=person['username'], fullname=person['fullname']) db.session.add(p) for t in TASK: p = Todos(task=t['task'], completed=t['completed'], person_hash=t['person_hash']) db.session.add(p) db.session.commit()
def handle_hello(username): # Case: GET REQUEST if request.method == "GET": # query a user by username and store it in the user var # user should only ever return one result because the username is unique # but we will return only the .first() instead of .all() anyway user = User.query.filter_by(username=username).first() # if user is not empty, meaning query returned something # we set the response_body to the serialized version if user is not None: response_body = user.serialize_todos() response_status_code = 200 else: response_body = 'User was not found. Please check the username and try again.' response_status_code = 404 # Case: POST REQUEST elif request.method == "POST": body = request.get_json() # Get body from request as JSON # Test to see if the client app sent a request with empty array in body if isinstance(body, list): user = User() # user is an instance of the User model user.username = username # set username to the username from the api path variable <username> # we dont need to set id because it is automatically generated # we also don't need to set todos because it is by nature a list. Comes from a 1 to n relationship to Todos() class db.session.add(user) # add the new user via db.session db.session.commit() # commit changes # next, we will define what the response should be and the status code # this will be returned at the end of our function so that we don't have to repeat the return response_body = {"result": "ok"} response_status_code = 200 # Case: PUT REQUEST elif request.method == "PUT": body = request.get_json() # Get body from request as JSON if isinstance(body, list): # loop the list in body for todo in body: # make sure the todo we are looking at isn't empty if todo is not None: try: todo_item = Todos() # instantiate a new Todo() user = User.query.filter_by( username=username).first() # query the user # set label, done, and user_id field for the new todo todo_item.label = todo['label'] todo_item.done = todo['done'] todo_item.user_id = user.id db.session.add(todo_item) # add the current todo db.session.commit() # commit the change except Exception as e: return jsonify(f"An Error Occured: {e}") # set response body and status code response_body = { "result": "A list with %r todos was succesfully saved" % len(body) } response_status_code = 200 # Case: DELETE REQUEST elif request.method == "DELETE": try: user = User.query.filter_by( username=username).first() # get user by username todos = Todos.query.filter_by( user_id=user.id).all() # get todos for given username # loop todos list for item in todos: db.session.delete( item ) # delete each todo related to the current user from the list db.session.delete(user) # delete the selected user db.session.commit() # commit the changes # set the response body and status_code response_body = {"result": "ok"} response_status_code = 200 except Exception as e: return jsonify(f"An Error Occured: {e}") return jsonify(response_body), response_status_code