Skip to content

Instantly share code, notes, and snippets.

@angstwad
Last active June 2, 2021 23:11
Show Gist options
  • Save angstwad/702118245b94469e066993c8e02fe201 to your computer and use it in GitHub Desktop.
Save angstwad/702118245b94469e066993c8e02fe201 to your computer and use it in GitHub Desktop.
todo flask app
# Import Flask, Jsonify and Requests
from flask import Flask, jsonify, request
# Create the web applicatiion via Flask
app = Flask(__name__)
# Existing To-Do List
# it's easiest to manipulate if this is a dict where key is the id and value is the todo
todos = {
1: "Buy Hitman 3",
2: "Play Saints Row IV with friends (Xbox)",
3: "Watch 'Last Kids on Earth'",
4: "Read 'Mastery' by Robert Greene"
}
# Get, Post and Delete Requests
@app.route("/todo", methods=["GET", "POST"])
def todo():
# Post Request, post a todo to exisiting list
if request.method == 'POST':
new_id = max(todos.keys()) + 1 # generates a new ID
todos[new_id] = request.json['todo'] # puts the todo into dict
return jsonify({'status': 'created', 'id': new_id}) # returns status
# Get Request, Returning a list of all todos and their IDs
elif request.method == 'GET':
return jsonify(todos)
# Delete Request, deletes a single todo by ID
@app.route("/todo/<int:id_>", methods=["GET", "DELETE"])
def get_todo(id_):
if request.method == 'DELETE':
del todos[id_] # deletes from todos dict
return jsonify({"status": "deleted"}) # success, let's return status
# Get Request, Returning the data of a single todo by ID
elif request.method == "GET":
# return by ID or delete
return jsonify({id_: todos[id_]}) # gets object by ID
if __name__ == "__main__":
app.run(port=5000, debug=True)
# Import necessary objects
from flask import Flask, jsonify, request
# Initialize app
app = Flask(__name__)
# Existing todos
todos = {}
# Post, GET requests
@app.route("/todo", methods=["GET", "POST"])
def todo():
if request.method == "POST":
try:
new_id = max(todos.keys()) + 1 # Generate new ID
except ValueError: # todos is empty
new_id = 0
try:
todos[new_id] = request.json["todo"] # Put todo in dict
except KeyError:
resp = jsonify({"status": "error", "error": "missing key 'todo'"})
resp.status_code = 400
return resp
# Exception error
return jsonify({"Status": "Created", "id": new_id}) # Return status of task with ID
elif request.method == "GET":
try:
return jsonify(todos) # Get all todos and post todo to an existing list
except ValueError: # invalid json
jsonify({"Status": "failed to jsonify todos"}) # KeyError Exception
# DELETE, GET requests
@app.route("/todo/<int:id_>", methods=["GET", "DELETE"])
def single_todo(id_):
if request.method == "DELETE":
try:
del todos[id_] # Deletes a single todo by ID
return jsonify({"Status": "Deleted"}) # Return status of item
except Exception:
return jsonify({"Status": "Item does not exist"}) # KeyError Exception
elif request.method == "GET":
try:
return jsonify({id_: todos[id_]})
except Exception:
return jsonify({"Status": "Item does not exist"}) # KeyError Exception
# Run app
if __name__ == "__main__":
app.run(port=5000, debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment