-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtasks.py
More file actions
126 lines (93 loc) · 2.84 KB
/
tasks.py
File metadata and controls
126 lines (93 loc) · 2.84 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
from flask import Flask, jsonify, request
from pymongo import MongoClient
import dns # required for connecting with SRV
from bson.objectid import ObjectId
app = Flask(__name__)
username = 'username'
password = 'password'
client = MongoClient(
'mongodb+srv://' + username + ':'+password+'@cluster0-h74u6.mongodb.net')
database = client.get_database('pymongotasks')
collection = database.tasks
@app.route('/tasks', methods=['GET'])
def get_tasks():
tasks = collection.find()
output = []
for task in tasks:
output.append({
'id': str(task['_id']),
'title': task['title'],
'description': task['description'],
'complete': task['complete']
})
return jsonify({'result': output})
@app.route('/tasks/<id>', methods=['GET'])
def get_task(id):
task = collection.find_one({'_id': ObjectId(id)})
if task:
output = {
'id': str(task['_id']),
'title': task['title'],
'description': task['description'],
'complete': task['complete']
}
else:
output = 'no results found'
return jsonify({'result': output})
@app.route('/tasks/<id>', methods=['DELETE'])
def delete_task(id):
task = collection.delete_one({'_id': ObjectId(id)})
if task.deleted_count > 0:
output = {
'sucessful': True,
'message': 'successfully deleted'
}
else:
output = {
'sucessful': False,
'message': 'not successfully deleted'
}
return jsonify({'result': output})
@app.route('/tasks/<id>', methods=['PATCH'])
def update_task(id):
title = request.json['title']
description = request.json['description']
complete = request.json['complete']
task = {
'title': title,
'description': description,
'complete': complete
}
result = collection.update_one(
{'_id': ObjectId(id)}, {'$set': task})
if result.modified_count > 0:
output = {
'sucessful': True,
'message': 'successfully updated'
}
else:
output = {
'sucessful': False,
'message': 'not successfully updated'
}
return jsonify({'result': output})
@app.route('/tasks', methods=['POST'])
def add_task():
title = request.json['title']
description = request.json['description']
task = {
'title': title,
'description': description,
'complete': False
}
inserted_task = collection.insert_one(task)
task_id = inserted_task.inserted_id
new_task = collection.find_one({'_id': task_id})
output = {
'title': new_task['title'],
'description': new_task['description'],
'complete': new_task['complete']
}
return jsonify({'result': output})
if __name__ == '__main__':
app.run(debug=True)