Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. from __future__ import print_function
  2. from flask import Flask
  3. from flask import jsonify
  4. from flask import request
  5. import pymongo
  6. import json
  7. from bson import json_util
  8.  
  9. app = Flask(__name__)
  10.  
  11. @app.before_request
  12. def abc():
  13. auth = request.authorization
  14. if auth.username == 'admin' and auth.password == 'abc123':
  15. # response = jsonify({"message":"success"})
  16. # response.status_code = 200
  17. # return response
  18. pass
  19. else:
  20. response = jsonify({"message":"Invalid credentials"})
  21. response.status_code = 401
  22. return response
  23.  
  24.  
  25. def connecttomongodb():
  26. conn=pymongo.MongoClient('localhost', 27017)
  27. db = conn.student_database
  28. coll = db.students
  29. return coll
  30.  
  31.  
  32. @app.route('/students/<name>', methods = ['GET'])
  33. def test(name):
  34. temp = connecttomongodb()
  35. var =temp.find_one({"name":name})
  36. return json_util.dumps(var)
  37.  
  38. @app.route('/students/',methods = ['POST'])
  39. def test123():
  40. var = request.json
  41. temp = connecttomongodb()
  42. temp.insert(var)
  43. print(var)
  44. return 'good morning ' + str(request.json)
  45.  
  46. @app.route('/students/',methods = ['GET'])
  47. def test123():
  48. temp = connecttomongodb()
  49. var = temp.find()
  50. return json_util.dumps(var)
  51.  
  52.  
  53. @app.route('/students/<name>', methods = ['DELETE'])
  54. def test_delete(name):
  55. return 'delete success ' + name
  56.  
  57. @app.route('/students/<name>', methods = ['PUT'])
  58. def test_put(name):
  59. var = request.json
  60. temp = connecttomongodb()
  61. temp.update({"name":"palo"},{'$set':var})
  62. # db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}})
  63. return 'put success ' + name + str(var)
  64.  
  65. if __name__ == '__main__':
  66. app.run('localhost',8080,True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement