/cs496 schmicar final proj/Python Web Service/wsgi/myflaskapp.py
Python | 195 lines | 109 code | 44 blank | 42 comment | 6 complexity | 82f6fcc29b82a85801bab0f160031c5c MD5 | raw file
- import os
- import sys
- from flask import Flask
- from flask import request
- from flask import make_response
- from flask import jsonify
- import pymongo
- import json
- from bson import json_util
- from bson import objectid
- import re
- sys.path.append(os.path.join(os.environ['OPENSHIFT_REPO_DIR'], 'wsgi', 'openshift'))
- virtenv = os.environ['APPDIR'] + '/virtenv/'
- os.environ['PYTHON_EGG_CACHE'] = os.path.join(virtenv, 'lib/python2.6/site-packages')
- virtualenv = os.path.join(virtenv, 'bin/activate_this.py')
- try:
- execfile(virtualenv, dict(__file__=virtualenv))
- except:
- pass
- app = Flask(__name__)
- #add this so that flask doesn't swallow error messages
- app.config['PROPAGATE_EXCEPTIONS'] = True
- # route uri that returns all the albums in the collection
- @app.route("/ws/albums")
- def albums():
- #setup the connection
- conn = pymongo.Connection(os.environ['OPENSHIFT_MONGODB_DB_URL'])
- db = conn[os.environ['OPENSHIFT_APP_NAME']]
- #query the DB for all the users - get only albums, not stray documents
- result = db.albums.find( { 'album_name': { '$exists': True } })
- #Now turn the results into valid JSON
- return str(json.dumps({'results':list(result)},default=json_util.default))
- # route uri that returns all the albums in the collection
- @app.route("/ws/users")
- def users():
- #setup the connection
- conn = pymongo.Connection(os.environ['OPENSHIFT_MONGODB_DB_URL'])
- db = conn[os.environ['OPENSHIFT_APP_NAME']]
- #query the DB for all the parkpoints - get only albums
- result = db.users.find( )
- #Now turn the results into valid JSON
- return str(json.dumps({'results':list(result)},default=json_util.default))
- # route uri that adds a new user
- @app.route("/ws/add_user", methods=['POST'])
- def add_user():
- #setup the connection
- conn = pymongo.Connection(os.environ['OPENSHIFT_MONGODB_DB_URL'])
- db = conn[os.environ['OPENSHIFT_APP_NAME']]
- error = None # to implement validation later - should validate email
- #check that user_id was supplied
- if 'userid' not in request.form:
- return jsonify( { 'error': 'userid not supplied' } )
-
- # NOTE: I am doing all this now in case I have time to implement some
- # validation, however time is running out...
- user_id = request.form['userid']
- fname = request.form['fname']
- lname = request.form['lname']
- email = request.form['email']
- favs = request.form['fav_genres']
- # check that user_id is not duplicate of existing user
- if db.users.find({"_id": user_id}).count() > 0:
- return jsonify( { 'error': 'userid already exists'})
- # put user data into python dictionary object
- new_user = { "_id": user_id,
- "type": "user",
- "fname": fname,
- "lname": lname,
- "email": email,
- "fav_genres": favs,
- "albums": [] }
- # store the new album in database
- result = db.users.save(new_user)
- return str(json.dumps({'results':result},default=json_util.default))
- # NOTE: Not used in current to-do list application, but leaving in for reference for now
- # route that adds a new album to users collection
- @app.route("/ws/add_user_album/<userId>/<albumId>", methods=["PUT"])
- def add_user_album(userId, albumId):
- #setup the connection
- conn = pymongo.Connection(os.environ['OPENSHIFT_MONGODB_DB_URL'])
- db = conn[os.environ['OPENSHIFT_APP_NAME']]
- #check that userId is valid
- if db.users.find( {"_id": userId } ).count() < 1:
- return jsonify( { 'error': 'invalid userId' } )
- #check that album_id was supplied
- if db.albums.find( {"_id": albumId } ).count() < 1:
- return jsonify( { 'error': 'invalid albumId' } )
- return db.users.find( {"_id": { "$in": userId } } ).count
- # add album to user's collection
- result = db.users.update( {'_id': userId},
- { '$addToSet': { 'albums': albumId } } )
- # turn the results into valid JSON
- return str(json.dumps({'results':result},default=json_util.default))
- # Note: not used in current to-do list app, leaving in for reference
- # route that deletes a specific album from album collection
- @app.route("/ws/delete_album/<albumID>", methods=['DELETE'])
- def delete_album(albumID):
- #setup the connection
- conn = pymongo.Connection(os.environ['OPENSHIFT_MONGODB_DB_URL'])
- db = conn[os.environ['OPENSHIFT_APP_NAME']]
- # delete query based on the objectid
- result = db.albums.remove({'_id': objectid.ObjectId(albumID)})
- # turn the results into valid JSON
- return jsonify( { 'result': True } )
- # route that deletes a specific user from user collection
- @app.route("/ws/delete_user/<userID>", methods=['DELETE'])
- def delete_user(userID):
- #setup the connection
- conn = pymongo.Connection(os.environ['OPENSHIFT_MONGODB_DB_URL'])
- db = conn[os.environ['OPENSHIFT_APP_NAME']]
- # delete query based on the userId
- result = db.users.remove({'_id': userID } )
- # turn the results into valid JSON
- return jsonify( { 'result': True } )
- # route that adds genre to a specific album from album collection
- @app.route("/ws/add_genre/<albumID>/<genre>", methods=['PUT'])
- def add_album_genre(albumID, genre):
- #Note: known bug in mongo = not returning if addtoset() actually added
- #or not, result is always returning NULL from mongo. addToSet gaurantees
- #that it won't duplicate in a set.
- #setup the connection
- conn = pymongo.Connection(os.environ['OPENSHIFT_MONGODB_DB_URL'])
- db = conn[os.environ['OPENSHIFT_APP_NAME']]
- # TODO - add regex validation of name, alpha chars at least length 4
- #query based on the objectid
- result = db.albums.update( { '_id': objectid.ObjectId(albumID) },
- { '$addToSet': { 'album_genre': genre }})
- #turn the results into valid JSON
- return jsonify( { 'result': True } )
- @app.route("/test")
- def test():
- return "<strong>It actually worked</strong>"
-
- #need this in a scalable app so that HAProxy thinks the app is up
- @app.route("/")
- def blah():
- html_str = "<h3>CS496-400 Spring 2014<h3>"
- html_str += "Assignment 3.2 - Basic API<br>"
- html_str += "Vaughan Schmidt"
- html_str += "<h4>API calls</h4>"
- html_str += "TODO: For RESTful type service, this should advertise API as a return"
- return html_str
- @app.errorhandler(404)
- def not_found(error):
- return make_response(jsonify({'error': 'Not found'}), 404)
- @app.errorhandler(400)
- def not_found(error):
- return make_response(jsonify({'error': 'Bad Request, possible index violation'}), 400)
- @app.errorhandler(405)
- def not_found(error):
- return make_response(jsonify({'error': 'Method not allowed'}), 405)
- if __name__ == "__main__":
- app.run()