def add_new_event_type(): event_type = request.form.get("eventType") label = request.form.get("label") unit = request.form.get("unit") user = get_user() invalid_message = validate_new_event_type(label) if invalid_message: return invalid_message if event_type == "habit": new_event_type = Habit(label=label, unit=unit, user_id=user.id) elif event_type == "influence": new_event_type = Influence(label=label, scale=unit, user_id=user.id) elif event_type == "symptom": new_event_type = Symptom(label=label, scale=unit, user_id=user.id) db.session.add(new_event_type) db.session.commit() if event_type == "habit": new_obj = Habit.query.filter(Habit.label == label, Habit.user == user).one() new_id = new_obj.id elif event_type == "influence": new_obj = Influence.query.filter(Influence.label == label, Influence.user == user).one() new_id = new_obj.id elif event_type == "symptom": new_obj = Symptom.query.filter(Symptom.label == label, Symptom.user == user).one() new_id = new_obj.id return json.dumps({ "new_id": new_id, "success": f"New {event_type} added successfully!" })
def habit_create(username: str): schema = Schema({ "name": And(str, len, error="Namr not specified"), "description": And(str, len, error="description not specified"), "num_Days": And(Use(int), error="Number of Days not specified"), "is_public": And(str, len, error="publicity not specified") }) form = { "name": request.form.get("name"), "description": request.form.get("description"), "num_Days": request.form.get("num_Days"), "is_public": request.form.get("is_public") } validated = schema.validate(form) temp_data = [] user = User.objects(username=username).first() for i in range(validated["num_Days"]): temp_data.append(["false", 0, 0]) habit = Habit( user=user, name=validated["name"], description=validated["description"], num_Days=validated["num_Days"], repeat=[], start_Date=datetime.now(), string_start=datetime.strftime( datetime.now(), "%B %m, %Y" ), #A list with the month in mm format and day in the dd format curr_Date=datetime.now(), end_Date=datetime.now() + timedelta(days=int(validated["num_Days"])), is_public=validated["is_public"], habit_data=temp_data).save() return jsonify(habit.to_public_json())
def handle_habits(habit_id=None): """ handle habits for an authenticated user """ headers = {"Content-Type": "application/json"} # grab user auth_user = get_current_user() # check methods if request.method == "GET": # check if habit_id is not none if habit_id: # return specific habit details specific_habit = Habit.query.filter_by(id=habit_id).one_or_none() response_body = specific_habit.serialize() else: # return all user habits user_habits = Habit.query.filter_by(user_id=auth_user.id).all() response_body = [] for habit in user_habits: response_body.append(habit.serialize()) status_code = 200 elif request.method == "POST": # create habit, validate input... new_habit_data = request.json if set(("name", "personalMessage", "targetPeriod", "targetValue", "iconName", "toBeEnforced")).issubset(new_habit_data): # all data is present new_habit_name = new_habit_data["name"] new_habit_message = new_habit_data["personalMessage"] new_habit_period = new_habit_data["targetPeriod"] new_habit_value = new_habit_data["targetValue"] new_habit_icon = new_habit_data["iconName"] new_habit_enforcement = new_habit_data["toBeEnforced"] if (new_habit_name and new_habit_message and new_habit_period and 0 < new_habit_value < 100 and new_habit_icon): # all values valid new_habit = Habit(new_habit_name, new_habit_message, new_habit_enforcement, new_habit_period, new_habit_value, new_habit_icon, auth_user.id) db.session.add(new_habit) try: db.session.commit() status_code = 201 result = f"HTTP_201_CREATED. habit successfully created with id: {new_habit.id}" response_body = {"result": result} except: db.session.rollback() status_code = 500 response_body = {"result": "something went wrong in db"} else: # some value is empty or invalid status_code = 400 response_body = { "result": "HTTP_400_BAD_REQUEST. received invalid input values..." } else: # some key is missing status_code = 400 response_body = { "result": "HTTP_400_BAD_REQUEST. some key is missing in request..." } elif request.method == "PUT": # only allowed if habit_id is not None if habit_id: habit_to_edit = Habit.query.filter_by(id=habit_id).one_or_none() if habit_to_edit: # editing habit with input habit_data = request.json if set( ("name", "personalMessage", "targetPeriod", "targetValue", "iconName", "toBeEnforced")).issubset(habit_data): # all data is present habit_to_edit.update(habit_data) try: db.session.commit() status_code = 200 response_body = { "result": "HTTP_200_OK. habit successfully updated" } except IntegrityError: print("some error on db saving op") db.session.rollback() status_code = 400 response_body = { "result": "HTTP_400_BAD_REQUEST. same user can't have two habits named the same!" } else: status_code = 400 response_body = { "result": "HTTP_400_BAD_REQUEST. check inputs, some key is missing, this is PUT method, all keys required..." } else: # oh boy, no such habit... status_code = 404 response_body = { "result": "HTTP_404_NOT_FOUND. oh boy, no such habit here..." } else: # what? no habit_id shouldn't even get in here status_code = 500 response_body = { "result": "HTTP_666_WTF. this should not be able to happen..." } elif request.method == "DELETE": # check if habit_id and delete if habit_id: habit_to_delete = Habit.query.filter_by(id=habit_id).one_or_none() if habit_to_delete: try: db.session.delete(habit_to_delete) db.session.commit() status_code = 204 response_body = {} except: # something went wrong in db committing print("dunno...") status_code = 500 response_body = { "result": "HTTP_500_INTERNAL_SERVER_ERROR. something went wrong on db..." } else: # habit does not exist... status_code = 404 response_body = { "result": "HTTP_404_NOT_FOUND. oh boy, no such habit here..." } else: status_code = 500 response_body = { "result": "HTTP_666_WTF. you should not be here..." } return make_response(json.dumps(response_body), status_code, headers)