-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
85 lines (66 loc) · 2.51 KB
/
app.py
File metadata and controls
85 lines (66 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
from flask import Flask
from flask_restful import Resource, Api, reqparse, abort, fields, marshal_with
from flask_sqlalchemy import SQLAlchemy
app=Flask(__name__)
api=Api(app)
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///sqlite.db'
db=SQLAlchemy(app)
class ToDoModel(db.Model):
id = db.Column(db.Integer, primary_key=True)
task=db.Column(db.String(200))
summary=db.Column(db.String(500))
task_post_args=reqparse.RequestParser()
task_post_args.add_argument('task', type=str, help='Task is required' , required=True)
task_post_args.add_argument('summary', type=str, help='Summary is required' , required=True)
task_update_args = reqparse.RequestParser()
task_update_args.add_argument('task', type=str)
task_update_args.add_argument('summary', type=str)
resource_fields={
'id': fields.Integer,
'task': fields.String,
'summary': fields.String,
}
class ToDoList(Resource):
def get(self):
tasks=ToDoModel.query.all()
todos={}
for task in tasks:
todos[task.id] = {'task': task.task, 'summary':task.summary}
return todos
class ToDo(Resource):
@marshal_with(resource_fields)
def get(self, todo_id):
task=ToDoModel.query.filter_by(id=todo_id).first()
if not task:
abort(404, message='Could not find task with the given id.')
return task
@marshal_with(resource_fields)
def post(self, todo_id):
args=task_post_args.parse_args()
task=ToDoModel.query.filter_by(id=todo_id).first()
if task:
abort(409, message='task id is taken')
todo=ToDoModel(id=todo_id, task=args['task'], summary=args['summary'])
db.session.add(todo)
db.session.commit()
return todo, 201
@marshal_with(resource_fields)
def put(self, todo_id):
args=task_update_args.parse_args()
task = ToDoModel.query.filter_by(id=todo_id).first()
if not task:
abort(404, message="task doesnot exist, cannot update")
if args['task']:
task.task=args['task']
if args['summary']:
task.summary=args['summary']
db.session.commit()
return task
def delete(self, todo_id):
task = ToDoModel.query.filter_by(id=todo_id).first()
db.session.delete(task)
return 'ToDo deleted', 204
api.add_resource(ToDo,'/todos/<int:todo_id>')
api.add_resource(ToDoList, '/todos')
if __name__=='__main__':
app.run(debug=True)