PageRenderTime 92ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/cs496 schmicar final proj/Python Web Service/wsgi/myflaskapp.py

https://gitlab.com/vschmidt94/ubiquitous-octo-wookie
Python | 195 lines | 109 code | 44 blank | 42 comment | 6 complexity | 82f6fcc29b82a85801bab0f160031c5c MD5 | raw file
  1. import os
  2. import sys
  3. from flask import Flask
  4. from flask import request
  5. from flask import make_response
  6. from flask import jsonify
  7. import pymongo
  8. import json
  9. from bson import json_util
  10. from bson import objectid
  11. import re
  12. sys.path.append(os.path.join(os.environ['OPENSHIFT_REPO_DIR'], 'wsgi', 'openshift'))
  13. virtenv = os.environ['APPDIR'] + '/virtenv/'
  14. os.environ['PYTHON_EGG_CACHE'] = os.path.join(virtenv, 'lib/python2.6/site-packages')
  15. virtualenv = os.path.join(virtenv, 'bin/activate_this.py')
  16. try:
  17. execfile(virtualenv, dict(__file__=virtualenv))
  18. except:
  19. pass
  20. app = Flask(__name__)
  21. #add this so that flask doesn't swallow error messages
  22. app.config['PROPAGATE_EXCEPTIONS'] = True
  23. # route uri that returns all the albums in the collection
  24. @app.route("/ws/albums")
  25. def albums():
  26. #setup the connection
  27. conn = pymongo.Connection(os.environ['OPENSHIFT_MONGODB_DB_URL'])
  28. db = conn[os.environ['OPENSHIFT_APP_NAME']]
  29. #query the DB for all the users - get only albums, not stray documents
  30. result = db.albums.find( { 'album_name': { '$exists': True } })
  31. #Now turn the results into valid JSON
  32. return str(json.dumps({'results':list(result)},default=json_util.default))
  33. # route uri that returns all the albums in the collection
  34. @app.route("/ws/users")
  35. def users():
  36. #setup the connection
  37. conn = pymongo.Connection(os.environ['OPENSHIFT_MONGODB_DB_URL'])
  38. db = conn[os.environ['OPENSHIFT_APP_NAME']]
  39. #query the DB for all the parkpoints - get only albums
  40. result = db.users.find( )
  41. #Now turn the results into valid JSON
  42. return str(json.dumps({'results':list(result)},default=json_util.default))
  43. # route uri that adds a new user
  44. @app.route("/ws/add_user", methods=['POST'])
  45. def add_user():
  46. #setup the connection
  47. conn = pymongo.Connection(os.environ['OPENSHIFT_MONGODB_DB_URL'])
  48. db = conn[os.environ['OPENSHIFT_APP_NAME']]
  49. error = None # to implement validation later - should validate email
  50. #check that user_id was supplied
  51. if 'userid' not in request.form:
  52. return jsonify( { 'error': 'userid not supplied' } )
  53. # NOTE: I am doing all this now in case I have time to implement some
  54. # validation, however time is running out...
  55. user_id = request.form['userid']
  56. fname = request.form['fname']
  57. lname = request.form['lname']
  58. email = request.form['email']
  59. favs = request.form['fav_genres']
  60. # check that user_id is not duplicate of existing user
  61. if db.users.find({"_id": user_id}).count() > 0:
  62. return jsonify( { 'error': 'userid already exists'})
  63. # put user data into python dictionary object
  64. new_user = { "_id": user_id,
  65. "type": "user",
  66. "fname": fname,
  67. "lname": lname,
  68. "email": email,
  69. "fav_genres": favs,
  70. "albums": [] }
  71. # store the new album in database
  72. result = db.users.save(new_user)
  73. return str(json.dumps({'results':result},default=json_util.default))
  74. # NOTE: Not used in current to-do list application, but leaving in for reference for now
  75. # route that adds a new album to users collection
  76. @app.route("/ws/add_user_album/<userId>/<albumId>", methods=["PUT"])
  77. def add_user_album(userId, albumId):
  78. #setup the connection
  79. conn = pymongo.Connection(os.environ['OPENSHIFT_MONGODB_DB_URL'])
  80. db = conn[os.environ['OPENSHIFT_APP_NAME']]
  81. #check that userId is valid
  82. if db.users.find( {"_id": userId } ).count() < 1:
  83. return jsonify( { 'error': 'invalid userId' } )
  84. #check that album_id was supplied
  85. if db.albums.find( {"_id": albumId } ).count() < 1:
  86. return jsonify( { 'error': 'invalid albumId' } )
  87. return db.users.find( {"_id": { "$in": userId } } ).count
  88. # add album to user's collection
  89. result = db.users.update( {'_id': userId},
  90. { '$addToSet': { 'albums': albumId } } )
  91. # turn the results into valid JSON
  92. return str(json.dumps({'results':result},default=json_util.default))
  93. # Note: not used in current to-do list app, leaving in for reference
  94. # route that deletes a specific album from album collection
  95. @app.route("/ws/delete_album/<albumID>", methods=['DELETE'])
  96. def delete_album(albumID):
  97. #setup the connection
  98. conn = pymongo.Connection(os.environ['OPENSHIFT_MONGODB_DB_URL'])
  99. db = conn[os.environ['OPENSHIFT_APP_NAME']]
  100. # delete query based on the objectid
  101. result = db.albums.remove({'_id': objectid.ObjectId(albumID)})
  102. # turn the results into valid JSON
  103. return jsonify( { 'result': True } )
  104. # route that deletes a specific user from user collection
  105. @app.route("/ws/delete_user/<userID>", methods=['DELETE'])
  106. def delete_user(userID):
  107. #setup the connection
  108. conn = pymongo.Connection(os.environ['OPENSHIFT_MONGODB_DB_URL'])
  109. db = conn[os.environ['OPENSHIFT_APP_NAME']]
  110. # delete query based on the userId
  111. result = db.users.remove({'_id': userID } )
  112. # turn the results into valid JSON
  113. return jsonify( { 'result': True } )
  114. # route that adds genre to a specific album from album collection
  115. @app.route("/ws/add_genre/<albumID>/<genre>", methods=['PUT'])
  116. def add_album_genre(albumID, genre):
  117. #Note: known bug in mongo = not returning if addtoset() actually added
  118. #or not, result is always returning NULL from mongo. addToSet gaurantees
  119. #that it won't duplicate in a set.
  120. #setup the connection
  121. conn = pymongo.Connection(os.environ['OPENSHIFT_MONGODB_DB_URL'])
  122. db = conn[os.environ['OPENSHIFT_APP_NAME']]
  123. # TODO - add regex validation of name, alpha chars at least length 4
  124. #query based on the objectid
  125. result = db.albums.update( { '_id': objectid.ObjectId(albumID) },
  126. { '$addToSet': { 'album_genre': genre }})
  127. #turn the results into valid JSON
  128. return jsonify( { 'result': True } )
  129. @app.route("/test")
  130. def test():
  131. return "<strong>It actually worked</strong>"
  132. #need this in a scalable app so that HAProxy thinks the app is up
  133. @app.route("/")
  134. def blah():
  135. html_str = "<h3>CS496-400 Spring 2014<h3>"
  136. html_str += "Assignment 3.2 - Basic API<br>"
  137. html_str += "Vaughan Schmidt"
  138. html_str += "<h4>API calls</h4>"
  139. html_str += "TODO: For RESTful type service, this should advertise API as a return"
  140. return html_str
  141. @app.errorhandler(404)
  142. def not_found(error):
  143. return make_response(jsonify({'error': 'Not found'}), 404)
  144. @app.errorhandler(400)
  145. def not_found(error):
  146. return make_response(jsonify({'error': 'Bad Request, possible index violation'}), 400)
  147. @app.errorhandler(405)
  148. def not_found(error):
  149. return make_response(jsonify({'error': 'Method not allowed'}), 405)
  150. if __name__ == "__main__":
  151. app.run()