full_todo.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #!/bin/env python
  2. from flask import Flask
  3. from flask_restful import reqparse, abort, Api, Resource
  4. from flask_httpauth import HTTPBasicAuth
  5. # This "protects" paths with @auth.login_required
  6. auth = HTTPBasicAuth()
  7. # This is a very basic (and dumb) security model
  8. # We'll actually want the @auth.verify_password model,
  9. # which will let us use hashed passwords, etc.
  10. @auth.get_password
  11. def get_password(username):
  12. if username == 'admin':
  13. return '12345'
  14. return None
  15. @auth.error_handler
  16. def unauthorized():
  17. return abort(401, message='Unauthorized access')
  18. app = Flask(__name__)
  19. api = Api(app)
  20. TODOS = {
  21. 'todo1': {'task': 'build an API'},
  22. 'todo2': {'task': '?????'},
  23. 'todo3': {'task': 'profit!'},
  24. }
  25. def abort_if_todo_doesnt_exist(todo_id):
  26. if todo_id not in TODOS:
  27. abort(404, message="Todo {} doesn't exist".format(todo_id))
  28. parser = reqparse.RequestParser()
  29. parser.add_argument('task')
  30. # Todo
  31. # shows a single todo item and lets you delete a todo item
  32. # Yes! You can add the @auth.login_required to methods of the class. ! \o/ !
  33. class Todo(Resource):
  34. def get(self, todo_id):
  35. abort_if_todo_doesnt_exist(todo_id)
  36. return TODOS[todo_id]
  37. def delete(self, todo_id):
  38. abort_if_todo_doesnt_exist(todo_id)
  39. del TODOS[todo_id]
  40. return '', 204
  41. @auth.login_required
  42. def put(self, todo_id):
  43. args = parser.parse_args()
  44. t = args['task']
  45. if t is None:
  46. abort(400, message="I need text for the task. task=...")
  47. task = {'task': args['task']}
  48. TODOS[todo_id] = task
  49. return task, 201
  50. # TodoList
  51. # shows a list of all todos, and lets you POST to add new tasks
  52. class TodoList(Resource):
  53. def get(self):
  54. return TODOS
  55. def post(self):
  56. args = parser.parse_args()
  57. todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1
  58. todo_id = 'todo%i' % todo_id
  59. TODOS[todo_id] = {'task': args['task']}
  60. return TODOS[todo_id], 201
  61. ##
  62. ## Actually setup the Api resource routing here
  63. ##
  64. api.add_resource(TodoList, '/todos')
  65. api.add_resource(Todo, '/todos/<todo_id>')
  66. if __name__ == '__main__':
  67. app.run(port=11022, debug=True)