Skip to content

Instantly share code, notes, and snippets.

@LordGhostX
Created June 7, 2021 13:16
Show Gist options
  • Save LordGhostX/cbc378f15c2a3b8798373ab2a6d8b6d9 to your computer and use it in GitHub Desktop.
Save LordGhostX/cbc378f15c2a3b8798373ab2a6d8b6d9 to your computer and use it in GitHub Desktop.
Todo Demo for Flask RESTful
from flask import Flask
from flask_restful import Api, Resource, reqparse, fields, marshal_with, abort
app = Flask(__name__)
api = Api(app)
TODOS = {}
parser = reqparse.RequestParser()
parser.add_argument(
"task",
type=str,
help="Todo task must be a valid string",
location="form",
required=True
)
todo_resource_fields = {
"todo_id": fields.Integer,
"task": fields.String,
"uri": fields.Url("todo")
}
todo_list_resource_fields = {
"todos": fields.List(
fields.Nested({
"todo_id": fields.Integer,
"task": fields.String
})
),
"uri": fields.Url("todo_list")
}
def abort_if_todo_not_exist(todo_id):
if todo_id not in TODOS:
abort(404, message=f"Todo {todo_id} does not exist!")
class TodoDao(object):
def __init__(self, todo_id, task):
self.todo_id = todo_id
self.task = task
class TodoListDao(object):
def __init__(self, todos):
self.todos = todos
class HelloWorld(Resource):
def get(self):
return {"hello": "world"}
class Todo(Resource):
@marshal_with(todo_resource_fields)
def get(self, todo_id):
abort_if_todo_not_exist(todo_id)
return TodoDao(todo_id=todo_id, task=TODOS.get(todo_id)), 200
@marshal_with(todo_resource_fields)
def put(self, todo_id):
args = parser.parse_args()
TODOS[todo_id] = args.get("task")
return TodoDao(todo_id=todo_id, task=TODOS.get(todo_id)), 201
def delete(self, todo_id):
abort_if_todo_not_exist(todo_id)
del TODOS[todo_id]
return {}, 204
class TodoList(Resource):
@marshal_with(todo_list_resource_fields)
def get(self):
return TodoListDao([{"todo_id": i, "task": TODOS.get(i)} for i in TODOS]), 200
@marshal_with(todo_resource_fields)
def post(self):
args = parser.parse_args()
todo_id = len(TODOS)
TODOS[todo_id] = args.get("task")
return TodoDao(todo_id=todo_id, task=TODOS.get(todo_id)), 201
api.add_resource(HelloWorld, "/", "/ping/")
api.add_resource(TodoList, "/todo/", endpoint="todo_list")
api.add_resource(Todo, "/todo/<int:todo_id>/", endpoint="todo")
if __name__ == "__main__":
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment