def createTopic(group_id=None): """loads the create topic page""" form = TopicForm() if form.validate_on_submit(): topic = DatabaseManager.addTopic(user_id=current_user.id,\ title=form.title.data,body=form.body.data,group_id=group_id) flash('Topic created!','info') ## User will be automatically subscribed to a topic they themselves create. DatabaseManager.addSubscription(current_user.id, topic.id) return redirect(url_for('viewTopic',id=topic.id)) return render_template('create_topic.html', title='Create New Topic', form=form)
def editComment(id): """loads the form/page to edit a comment""" comment = DatabaseManager.getComment(id) form = CommentForm(comment=comment.body) if DatabaseManager.checkCommentAuthor(current_user,comment): if form.validate_on_submit(): DatabaseManager.editComment(id=id,body=form.comment.data) return redirect(url_for('viewTopic',id=comment.topic_id)) return render_template('edit_comment.html', title='Edit Comment',form=form,comment=comment) else: flash('You are not eligible to edit this comment','error') return redirect(url_for('home'))
def editTopic(id): """loads the form/page to edit a post""" form = TopicForm() topic = DatabaseManager.getTopic(id) if DatabaseManager.checkTopicAuthor(current_user,topic): if form.validate_on_submit(): DatabaseManager.editTopic(id=id,title=form.title.data, body=form.body.data) return redirect(url_for('viewTopic',id=id)) return render_template('edit_topic.html', title='Edit Topic',form=form,topic=topic) else: flash('You are not elgible to edit this topic','error') return redirect(url_for('home'))
def index(): """loads the index page""" users = DatabaseManager.getAllUsers() topics = DatabaseManager.getAllPublicTopics() comments = DatabaseManager.getAllComments() numNots = DatabaseManager.countNotifications(current_user) form = FindUserForm() if form.validate_on_submit(): user = DatabaseManager.getUserByUsername(form.username.data) if user is None: flash('No such user exists','error') else: return redirect(url_for('generalProfile',id=user.id)) return render_template('index.html', title='Home', users=users, topics=topics, comments=comments, form=form, numNots=numNots)
def get_ride_requests(ride_id, user_id): all_requests_on_given_ride = [] sql = "SELECT * FROM requests WHERE ride_id = %s" """ Check if user exists """ if check_user(user_id): try: with DatabaseManager() as cursor: if check_ride(ride_id): cursor.execute(sql, [ride_id]) results = cursor.fetchall() if results: for result in results: all_requests_on_given_ride.append(request_json(result[0], result[1], result[2], result[3])) return { "Ride's requests": all_requests_on_given_ride } return { "message": "Ride has no requests" } return { "Message": "Ride not Found" } except Exception as e: logging.error(e) return { "message": "You are not registered, Register to request ride" }
def create_request(self): sql = "INSERT INTO requests (ride_id, requestor_id, status) VALUES (%s, %s, %s) RETURNING id" """ Check if user exists """ if check_user(self.user_id): try: with DatabaseManager() as cursor: if check_ride(self.ride_id): cursor.execute( sql, (self.ride_id, self.user_id, self.status)) if cursor.fetchone(): return { "message": "request made successfully", "code": 201 } return { "Message": "Failed to make request" } return { "message": "Ride not found", "code": 400 } except Exception as e: return e else: return { "message": "You are not registered, Register to request ride", "code": 401 }
def test_registration(self): response = register(self.app, 'Tester', '*****@*****.**', 'password!', 'password!') self.assertEqual(response.status_code, 200) self.assertIn(b'Congratulations, you have successfully registered.', response.data) u = DatabaseManager.getUser(1) self.assertEqual(u.username, "Tester")
def check_ride(ride_id): with DatabaseManager() as cursor: """ Check if ride exists """ cursor.execute("SELECT id FROM rides WHERE id = %s", [ride_id]) exists = cursor.fetchone() return exists
def createGroup(): """loads the form/page to create a group""" ## Allows current user to create a new group form = GroupForm() if form.validate_on_submit(): group_id = DatabaseManager.addGroup(name=form.name.data) return redirect(url_for('viewGroup',id=group_id)) return render_template('create_group.html',form=form)
def register(): """loads the register template/forms""" ## Check if current user is already logged in if current_user.is_authenticated: return redirect(url_for('index')) ## Create FlaskForm child object defined in forms.py form = RegistrationForm() ## Checks if request is POST request and validates form This also checks ## for duplicate usernames/emails and matching password fields if form.validate_on_submit(): ## Create new user and add to database DatabaseManager.addUser(form.username.data, form.email.data, \ form.password.data) return redirect(url_for('login')) ## If form isn't valid we send user back to registration page ## and display correct error messages return render_template('register.html', title='Register', form=form)
def check_user(user_id): with DatabaseManager() as cursor: """ Check if user exists """ cursor.execute("SELECT id FROM users WHERE id = %s", [user_id]) exists = cursor.fetchone() return exists
def check_request(request_id): with DatabaseManager() as cursor: """ Check if request exists """ cursor.execute("SELECT id FROM requests WHERE id = %s", [request_id]) exists = cursor.fetchone() if not exists: return False return True
def searchUser(): """loads the functionality of the search bar for searching for users.""" if g.profile_search.validate_on_submit(): user = DatabaseManager.getUserByUsername(g.profile_search.username.data) if user is None: flash('No such user exists','error') return redirect(url_for('home')) else: return redirect(url_for('generalProfile',id=user.id)) else: return redirect(url_for('home'))
def test_check_topic_author(self): response1 = register(self.app, 'Tester', '*****@*****.**', 'password!', 'password!') self.assertEqual(response1.status_code, 200) response2 = register(self.app, 'Tester2', '*****@*****.**', 'password!', 'password!') self.assertEqual(response2.status_code, 200) response3 = login(self.app, 'Tester', 'password!') self.assertEqual(response3.status_code, 200) response4 = create_topic(self.app, 1, "the topic title", "the topic body") self.assertEqual(response4.status_code, 200) self.assertIn(b'Topic created!', response4.data) t = DatabaseManager.getTopic(1) u1 = DatabaseManager.getUserByUsername("Tester") u2 = DatabaseManager.getUserByUsername("Tester2") result1 = DatabaseManager.checkTopicAuthor(u1, t) result2 = DatabaseManager.checkTopicAuthor(u2, t) self.assertTrue(result1) self.assertFalse(result2)
def not_approved(request_id): with DatabaseManager() as cursor: """ Check if request is not pending """ cursor.execute("SELECT status FROM requests WHERE id = %s", [request_id]) status = cursor.fetchone() if status[0] != "Pending": return "approved" else: return "not_approved"
def login(): """Logs a user in""" ## Check if current user is already logged in if current_user.is_authenticated: return redirect(url_for('index')) ## Create FlaskForm child object defined in forms.py form = LoginForm() if form.validate_on_submit(): ## Check user submitted information with database via DatabaseManager ## and if correct log in user under account matching that information return DatabaseManager.login(form.username.data, form.password.data, \ form.remember_me.data) ## If information does not match any accounts, return user to login page return render_template('login.html', title='Sign In', form=form)
def create_notification(self): sql = """INSERT INTO notifications (user_id, request_id, message) VALUES( %s, %s, %s) RETURNING id""" try: with DatabaseManager() as cursor: cursor.execute(sql, (self.user_id, self.request_id, self.message)) results = cursor.fetchone() if results: return not_json(results[0], results[1], results[2], results[3]) return "Failed to create notification" except Exception as e: logging.error(e)
def approve_request(request_id, user_id, status): if check_user(user_id): if check_request(request_id): try: with DatabaseManager() as cursor: cursor.execute( "SELECT ride_id FROM requests WHERE id = '%s'" % request_id) ride_id = cursor.fetchone() # This sql determines whether the user to approve request is owner of ride offer sql = """SELECT creator_id, ref_no FROM rides WHERE id = %s AND creator_id = %s""" cursor.execute(sql, (ride_id, user_id)) results = cursor.fetchone() if results: creator_id = str(results[0]) ride_ref_no = results[1] cursor.execute( "SELECT l_name FROM users WHERE id = %s", creator_id) driver = cursor.fetchone() update_sql = "UPDATE requests SET status = '%s' WHERE id = '%s'" % ( status.title(), request_id) if status.title() == "Y": message = "%s Accepted you to join ride %s" % ( driver[0], ride_ref_no) else: message = "%s Rejected you to join ride %s" % ( driver[0], ride_ref_no) notification = Notification( user_id, request_id, message) Notification.create_notification(notification) cursor.execute(update_sql) return {"Message": "Approval action was successful"} else: return {"Message": "Access Denied"} except Exception as e: logging.error(e) else: return {"Message": "Request not found"} else: return {"message": "You are not registered, Register to request ride"}
def get_notifications(): sql = "SELECT * FROM notifications" notifications = [] try: with DatabaseManager() as cursor: cursor.execute(sql) results = cursor.fetchall() if results: print(results) for notification in results: notifications.append( not_json(notification[0], notification[1], notification[2], notification[3])) print(notifications) return {"notifications": notifications} return "no results" except Exception as e: logging.error(e)
def viewGroup(id): """loads the form/page to view a group""" group = DatabaseManager.getGroup(id) leaveGroup = LeaveGroupForm(prefix="leaveGroup") if DatabaseManager.checkMember(current_user,group): form = AddUserForm(prefix="form") if form.submit.data and form.validate_on_submit(): user = DatabaseManager.getUserByUsername(form.username.data) if user is None: flash('No such user exists','error') else: DatabaseManager.addGroupMember(user=user,group=group) flash('You have successfully added a user to the group','info') return render_template('group.html', group=group, title=group.name,form=form,leaveGroup=leaveGroup) elif leaveGroup.submit.data and leaveGroup.validate_on_submit(): DatabaseManager.leaveGroup(current_user,group) flash('You have left the group','info') return redirect(url_for('home')) return render_template('group.html', group=group, title=group.name,form=form,leaveGroup=leaveGroup) else: flash('You are not a member of the specified group','error') return redirect(url_for('home'))
def myProfile(): subs = DatabaseManager.getUserSubscriptions(current_user.id) notifications = DatabaseManager.getUserNotifications(current_user.id) return render_template('my_profile.html', title = 'My Profile', subs=subs, nots=notifications)
def run_quickstart(self): from fuzzywuzzy import fuzz # [START language_quickstart] # Imports the Google Cloud client library # [START language_python_migration_imports] from google.cloud import language from google.cloud.language import enums from google.cloud.language import types # [END language_python_migration_imports] from database import DatabaseManager, Note dataIn = DatabaseManager("notes") dataOut = DatabaseManager("super_notes") # Instantiates a client # [START language_python_migration_client] client = language.LanguageServiceClient() # [END language_python_migration_client] text1 = dataOut.get_note_key(self.note1_key)["note"] text2 = dataIn.get_note_key(self.note2_key)["note"] # __________________________ # READ VALUE 1 # __________________________ # with open('input1.txt', 'r') as file: # text1 = file.read().replace('\n', '') # ___________________________ # READ VALUE 2 # ___________________________ # with open('input2.txt', 'r') as file2: # text2 = file2.read().replace('\n', '') words1 = text1.split(".") words2 = text2.split(".") for x in words1: if (x[:1] == " "): x = x[1:] for x in words2: if (x[:1] == " "): x = x[1:] keywords1 = [] key_sentances1 = "" key_sent_array_1 = [] keywords2 = [] key_sentances2 = "" key_sent_array_2 = [] # The text to analyze document1 = types.Document(content=text1, type=enums.Document.Type.PLAIN_TEXT) document2 = types.Document(content=text2, type=enums.Document.Type.PLAIN_TEXT) outputText = "" # Detects the sentiment of the text response1 = client.analyze_entities( document=document1, encoding_type='UTF32', ) for entity in response1.entities: if entity.salience > 0.015: keywords1.append(entity.name) print('=' * 20) print('name: {0}'.format(entity.name)) print('type: {0}'.format(entity.type)) print('metadata: {0}'.format(entity.metadata)) print('salience: {0}'.format(entity.salience)) response2 = client.analyze_entities( document=document2, encoding_type='UTF32', ) for entity in response2.entities: if entity.salience > 0.015: keywords2.append(entity.name) print('=' * 20) print('name: {0}'.format(entity.name)) print('type: {0}'.format(entity.type)) print('metadata: {0}'.format(entity.metadata)) print('salience: {0}'.format(entity.salience)) print("Keys 1:", keywords1) print("Keys 2:", keywords2) for x in words1: for i in keywords1: if (x.find(i) > -1) and x not in key_sentances1: key_sentances1 += x + "\n" key_sent_array_1.append(x) for x in words2: for i in keywords2: if (x.find(i) > -1) and x not in key_sentances2: key_sentances2 += x + "\n" key_sent_array_2.append(x) #print(key_sentances2) #out = open("output1.txt", "w") #out.write(key_sentances1) #out.close() #out = open("output2.txt", "w") #out.write(key_sentances2) #out.close() newVals = [" "] for x in key_sent_array_1: canAdd = True for i in newVals: Token_Set_Ratio = fuzz.token_set_ratio(x, i) if Token_Set_Ratio > 80: canAdd = False if canAdd: newVals.append(x) for x in key_sent_array_2: canAdd = True for i in newVals: Token_Set_Ratio = fuzz.token_set_ratio(x, i) if Token_Set_Ratio > 50: canAdd = False if canAdd: newVals.append(x) newValsString = "" for x in newVals: newValsString += x + "\n" #writing to database super_note = Note(2, "physics", newValsString) dataOut.add_note_to_db(super_note) #_______________________________________ # ADDING OUTPUT #_______________________________________ # final = open("final.txt", "w") # final.write(newValsString) # final.close() return newValsString # n = NoteAnalysis("-LqyiulvtclaFSFsC4_Q", "-Lqyl7NHN9vWsMeJYBIM")
def logout(): """logs a user out""" return DatabaseManager.logout();
def test_group_table_empty(self): groups = DatabaseManager.getAllGroups() self.assertEqual(len(groups), 0, "Group table is not empty.")
def test_comment_table_empty(self): comments = DatabaseManager.getAllComments() self.assertEqual(len(comments), 0, "Comment table is not empty")
def test_user_table_empty(self): users = DatabaseManager.getAllUsers() self.assertEqual(len(users), 0, "User table is not empty.")
def viewTopic(id): """Loads the form/page to view a post""" form = CommentForm() sub_btn = SubscriptionForm() unsub_btn = UnsubscriptionForm() topic = DatabaseManager.getTopic(id) DatabaseManager.removeNotification(current_user.id, id) if topic.group_id is not None: group = DatabaseManager.getGroup(topic.group_id) if DatabaseManager.checkMember(current_user,group): if form.validate_on_submit(): DatabaseManager.addComment(user_id=current_user.id,topic_id=id,body=form.comment.data) DatabaseManager.notifyUsers(id) return redirect(url_for('viewTopic',id=id)) if request.method == "POST" and request.form['btn'] == "sub": ## add topic to user subscriptions DatabaseManager.addSubscription(current_user.id, id) return redirect(url_for('viewTopic',id=id)) elif request.method == "POST" and request.form['btn'] == "unsub": ## Remove the topic from user subscriptions DatabaseManager.removeSubscription(current_user.id, id) return redirect(url_for('viewTopic',id=id)) if DatabaseManager.checkForSub(current_user.id, id): return render_template('post.html', title='View Topic',\ topic=topic,form=form,btn=unsub_btn,val="unsub") else: return render_template('post.html', title='View Topic',\ topic=topic,form=form,btn=sub_btn,val="sub") else: flash('You are not a member of the group this topic belongs to','error') return redirect(url_for('home')) else: if form.validate_on_submit(): DatabaseManager.addComment(user_id=current_user.id,topic_id=id,body=form.comment.data) DatabaseManager.notifyUsers(id) return redirect(url_for('viewTopic',id=id)) if request.method == "POST" and request.form['btn'] == "sub": ## add topic to user subscriptions DatabaseManager.addSubscription(current_user.id, id) return redirect(url_for('viewTopic',id=id)) elif request.method == "POST" and request.form['btn'] == "unsub": ## Remove the topic from user subscriptions DatabaseManager.removeSubscription(current_user.id, id) return redirect(url_for('viewTopic',id=id)) ## Check if user is subscribed to this topic. If true, show unsub button if DatabaseManager.checkForSub(current_user.id, id): return render_template('post.html', title='View Topic',\ topic=topic,form=form,btn=unsub_btn,val="unsub") else: return render_template('post.html', title='View Topic',\ topic=topic,form=form,btn=sub_btn,val="sub")
def generalProfile(id): """loads the form/page to view any users profile""" user = DatabaseManager.getUser(id) if user is None: return render_template('500.html') return render_template('general_profile.html', user=user, title = 'User Profile')
def test_topic_table_empty(self): topics = DatabaseManager.getAllTopics() self.assertEqual(len(topics), 0, "Topic table is not empty.")