-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
104 lines (68 loc) · 2.4 KB
/
app.py
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
from logging import debug
from flask import Flask, json
from flask_pymongo import PyMongo
from bson.json_util import dumps
from bson.objectid import ObjectId
from flask import jsonify, request
from werkzeug.security import generate_password_hash, check_password_hash
app = Flask(__name__)
app.secret_key = "secretkey"
app.config['MONGO_URI'] = "mongodb://localhost:27017/users"
mongo = PyMongo(app)
@app.route('/add',methods=['POST'])
def add_user():
_json = request.json
_name = _json['name']
_email = _json['email']
_password = _json['pwd']
if _name and _email and _password and request.method == 'POST':
_hashed_password = generate_password_hash(_password)
id = mongo.db.user.insert({'name': _name, 'email':_email,'pwd':_hashed_password})
resp = jsonify("user added successfully")
resp.status_code = 200
return resp
else:
return not_found()
@app.errorhandler(404)
def not_found(error=None):
message = {
'status' : 404,
'message' : 'Not found' + request.url
}
resp = jsonify(message)
resp.status_code = 404
return resp
@app.route('/users')
def users():
users = mongo.db.user.find()
resp = dumps(users)
return resp
@app.route('/user/<id>')
def user(id):
user = mongo.db.user.find_one({'_id':ObjectId(id)})
resp = dumps(user)
return resp
@app.route('/delete/<id>', methods=['DELETE'])
def delete_user(id):
mongo.db.user.delete_one({'_id':ObjectId(id)})
resp = jsonify("user deleted successfully")
resp.status_code = 200
return resp
@app.route('/update/<id>', methods=['PUT'])
def update_user(id):
_id = id
_json = request.json
_name = _json['name']
_email = _json['email']
_password = _json['pwd']
if _name and _email and _password and _id and request.method == 'PUT':
_hashed_password = generate_password_hash(_password)
mongo.db.user.update_one({'_id':ObjectId(_id['$oid']) if '$oid' in _id else ObjectId(_id)},
{'$set':{'name':_name, 'email':_email, 'pwd':_hashed_password}})
resp = jsonify("user updated successfully")
resp.status_code = 200
return resp
else:
return not_found()
if __name__ =="__main__":
app.run(debug=True)