-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
96 lines (77 loc) · 2.35 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
from flask import Flask
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 _password and _email and request.method == 'POST':
_hashed_password = generate_password_hash(_password)
id = mongo.db.user.insert({
'name' : _name,
'email' : _email,
'pwd': _hashed_password
})
response = jsonify("User added successfully"),200
return response
else:
return not_found()
@app.route('/users',methods=['GET'])
def users():
users = mongo.db.user.find()
response = dumps(users)
return response
@app.route('/users/<id>')
def user(id):
user = mongo.db.user.find_one({'_id' : ObjectId(id)})
response = dumps(user)
return response
@app.route('/delete/<id>',methods=['DELETE'])
def delete_user(id):
mongo.db.user.delete_one({
'_id' : ObjectId(id)
})
response = jsonify("user deleted successfully"),202
return response
@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 _password and _id and _email 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,
}
}
)
response = jsonify('User updated successfully'),200
return response
@app.errorhandler(404)
def not_found(error = None):
message = {
'status' : 404,
'message':'Not Found'+ request.url
}
response = jsonify(message)
return response
if __name__=='__main__':
app.run(debug=True)