def receipt(id): receipts = mongo.db.receipts if request.method == 'GET': '''Get receipt specified by ID''' # TODO return {'id': id, 'data': 'GET mocked'} if request.method == 'PUT': '''Update receipt data''' receipt = request.get_json() receipt['_id'] = ObjectId(receipt['_id']) query = receipts.save(receipt) # TODO A save receipt product names to autocomplete database ac_add_new_words(receipt) # add if not exists return jsonify(receipt) if request.method == 'DELETE': '''Delete receipt''' # TODO: other users receipts can now be removed by ID try: query = receipts.remove(ObjectId(id)) if query[u'n'] is 0: abort(404, "Problem with Mongo remove function") except: abort(404) return jsonify({"query": str(query)}), 200
def delete(oid): if not is_logged_in(): flash("You must be logged in to do that", 'error') return redirect(url_for('home')) login = session['user_data']['login'] result = mongo.db.mycollection.find_one({'_id': ObjectId(oid)}) if not 'login' in result: flash( "Error deleting record with oid " + repr(oid) + "; could not determine user for record", "error") return redirect(url_for('listAll')) elif result['login'] != login: flash( "Cannot delete record for oid " + repr(oid) + " belonging to user " + result['login'], 'error') return redirect(url_for('listAll')) result = mongo.db.mycollection.delete_one({ '_id': ObjectId(oid), 'login': login }) if result.deleted_count == 0: flash("Error: Record with oid " + repr(oid) + " was not deleted", 'error') elif result.deleted_count == 1: flash("Record with oid " + repr(oid) + " deleted") else: flash("Error: Unexpected result.deleted_count=" + \ str(result.deleted_count)) return redirect(url_for('listAll'))
def get_user_node(user_id=None): cypher = secure_graph1.cypher user_cursor = mongo3.db.users.find({"_id": ObjectId(user_id)}) #find all activities json_user = json.dumps(user_cursor[0], default=json_util.default) # Create a new python dictionary from the json_user, we'll call it user_dict user_dict = json.loads(json_user) # Assumes either a record list of 1 or no records at all! user_node_list = cypher.execute("MATCH (user:User {user_id: '" + user_id + "'}) RETURN user") user_node=None if len(user_node_list) == 0: # Create a user node user_node = Node("User", email=user_dict.get('email'), user_id=user_dict.get('_id').get('$oid'), nodeType='user', ) else: # Don't create a new user node it already exists user_node = user_node_list[0][0] return user_node
def process_experiences_overview(user=None): cursor = mongo3.db.experiences.find({"user": ObjectId(user) }) #works! React User id # Create a data dictionary to set up the building of data intended for different charts. data_dict = {'data': []} # Create a dictionary to hold the main object main_return_dict = {'all': []} # Create a list to hold the time counts (in seconds) second_counts_dict = [] for item in cursor: json_item = json.dumps(item, default=json_util.default) # Create a new python dictionary from the json_item, we'll call it json_dict json_dict = json.loads(json_item) # Append the second count to the second_counts_dict second_counts_dict.append(json_dict.get('seconds')) # Append the entire json_dict dictionary data_dict['data'].append(json_dict) main_return_dict['all'].append( data_dict) # last json dict, and needs refactoring main_return_dict['all'].append({'secondCounts': second_counts_dict}) main_return_dict['all'].append({ 'description_primary': 'The experience information for every experience you have written.' }) main_return_dict['all'].append({'description_secondary': 'Use it wisely!'}) main_return_dict['all'].append({'title': 'Experience Summary'}) return jsonify(**main_return_dict)
def intercepts_update_single_experience(experience=None): print '====update single experience node====' cypher = secure_graph1.cypher # Find all activities, but really just one in this case experience_cursor = mongo3.db.experiences.find({"_id": ObjectId(experience)}) json_experience = json.dumps(experience_cursor[0], default=json_util.default) # Create a new python dictionary from the json_experience, we'll call it experience_dict experience_dict = json.loads(json_experience) print experience_dict ### # Business logic for USER_NODE starts here, uses data from above. ### user_id = experience_dict.get('user').get('$oid') user_node = get_user_node(user_id=user_id) ### # Business logic for EXPERIENCE_NODE starts here, uses data from above. ### update_experience_node(new_user_node=user_node, experience_dict=experience_dict) # TODO: update this: where the experience node changes its containing activity return 'success'
def intercepts_create_single_activity(activity=None): cypher = secure_graph1.cypher # Find all activities, but really just one in this case activity_cursor = mongo3.db.activities.find({"_id": ObjectId(activity)}) json_activity = json.dumps(activity_cursor[0], default=json_util.default) # Create a new python dictionary from the json_activity, we'll call it activity_dict activity_dict = json.loads(json_activity) print activity_dict ### # Business logic for USER_NODE starts here, uses data from above. ### user_id = activity_dict.get('user').get('$oid') user_node = get_user_node(user_id=user_id) ### # Business logic for ACTIVITIY_NODE starts here, uses data from above. ### cnr_user_did_activity(new_user_node=user_node, activity_dict=activity_dict) return 'success'
def delete(self, expense_id = None): if expense_id is None: return "Bad Request", 400 mongo.db.expenses.remove({"_id": ObjectId(expense_id)}) return "OK", 200
def load_user(_id): """Flask-login hook into mongo""" r_dict = mongo.db.users.find_one(ObjectId(_id)) if r_dict is None: return None user = User(r_dict['username'], r_dict['password'], r_dict['_id']) return user
def delete_todo(): if request.method == 'DELETE': todo_id = request.form.get('id', '') todo_objectid = ObjectId(todo_id) mongo.db.todo_list.remove({'_id': todo_objectid}) todo_list, count = get_todo_list() return jsonify(data=todo_list, count=count)
def save_dropbox(mongo, code): mongo.db[MONGO.FORWARDERS].update( {'userId' : ObjectId(session['uid'])}, { '$set' : { 'forwarders.dropbox.refreshToken' : code } })
def retrieve_single_run_anlysis(collection=None, analysis_id=None): result = affect_analysis.db[collection].find_one( {"_id": ObjectId(analysis_id)}) return jsonify( status="success", data=json.loads(json.dumps(result, default=json_util.default)), )
def complete(mongo, data=None): print data response = mongo.db[MONGO.REMINDERS].update({'_id': ObjectId(data['rid'])}, {'$set': { 'completed': True }}) if not response: return ERR.REMINDER_NOT_FOUND return RESP.REMINDER_COMPLETED
def process_activities_overview(user=None): cursor = mongo3.db.activities.find({"user": ObjectId(user)}) #works! React User id # Create a data dictionary to set up the building of data intended for different charts. data_dict = {'data': []} # Create a dictionary to hold the main object main_return_dict = {'all' : []} return jsonify(**main_return_dict)
def intercepts_create_single_log(log=None): print '====create single log node====' cypher = secure_graph1.cypher # Find all activities, but really just one in this case log_cursor = mongo3.db.logs.find({"_id": ObjectId(log)}) json_log = json.dumps(log_cursor[0], default=json_util.default) # Create a new python dictionary from the json_log, we'll call it log_dict log_dict = json.loads(json_log) ### # Business logic for USER_NODE starts here, uses data from above. ### user_id = log_dict.get('user').get('$oid') user_node = get_user_node(user_id=user_id) ### # Business logic for getting EXPERIENCE_NODE starts here, uses data from above. ### experience_id = log_dict.get('firstExperience').get('$oid') experience_node = get_experience_node(experience_id=experience_id) ### # Business logic for LOG_NODE starts here, uses data from above. ### new_log_node = cnr_user_logged_log(new_user_node=user_node, log_dict=log_dict) ### # Business logic for SUBLOG_NODE starts here, uses data from above. ### # List of all dictionary types sublog_list = ['physic', 'emotion', 'academic', 'commune', 'ether'] for sublog_name in sublog_list: # This method also creates a new sublog, and builds a relationship # to the user (and adds the word nodes)! cnr_log_contains_sub( new_user_node=user_node, new_log_node=new_log_node, log_dict=log_dict, sublog_array_name=sublog_name, node_title=sublog_name.title() + 'Log', ) # Create a new relationship for the experience/log experience_contains_log = Relationship(experience_node, "CONTAINS", new_log_node) secure_graph1.create(experience_contains_log) return 'success'
def update(mongo, data=None): mongo.db[MONGO.FORWARDERS].update({ 'userId': ObjectId(session['uid']), }, { '$set': { 'current': data['current'], 'forwarders.sms.number': data['forwarders']['sms']['number'], 'forwarders.dropbox': data['forwarders']['dropbox'] } }) return RESP.UPDATED
def modify_state(): if request.method == 'PUT': todo_id = request.form.get('id', '') todo_status = int(request.form.get('isCompleted', 0)) todo_status = bool(todo_status) todo_objectid = ObjectId(todo_id) mongo.db.todo_list.update({'_id': todo_objectid}, {'$set': { 'completed': todo_status }}) return jsonify(status='success')
def modify_matter(): if request.method == 'PUT': todo_id = request.form.get('id', '') matter = request.form.get('matter', '') todo_objectid = ObjectId(todo_id) mongo.db.todo_list.update({'_id': todo_objectid}, {'$set': { 'matter': matter }}) todo_list, count = get_todo_list() return jsonify(data=todo_list, count=count)
def get_user(mongo, uid=None, data=None): try: user = mongo.db[MONGO.USERS].find_one({'_id': ObjectId(uid)}) except: return ERR.USER_NOT_FOUND if not user: return ERR.USER_NOT_FOUND response = {} # build response for key in data['return']: response[key] = user[key] return simplejson.dumps(response), 200
def intercepts_update_single_log(log=None): print '====update single log node====' cypher = secure_graph1.cypher # Find all activities, but really just one in this case log_cursor = mongo3.db.logs.find({"_id": ObjectId(log)}) json_log = json.dumps(log_cursor[0], default=json_util.default) # Create a new python dictionary from the json_log, we'll call it log_dict log_dict = json.loads(json_log) print log_dict ### # Business logic for USER_NODE starts here, uses data from above. ### user_id = log_dict.get('user').get('$oid') user_node = get_user_node(user_id=user_id) # TODO: Get the log node, and update it and its words!! ### # Business logic for LOG_NODE starts here, uses data from above. ### log_node = update_log_node(new_user_node=user_node, log_dict=log_dict) # TODO: update this: where the log node changes its containing experience ### # Business logic for SUBLOG_NODE starts here, uses data from above. ### # List of all dictionary types sublog_list = ['physic', 'emotion', 'academic', 'commune', 'ether'] for sublog_name in sublog_list: # This method also creates a new sublog, and builds a relationship # to the user (and adds the word nodes)! cnr_log_contains_sub( new_user_node=user_node, new_log_node=log_node, log_dict=log_dict, sublog_array_name=sublog_name, node_title=sublog_name.title() + 'Log', ) return 'success'
def get_log_node(log_id=None): cypher = secure_graph1.cypher log_cursor = mongo3.db.logs.find({"_id": ObjectId(log_id)}) #find all activities json_log = json.dumps(log_cursor[0], default=json_util.default) # Create a new python dictionary from the json_log, we'll call it log_dict log_dict = json.loads(json_log) # Assumes either a record list of 1 or no records at all! log_node_list = cypher.execute("MATCH (log:Log {log_id: '" + log_id + "'}) RETURN log") # Define the log node to return log_node = log_node_list[0][0] return log_node
def get_activity_node(activity_id=None): cypher = secure_graph1.cypher activity_cursor = mongo3.db.activities.find({"_id": ObjectId(activity_id)}) #find all activities json_activity = json.dumps(activity_cursor[0], default=json_util.default) # Create a new python dictionary from the json_activity, we'll call it activity_dict activity_dict = json.loads(json_activity) # Assumes either a record list of 1 or no records at all! activity_node_list = cypher.execute("MATCH (activity:Activity {activity_id: '" + activity_id + "'}) RETURN activity") # Define the activity node to return activity_node = activity_node_list[0][0] return activity_node
def get_experience_node(experience_id=None): cypher = secure_graph1.cypher experience_cursor = mongo3.db.experiences.find({"_id": ObjectId(experience_id)}) #find all activities json_experience = json.dumps(experience_cursor[0], default=json_util.default) # Create a new python dictionary from the json_experience, we'll call it experience_dict experience_dict = json.loads(json_experience) # Assumes either a record list of 1 or no records at all! experience_node_list = cypher.execute("MATCH (experience:Experience {experience_id: '" + experience_id + "'}) RETURN experience") # Define the experience node to return experience_node = experience_node_list[0][0] return experience_node
def find_one(cls, userid=None, username=None): if not id and not username: return None if userid: if type(userid) is not 'bson.objectid.ObjectId': userid = ObjectId(userid) db_user = g.mongo.users.find({ '_id': userid, }) elif username: db_user = g.mongo.users.find({ 'username': username, }) if not db_user: return None return cls(db_user)
def process_logs_word_lengths(user=None): cursor = mongo3.db.logs.find({"user": ObjectId(user)}) #works! React User id # Create a data dictionary to set up the building of data intended for different charts. data_dict = {'data': []} # Create a dictionary to hold the main object main_return_dict = {'all': []} # Create a list to hold the time counts (in seconds) word_lengths_counts_dict = [] for item in cursor: json_item = json.dumps(item, default=json_util.default) # Create a new python dictionary from the json_item, we'll call it json_dict json_dict = json.loads(json_item) # Append the second count to the second_counts_dict word_lengths_counts_dict.append([ json_dict.get('physicArrayLength'), json_dict.get('emotionArrayLength'), json_dict.get('academicArrayLength'), json_dict.get('communeArrayLength'), json_dict.get('etherArrayLength'), ]) # Append the entire json_dict dictionary data_dict['data'].append(json_dict) main_return_dict['all'].append( data_dict) # last json dict, and needs refactoring main_return_dict['all'].append( {'wordLengthCounts': word_lengths_counts_dict}) main_return_dict['all'].append({ 'description_primary': 'The word length information for every log you have written.' }) main_return_dict['all'].append({'description_secondary': 'Use it wisely!'}) main_return_dict['all'].append({'title': 'Word Lengths'}) return jsonify(**main_return_dict)
def intercepts_create_single_experience(experience=None): print '====create single experience node====' cypher = secure_graph1.cypher # Find all activities, but really just one in this case experience_cursor = mongo3.db.experiences.find({"_id": ObjectId(experience)}) json_experience = json.dumps(experience_cursor[0], default=json_util.default) # Create a new python dictionary from the json_experience, we'll call it experience_dict experience_dict = json.loads(json_experience) print experience_dict ### # Business logic for USER_NODE starts here, uses data from above. ### user_id = experience_dict.get('user').get('$oid') user_node = get_user_node(user_id=user_id) ### # Business logic for getting ACTIVITY_NODE starts here, uses data from above. ### activity_id = experience_dict.get('firstActivity').get('$oid') activity_node_one = get_activity_node(activity_id=activity_id) activity_id = experience_dict.get('secondActivity').get('$oid') activity_node_two = get_activity_node(activity_id=activity_id) ### # Business logic for EXPERIENCE_NODE starts here, uses data from above. ### new_experience_node = cnr_user_experienced_experience(new_user_node=user_node, experience_dict=experience_dict) # Create a new relationship for the activity/experience activity_contains_experience = Relationship(activity_node_one, "CONTAINS", new_experience_node) secure_graph1.create(activity_contains_experience) activity_contains_experience = Relationship(activity_node_two, "CONTAINS", new_experience_node) secure_graph1.create(activity_contains_experience) return 'success'
def signup(mongo, data=None): print data if user_exists(mongo, data={'email': data['email']}): return ERR.USER_ALREADY_EXISTS userId = mongo.db[MONGO.USERS].insert({ "username": data['username'], "email": data['email'], "password": cryptor.encrypt(data["password"]) }) user = mongo.db[MONGO.USERS].find_one({'_id': ObjectId(userId)}) mongo.db[MONGO.FORWARDERS].insert({ 'current': 'email', 'forwarders': { 'sms': { 'number': '' }, 'dropbox': { 'refreshToken': '' }, 'gtasks': { 'refreshToken': '' }, 'gcalendar': { 'refreshToken': '' } }, 'userId': userId }) addUserToSession(user) return RESP.LOGGED_IN
def process_experiences_statistics(user=None): cursor = mongo3.db.experiences.find({"user": ObjectId(user) }) #works! React User id # Create a data dictionary to set up the building of data intended for different charts. data_dict = {'data': []} # Create a dictionary to hold the main object main_return_dict = {'all': []} # Create a list to hold the time counts (in seconds) word_length_dict = [] # Create a list to hold the time counts (in seconds) second_counts_dict = [] # Create an empty array to hold the data I care about, in this case # the data is an array of privacy info privacy_dict = [0, 0] # Create an empty array to hold the data I care about, in this case # the data is an array of privacy info pronoun_dict = { 'singular1stPerson': 0, 'singular2ndPerson': 0, 'masculine3rdPerson': 0, 'femine3rdPerson': 0, 'neuter3rdPerson': 0, 'plural2ndPerson': 0, 'plural1stPerson': 0, 'plural3rdPerson': 0, } # Create an empty array to hold the data I care about, in this case # the data is an array of experience time info experience_time_dict = { 'before': 0, 'while': 0, 'after': 0, } # Totals totals_dict = { 'totalSeconds': 0, 'totalWords': 0, 'totalExperiences': 0, } # Averages averages_dict = { 'avgSeconds': 0, 'avgWords': 0, } for item in cursor: json_item = json.dumps(item, default=json_util.default) # Count total Experiences totals_dict['totalExperiences'] += 1 # Create a new python dictionary from the json_item, we'll call it json_dict json_dict = json.loads(json_item) # Append the second count to the second_counts_dict second_counts_dict.append(json_dict.get('seconds')) # Count total seconds totals_dict['totalSeconds'] += json_dict.get('seconds') # Append the second count to the second_counts_dict word_length_dict.append(json_dict.get('descriptionArrayLength')) # Count total words totals_dict['totalWords'] += json_dict.get('descriptionArrayLength') # Append the entire json_dict dictionary data_dict['data'].append(json_dict) # Count the different privacies if json_dict.get('privacy') < 1: privacy_dict[0] += 1 else: privacy_dict[1] += 1 # Count the different pronouns if json_dict.get('pronoun') == 'I': pronoun_dict['singular1stPerson'] += 1 elif json_dict.get('pronoun') == 'You': pronoun_dict['singular2ndPerson'] += 1 elif json_dict.get('pronoun') == 'He': pronoun_dict['masculine3rdPerson'] += 1 elif json_dict.get('pronoun') == 'She': pronoun_dict['femine3rdPerson'] += 1 elif json_dict.get('pronoun') == 'It': pronoun_dict['neuter3rdPerson'] += 1 elif json_dict.get('pronoun') == 'You all': pronoun_dict['plural2ndPerson'] += 1 elif json_dict.get('pronoun') == 'We': pronoun_dict['plural1stPerson'] += 1 elif json_dict.get('pronoun') == 'They': pronoun_dict['plural3rdPerson'] += 1 else: print 'pronoun not found' # Count the different pronouns if json_dict.get('experienceTime') == 'Before': experience_time_dict['before'] += 1 elif json_dict.get('experienceTime') == 'While': experience_time_dict['while'] += 1 elif json_dict.get('experienceTime') == 'After': experience_time_dict['after'] += 1 else: print 'pronoun not found' # Average total Importance averages_dict['avgSeconds'] = totals_dict['totalSeconds'] / len( second_counts_dict) averages_dict['avgWords'] = totals_dict['totalWords'] / len( word_length_dict) main_return_dict['all'].append( data_dict) # last json dict, and needs refactoring main_return_dict['all'].append({ 'secondCounts': second_counts_dict, 'wordLengths': word_length_dict, 'privacyCounts': privacy_dict, 'pronouns': pronoun_dict, 'experienceTimes': experience_time_dict, 'totals': totals_dict, 'averages': averages_dict, }) main_return_dict['all'].append({ 'description_primary': 'The experience statistics for every experience you have written.' }) main_return_dict['all'].append({'description_secondary': 'Use it wisely!'}) main_return_dict['all'].append({'title': 'Experience Statistics'}) return jsonify(**main_return_dict)
def find_by_current_user(mongo): forwarders = mongo.db[MONGO.FORWARDERS].find_one( {'userId': ObjectId(session['uid'])}) return simplejson.dumps(mongo_to_dict(forwarders)), 200
def process_logs_overview(user=None): if user: # Make it take a user id dynamically # https://api.mongodb.org/python/current/tutorial.html # cursor = mongo3.db.logs.find({"user": ObjectId('562d722a3f1f9f541814a3e8')}) #works! React User id cursor = mongo3.db.logs.find({"user": ObjectId(user)}) #works! React User id # Create a pie dictionary to set up the building of data intended for pie charts. pie_dict = {'pies': []} # Create counters for the total lengths of word_arrays physicArrayTotal = 0 emotionArrayTotal = 0 academicArrayTotal = 0 communeArrayTotal = 0 etherArrayTotal = 0 # Create a main dictionary for the response main_return_dict = {'all': []} # http://stackoverflow.com/questions/11280382/python-mongodb-pymongo-json-encoding-and-decoding for item in cursor: json_item = json.dumps(item, default=json_util.default) # Create a new python dictionary from the json_item, we'll call it json_dict json_dict = json.loads(json_item) # Define the json key for the array to hold the json_key = json_dict.get('_id').get('$oid') # Create an empty array to hold the data I care about, in this case # the data is an array of five numbers for each json_dict, the word_array lengths (words) word_array_lengths = [] if json_dict.get('physicArrayLength') > 0: word_array_lengths.append(json_dict.get('physicArrayLength')) else: word_array_lengths.append(0) if json_dict.get('emotionArrayLength') > 0: word_array_lengths.append(json_dict.get('emotionArrayLength')) else: word_array_lengths.append(0) if json_dict.get('academicArrayLength') > 0: word_array_lengths.append(json_dict.get('academicArrayLength')) else: word_array_lengths.append(0) if json_dict.get('communeArrayLength') > 0: word_array_lengths.append(json_dict.get('communeArrayLength')) else: word_array_lengths.append(0) if json_dict.get('etherArrayLength') > 0: word_array_lengths.append(json_dict.get('etherArrayLength')) else: word_array_lengths.append(0) # Get the content for each of the word array values, and order it correctly in the array word_array_contents = [] word_array_contents.append(json_dict.get('physicContent')) word_array_contents.append(json_dict.get('emotionContent')) word_array_contents.append(json_dict.get('academicContent')) word_array_contents.append(json_dict.get('communeContent')) word_array_contents.append(json_dict.get('etherContent')) # Assemble a pie_instance_dict pie_instance_dict = { 'key': json_key, 'data': word_array_lengths, 'values': word_array_contents, 'name': json_dict.get('name') } # Assembled pie_instance_dict now gets appended to the end of pies in pie_dict pie_dict['pies'].append(pie_instance_dict) # Remember, we are also counting the total lengths if json_dict.get('physicArrayLength') > 0: physicArrayTotal += json_dict.get('physicArrayLength') if json_dict.get('emotionArrayLength') > 0: emotionArrayTotal += json_dict.get('emotionArrayLength') if json_dict.get('academicArrayLength') > 0: academicArrayTotal += json_dict.get('academicArrayLength') if json_dict.get('communeArrayLength') > 0: communeArrayTotal += json_dict.get('communeArrayLength') if json_dict.get('etherArrayLength') > 0: etherArrayTotal += json_dict.get('etherArrayLength') # Append the totals to an array now that the 'for in' loop is done counts = [] counts.append(physicArrayTotal) counts.append(emotionArrayTotal) counts.append(academicArrayTotal) counts.append(communeArrayTotal) counts.append(etherArrayTotal) # Create an dictionart for all the totals word_array_dict = {'logCounts': counts} # Assemble the main_return_dict main_return_dict['all'].append(pie_dict) main_return_dict['all'].append(word_array_dict) main_return_dict['all'].append({ 'description_primary': 'The log information for every log you have written.' }) main_return_dict['all'].append( {'description_secondary': 'Use it wisely!'}) main_return_dict['all'].append({'title': 'Log Summary'}) # print the_dict return jsonify(**main_return_dict) # return json_item else: # Do nothing return 'You get nothing!'
def load_user(userid): db_user = mongo.db.users.find_one({'_id': ObjectId(str(userid))}) user = User(db_user) return user