Skip to content

Instantly share code, notes, and snippets.

@themaleem
Last active May 4, 2021 20:49
Show Gist options
  • Save themaleem/1a5da0a07d9575c4990cefe56fe98e82 to your computer and use it in GitHub Desktop.
Save themaleem/1a5da0a07d9575c4990cefe56fe98e82 to your computer and use it in GitHub Desktop.
# for pagination (create a new file)
def get_paginated_list(data, url, start, limit):
count = len(data)
# force numericalize start and limit
start = int(start)
limit = int(limit)
# build json response
obj = {}
obj["start"] = start
obj["limit"] = limit
obj["count"] = count
# previous page url
if start == 1:
obj["previous"] = ""
else:
start_copy = max(1, start - limit)
limit_copy = start - 1
obj["previous"] = url + "?start=%d&limit=%d" % (start_copy, limit_copy)
# next page url
if start + limit > count:
obj["next"] = ""
else:
start_copy = start + limit
obj["next"] = url + "?start=%d&limit=%d" % (start_copy, limit)
# slice json data according to start and limit bound
obj["data"] = data[(start - 1) : (start - 1 + limit)]
return obj
# import get_paginated_list
# GET all unis or POST a university
@app.route("/api/universities/", methods=["GET", "POST"])
def get():
if request.method == "GET":
universities = Universities
return jsonify(
get_paginated_list(
universities,
"/api/universities",
request.args.get("start", 1),
request.args.get("limit", 20),
)
)
else:
length_of_universities_list = len(Universities)
create_obj = {
"id": length_of_universities_list + 1,
"alpha_two_code": request.json["alpha_two_code"],
"country": request.json["country"],
"domain": request.json["domain"],
"name": request.json["name"],
"web_page": request.json["web_page"],
}
Universities.append(create_obj)
return jsonify(Universities)
# DELETE a university
@app.route("/api/university/<id>", methods=["DELETE"])
def delete_university(id):
university = (uni for uni in Universities if uni["id"] == float(id))
try:
Universities.remove(next(university))
return {"status": 204, "message": "no content"}
except StopIteration:
return {
"status": 404,
"message": "University matching that id was not found or something",
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment