main.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. from app import app, mongo
  2. from bson.json_util import dumps
  3. from bson.objectid import ObjectId
  4. from flask import jsonify, flash, request
  5. from werkzeug import generate_password_hash, check_password_hash
  6. @app.route('/add', methods=['POST'])
  7. def add_user():
  8. _json = request.json
  9. _name = _json['name']
  10. _email = _json['email']
  11. _password = _json['pwd']
  12. # validate the received values
  13. if _name and _email and _password and request.method == 'POST':
  14. #do not save password as a plain text
  15. _hashed_password = generate_password_hash(_password)
  16. # save details
  17. id = mongo.db.user.insert({'name': _name, 'email': _email, 'pwd': _hashed_password})
  18. resp = jsonify('User added successfully!')
  19. resp.status_code = 200
  20. return resp
  21. else:
  22. return not_found()
  23. @app.route('/users')
  24. def users():
  25. users = mongo.db.user.find()
  26. resp = dumps(users)
  27. return resp
  28. @app.route('/user/<id>')
  29. def user(id):
  30. user = mongo.db.user.find_one({'_id': ObjectId(id)})
  31. resp = dumps(user)
  32. return resp
  33. @app.route('/update', methods=['PUT'])
  34. def update_user():
  35. _json = request.json
  36. _id = _json['_id']
  37. _name = _json['name']
  38. _email = _json['email']
  39. _password = _json['pwd']
  40. # validate the received values
  41. if _name and _email and _password and _id and request.method == 'PUT':
  42. #do not save password as a plain text
  43. _hashed_password = generate_password_hash(_password)
  44. # save edits
  45. mongo.db.user.update_one({'_id': ObjectId(_id['$oid']) if '$oid' in _id else ObjectId(_id)}, {'$set': {'name': _name, 'email': _email, 'pwd': _hashed_password}})
  46. resp = jsonify('User updated successfully!')
  47. resp.status_code = 200
  48. return resp
  49. else:
  50. return not_found()
  51. @app.route('/delete/<id>', methods=['DELETE'])
  52. def delete_user(id):
  53. mongo.db.user.delete_one({'_id': ObjectId(id)})
  54. resp = jsonify('User deleted successfully!')
  55. resp.status_code = 200
  56. return resp
  57. @app.errorhandler(404)
  58. def not_found(error=None):
  59. message = {
  60. 'status': 404,
  61. 'message': 'Not Found: ' + request.url,
  62. }
  63. resp = jsonify(message)
  64. resp.status_code = 404
  65. return resp
  66. if __name__ == "__main__":
  67. app.run()