def get(self, user): """ Get all unique locations for user. """ # find the approriate user with the id db_user = User.query.filter_by(id=user).first() if db_user is None: return create_error_response( 404, "Not found", "User not found" ) # response body with proper controls body = RouteBuilder() body.add_namespace("locations", LINK_RELATIONS_URL) body.add_control("self", url_for("api.locationcollection", user=user)) body.add_control_climbed_by(user) body.add_control_routes_all(user) body["items"] = [] # get the locations, and only return unique values for db_route in Route.query.filter_by(user=db_user).group_by(Route.locationId): item = RouteBuilder( location=db_route.location.name ) item.add_control("self", url_for("api.locationitem", user=user, location=db_route.locationId)) item.add_control_location_routes(user, db_route.locationId) item.add_control("profile", ROUTE_PROFILE) body["items"].append(item) return Response(json.dumps(body), 200, mimetype=MASON)
def get(self, user): """ Get information of specific user """ # test if user exists db_user = User.query.filter_by(id=user).first() if db_user is None: return create_error_response( 404, "Not found", "User not found" ) # build response body body = RouteBuilder( email=db_user.email, firstName=db_user.firstName, lastName=db_user.lastName ) body.add_namespace("users", LINK_RELATIONS_URL) body.add_control("self", url_for("api.useritem", user=user)) body.add_control("profile", USER_PROFILE) body.add_control_climbed_by(user) body.add_control_all_users() body.add_control_edit_user(user) body.add_control_edit_user(user) body.add_control_delete_user(user) body.add_control_routes_all(user) return Response(json.dumps(body), 200, mimetype=MASON)
def get(self, user, location): """ Get all routes in specific location for user. """ # find the approriate user with the id db_user = User.query.filter_by(id=user).first() if db_user is None: return create_error_response( 404, "Not found", "User not found" ) # test if location is found for user db_location = Route.query.filter(Route.user==db_user).filter(Route.locationId==location).first() if db_location is None: return create_error_response( 404, "Not found", "No location was found with the id {}".format(location) ) # response body with proper controls body = RouteBuilder() body.add_namespace("locations", LINK_RELATIONS_URL) body.add_control("self", url_for("api.locationitem", user=user, location=location)) body.add_control_climbed_by(user) body.add_control_routes_all(user) body.add_control_locations_all(user) body["items"] = [] # get the routes in the specific location for db_route in Route.query.filter(Route.user==db_user).filter(Route.locationId==location).all(): item = RouteBuilder( date=db_route.date.isoformat(), location=db_route.location.name, discipline=db_route.discipline.name, grade=db_route.grade.name, extraInfo=db_route.extraInfo ) item.add_control("self", url_for("api.routeitem", user=user, route=db_route.id)) item.add_control_edit_route(user, db_route.id) item.add_control_delete_route(user, db_route.id) item.add_control_discipline_routes(user, db_route.disciplineId) item.add_control_grade_routes(user, db_route.gradeId) item.add_control("profile", ROUTE_PROFILE) body["items"].append(item) return Response(json.dumps(body), 200, mimetype=MASON)
def put(self, user): """ Edit user information """ # test if user exists db_user = User.query.filter_by(id=user).first() if db_user is None: return create_error_response( 404, "Not found", "User not found" ) if not request.json: return create_error_response( 415, "Unsupported media type", "Requests must be JSON" ) try: validate(request.json, User.get_schema()) except ValidationError as err: return create_error_response(400, "Invalid JSON document", str(err)) # check that email is not just empty string if request.json["email"] == "": return create_error_response(400, "Email can not be empty.", "Email must contain characters.") # test if firstname and lastname given, these are optional parameters # both need to exist in order to read either if "firstName" in request.json and "lastName" in request.json: db_user.email=request.json["email"] db_user.firstName=request.json["firstName"] db_user.lastName=request.json["lastName"] else: db_user.email=request.json["email"] # try to commit to db try: db.session.commit() except IntegrityError: return create_error_response( 409, "Already exists", "Email '{}' is already taken.".format(request.json["email"]) ) return Response(status=204)
def post(self): """ Add a new user """ # check that the request is valid if not request.json: return create_error_response( 415, "Unsupported media type", "Requests must be JSON" ) # check that the request is correct against the schema try: validate(request.json, User.get_schema()) except ValidationError as err: return create_error_response(400, "Invalid JSON document", str(err)) # check that email is not just empty string if request.json["email"] == "": return create_error_response(400, "Email can not be empty.", "Email must contain characters.") # test if firstname and lastname given, these are optional parameters # both need to exist in order to read either if "firstName" in request.json and "lastName" in request.json: user = User( email=request.json["email"], firstName=request.json["firstName"], lastName=request.json["lastName"] ) else: user = User(email=request.json["email"]) # try to commit to db try: db.session.add(user) db.session.commit() except IntegrityError: return create_error_response( 409, "Already exists", "Email '{}' is already taken.".format(request.json["email"]) ) return Response(status=201, headers={"Location": url_for("api.useritem", user=user.id)})
def delete(self, user, route): """ Delete route """ # test if user exists db_user = User.query.filter_by(id=user).first() if db_user is None: return create_error_response(404, "Not found", "User not found") # test if route exists for this user db_route = Route.query.filter(Route.user == db_user).filter( Route.id == route).first() if db_route is None: return create_error_response( 404, "Not found", "No route was found with the id {}".format(route)) db.session.delete(db_route) db.session.commit() return Response(status=204)
def get(self, user, route): """ get information of specific route """ # test that user with the route exists db_user = User.query.filter_by(id=user).first() if db_user is None: return create_error_response(404, "Not found", "User not found") # test if route exists for this user db_route = Route.query.filter(Route.user == db_user).filter( Route.id == route).first() if db_route is None: return create_error_response( 404, "Not found", "No route was found with the id {}".format(route)) # response body with proper controls body = RouteBuilder(date=db_route.date.isoformat(), location=db_route.location.name, discipline=db_route.discipline.name, grade=db_route.grade.name, extraInfo=db_route.extraInfo) body.add_namespace("routes", LINK_RELATIONS_URL) body.add_control("self", url_for("api.routeitem", user=user, route=route)) body.add_control("profile", ROUTE_PROFILE) body.add_control_routes_all(user) body.add_control_climbed_by(user) body.add_control_edit_route(user, route) body.add_control_delete_route(user, route) body.add_control_location_routes(user, db_route.locationId) body.add_control_discipline_routes(user, db_route.disciplineId) body.add_control_grade_routes(user, db_route.gradeId) return Response(json.dumps(body), 200, mimetype=MASON)
def delete(self, user): """ Delete user """ # test if user exists db_user = User.query.filter_by(id=user).first() if db_user is None: return create_error_response( 404, "Not found", "User not found" ) db.session.delete(db_user) db.session.commit() return Response(status=204)
def get(self, user): """ Get all routes for user. """ # find the approriate user with the id db_user = User.query.filter_by(id=user).first() if db_user is None: return create_error_response(404, "Not found", "User not found") # response body with proper controls body = RouteBuilder() body.add_namespace("routes", LINK_RELATIONS_URL) body.add_control("self", url_for("api.routecollection", user=user)) body.add_control_climbed_by(user) body.add_control_routes_all(user) body.add_control_add_route(user) body.add_control_locations_all(user) body.add_control_disciplines_all(user) body.add_control_grades_all(user) body["items"] = [] # use user id to get the routes, and add them to list # functions even if there are no routes for db_route in Route.query.filter_by(user=db_user): item = RouteBuilder( date=db_route.date.isoformat(), # convert date to isoformat location=db_route.location.name, discipline=db_route.discipline.name, grade=db_route.grade.name, extraInfo=db_route.extraInfo) item.add_control( "self", url_for("api.routeitem", user=user, route=db_route.id)) item.add_control_edit_route(user, db_route.id) item.add_control_delete_route(user, db_route.id) item.add_control_location_routes(user, db_route.location.id) item.add_control_discipline_routes(user, db_route.discipline.id) item.add_control_grade_routes(user, db_route.grade.id) item.add_control("profile", ROUTE_PROFILE) body["items"].append(item) return Response(json.dumps(body), 200, mimetype=MASON)
def post(self, user): """ Add a new route """ # check that the request is valid if not request.json: return create_error_response(415, "Unsupported media type", "Requests must be JSON") try: validate(request.json, Route.get_schema()) except ValidationError as err: return create_error_response(400, "Invalid JSON document", str(err)) # check that user exists user_db = User.query.filter_by(id=user).first() if user_db is None: return create_error_response(404, "Not found", "User not found") # test if date is in the right format: YYYY-MM-DD # Adapted following documentation for datetime and stackoverflow suggestions date_string = request.json["date"] try: date = datetime.strptime(date_string, '%Y-%m-%d') except ValueError: return create_error_response( 400, "Wrong date format", "Date was not given in YYYY-MM-DD format.") # check that location, discipline and grade are not just empty strings if request.json["location"] == "": return create_error_response(400, "Entry can not be empty.", "Location must contain characters.") elif request.json["discipline"] == "": return create_error_response( 400, "Entry can not be empty.", "Discipline must contain characters.") elif request.json["grade"] == "": return create_error_response(400, "Entry can not be empty.", "Grade must contain characters.") # check if the location, discipline, or grade already exists. # use the already existing instance if they are found. location = db.session.query(Location).filter_by( name=request.json["location"]).first() if not location: location = Location(name=request.json["location"]) discipline = db.session.query(Discipline).filter_by( name=request.json["discipline"]).first() if not discipline: discipline = Discipline(name=request.json["discipline"]) grade = db.session.query(Grade).filter_by( name=request.json["grade"]).first() if not grade: grade = Grade(name=request.json["grade"]) # and test if extraInfo (optional) is given in the request and act accordingly if "extraInfo" in request.json: route = Route(user=user_db, date=date, location=location, discipline=discipline, grade=grade, extraInfo=request.json["extraInfo"]) else: route = Route(user=user_db, date=date, location=location, discipline=discipline, grade=grade) # commit to db db.session.add(route) db.session.commit() # get the ID of the just commited route route = route.id return Response(status=201, headers={ "Location": url_for("api.routeitem", user=user, route=route) })
def put(self, user, route): """ Edit route information """ # test if user exists db_user = User.query.filter_by(id=user).first() if db_user is None: return create_error_response(404, "Not found", "User not found") # test if route exists for this user db_route = Route.query.filter(Route.user == db_user).filter( Route.id == route).first() if db_route is None: return create_error_response( 404, "Not found", "No route was found with the id {}".format(route)) if not request.json: return create_error_response(415, "Unsupported media type", "Requests must be JSON") try: validate(request.json, Route.get_schema()) except ValidationError as err: return create_error_response(400, "Invalid JSON document", str(err)) # test if date is in the right format: YYYY-MM-DD date_string = request.json["date"] try: date = datetime.strptime(date_string, '%Y-%m-%d') except ValueError: return create_error_response( 400, "Wrong date format", "Date was not given in YYYY-MM-DD format.") # check that location, discipline and grade are not just empty strings if request.json["location"] == "": return create_error_response(400, "Entry can not be empty.", "Location must contain characters.") elif request.json["discipline"] == "": return create_error_response( 400, "Entry can not be empty.", "Discipline must contain characters.") elif request.json["grade"] == "": return create_error_response(400, "Entry can not be empty.", "Grade must contain characters.") # check if the location, discipline, or grade already exists, it it does # then use the already found one location = db.session.query(Location).filter_by( name=request.json["location"]).first() if not location: location = Location(name=request.json["location"]) discipline = db.session.query(Discipline).filter_by( name=request.json["discipline"]).first() if not discipline: discipline = Discipline(name=request.json["discipline"]) grade = db.session.query(Grade).filter_by( name=request.json["grade"]).first() if not grade: grade = Grade(name=request.json["grade"]) # and test if extraInfo (optional) is given in the request and act accordingly if "extraInfo" in request.json: db_route.user = db_user db_route.date = date db_route.location = location db_route.discipline = discipline db_route.grade = grade db_route.extraInfo = request.json["extraInfo"] else: db_route.user = db_user db_route.date = date db_route.location = location db_route.discipline = discipline db_route.grade = grade # commit db.session.commit() return Response(status=204)