def newsfeed(): if 'username' in session: # Display newsfeed if request.method == 'GET': username = session['username'] conn = dbconn2.connect(DSN) # Get photos from people you follow information = newsfeedOps.retrievePics(conn, username) # Renders page with photos if (information != None): return render_template('newsfeed.html', username=username, posts=information, profuser=session['username']) # Renders page without photos else: flash("Follow people to see pictures on your Newsfeed!") return render_template('newsfeed.html', username=username, posts=None, profuser=session['username']) # Adds comment to post else: username = session['username'] comment = request.form['comment'] time_stamp = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime()) post_id = request.form['post_id'] conn = dbconn2.connect(DSN) # Add comment to database newsfeedOps.addComment(conn, username, post_id, comment, time_stamp) return redirect(url_for('newsfeed', profuser=session['username'])) else: return redirect(url_for('loginProcess'))
def getAnswer(qid): print "getting to the getAnswer" try: connect = dbconn2.connect(DSN) if request.method == 'POST': print 'handling POST Answer' user = myhelperfunctions.getUID(connect, session['email']) print qid ans = request.form.get('answer') date = datetime.datetime.now() #print quest #print user #print date print 'answer' print ans if ans is not None: myhelperfunctions.add_answer(connect, user, qid, ans, date) print ans + "its not empty" print "this is where answer get would show up" result = myhelperfunctions.show_answers(connect, qid) print jsonify(result) return jsonify(result) except Exception as err: return jsonify([{'error': True, 'err': str(err)}])
def addEducation(): """Allows user to add an education entry to their profile. Reads information input with the addEducation.html form and inserts it into the job database""" conn = dbconn2.connect(DSN) if request.method == 'GET': userid = session.get('userid') if not userid: return redirect(url_for('login')) return render_template('home/addEducation.html') if request.method == 'POST': #get data from form institution = request.form.get('institution') major = request.form.get('major') secondmajor = request.form.get('secondmajor') degreetype = request.form.get('degreetype') rating = request.form.get('rating') review = request.form.get('review') country = request.form.get('country') state = request.form.get('state') if country != None and country != 'US': state = None userid = session.get('userid') #add education to the education database, associated with user via #userid mymessage = helperFunctions.addEducation(conn, userid, institution, major, secondmajor, degreetype, rating, review, country, state) return render_template('home/addEducation.html', message=mymessage)
def browseMentors(): """Allows users to browse the profiles of mentors, and filter the results shown according to specific parameters """ conn = dbconn2.connect(DSN) if request.method == "GET": userid = session.get('userid') if not userid: return redirect(url_for('login')) #fetch mentor profile info from the databse mentorinfo = helperFunctions.viewMentors(conn) return render_template('home/browseMentors.html', mentors=mentorinfo) #filter parameters if request.method == 'POST': #gather filter parameters from the form searchform = request.form.get('searchform') profession_search = request.form.get('profession_search') minage = request.form.get('minage') maxage = request.form.get('maxage') gender = request.form.getlist('gender') country = request.form.get('country') state = request.form.get('state') #don't allow user to select a state if they choose a non-US country if country != None and country != 'US': state = None #filter mentor profiles displayed on the page according to filter parameters mentorinfo = helperFunctions.filterMentors(conn, searchform, profession_search, minage, maxage, gender, country, state) return render_template('home/browseMentors.html', mentors=mentorinfo)
def browseJobs(): """Allows users to browse jobs submitted by mentors and filter these jobs according to specific fields """ conn = dbconn2.connect(DSN) if request.method == "GET": userid = session.get('userid') if not userid: return redirect(url_for('login')) #view job listings jobinfo = helperFunctions.browseJobs(conn) return render_template('home/browseJobs.html', jobs=jobinfo) if request.method == 'POST': #get optional filter parameters from form searchform = request.form.get('searchform') jobtype = request.form.get('jobtype') tasks = request.form.get('tasks') minsalary = request.form.get('minsalary') workExperience = request.form.getlist('workExperience') educationExperience = request.form.getlist('educationExperience') #filter jobs shown on the page according to the filter paramaters jobinfo = helperFunctions.filterJobs(conn, searchform, jobtype, tasks, minsalary, workExperience, educationExperience) return render_template('home/browseJobs.html', jobs=jobinfo)
def get_question_responses(question_id): DSN['db'] = 'helproom_db' conn = dbconn2.connect(DSN) curs = conn.cursor(MySQLdb.cursors.DictCursor) curs.execute('SELECT * FROM response where qid = %s;', (question_id, )) all_responses = curs.fetchall() return all_responses
def insert_question(course_id, email, text_input, tag): DSN['db'] = 'helproom_db' conn = dbconn2.connect(DSN) curs = conn.cursor(MySQLdb.cursors.DictCursor) curs.execute( 'INSERT into question (qid, vote_count, courseid, user_id, text_input, tag) values(%s, %s, %s, %s, %s, %s);', ('cid', '0', course_id, email, text_input, tag))
def get_all_tags(): DSN['db'] = 'helproom_db' conn = dbconn2.connect(DSN) curs = conn.cursor(MySQLdb.cursors.DictCursor) curs.execute('SELECT * FROM tag;') all_tags = curs.fetchall() return all_tags
def update_question(qid): DSN['db'] = 'helproom_db' conn = dbconn2.connect(DSN) curs = conn.cursor(MySQLdb.cursors.DictCursor) curs.execute('UPDATE question set vote_count = vote_count+1 where qid=%s;', (qid, )) return curs.fetchall()
def get_courses(): DSN['db'] = 'helproom_db' conn = dbconn2.connect(DSN) curs = conn.cursor(MySQLdb.cursors.DictCursor) curs.execute('SELECT cid,name FROM course;') all_course = curs.fetchall() return all_course
def check_voted(user, qid): DSN['db'] = 'helproom_db' conn = dbconn2.connect(DSN) curs = conn.cursor(MySQLdb.cursors.DictCursor) curs.execute('SELECT * FROM vote where user_id= %s and comment_id = %s;', (user, qid)) return curs.fetchall()
def createProject(): conn = dbconn2.connect(dsn) try: roleCheck = updateDB.getRole(conn, session) if 'uid' in session: uid = session['uid'] roleDB = updateDB.checkUserRole(conn, uid) if 'client' in roleDB['role']: if request.method == 'POST': projName = request.form['projectTitle'] projDur = request.form['duration'] projComp = request.form['compensation'] projRoles = request.form['rolesOpen'] projReq = request.form['requirements'] projDesc = request.form['description'] projCreator = uid if (projName == '' or projDur == '' or projComp == '' or projRoles == ''\ or projReq == '' or projDesc == ''): flash('Please fill out all fields.') else: updateDB.addProject(conn, projCreator, projName, projDur, projComp,\ projRoles, projReq, projDesc) flash ("Project Submitted") return render_template('project.html', role = roleCheck) else: return render_template('project.html', role = roleCheck) else: flash('Only clients have access to this page, please login with a client account') return redirect( url_for('index') ) else: flash('You are not logged in. Please login or join') return redirect( url_for('index') ) except Exception as e: flash(e) return redirect( url_for('index') )
def init(): dsn = dbconn2.read_cnf(".my.cnf") dsn['db'] = 'wzhang2_db' dsn['host'] = 'localhost' conn = dbconn2.connect(dsn) conn.autocommit(True) return conn
def browseProjects(): conn = dbconn2.connect(dsn) try: if 'uid' in session: uid = session['uid'] roleDB = updateDB.checkUserRole(conn, uid) roleCheck = updateDB.getRole(conn, session) if 'student' in roleDB['role']: if request.method == 'POST': pid = request.form['projectID'] result = updateDB.applyToProject(conn, uid, pid) if result == None: flash('You have already applied to project ' + pid + '. You cannot apply to a project twice. ') else: flash('You have successfully applied to project number ' + pid) projects = updateDB.getProjects(conn) else: projects = updateDB.getProjects(conn) return render_template('browse.html', projects = projects, role = roleCheck ) else: flash('Only students have access to this page, please login with a student account') else: flash('You are not logged in. Please login or join') except Exception as e: flash(e) return redirect( url_for('index') )
def clientProjects(): conn = dbconn2.connect(dsn) roleCheck = updateDB.getRole(conn, session) try: if 'uid' in session: uid = session['uid'] roleDB = updateDB.checkUserRole(conn, uid) if 'client' in roleDB['role']: if request.method == 'POST': pid = request.form['projectID'] updateDB.deleteProject(conn, pid) flash("Project Deleted") projects = updateDB.getUserProjects(conn, uid) return render_template('clientProjects.html', projects = projects, role = roleCheck ) else: flash('Only clients have access to this page, please login with a client account') return redirect( url_for('index') ) else: flash('You are not logged in. Please login or join') return redirect( url_for('index') ) except Exception as e: flash(e) return redirect( url_for('index') )
def projectApproval(): conn = dbconn2.connect(dsn) roleCheck = updateDB.getRole(conn, session) try: if 'uid' in session: uid = session['uid'] roleDB = updateDB.checkUserRole(conn, uid) if 'admin' in roleDB['role']: if request.method == 'POST': pid = request.form['projectID'] updateDB.approveProject(conn, uid, pid) flash("selection approved") projects = updateDB.getUnapprovedProjects(conn) return render_template('projectApproval.html', projects = projects, role = roleCheck ) else: flash('Only administrators have access to this page, please login with an admin account') return redirect( url_for('index') ) else: flash('You are not logged in. Please login or join') return redirect( url_for('index') ) except Exception as e: flash(e) return redirect( url_for('index') )
def join(): try: username = request.form['username'] passwd1 = request.form['password1'] passwd2 = request.form['password2'] if passwd1 != passwd2: flash('passwords do not match') return redirect(url_for('index')) hashed = bcrypt.hashpw(passwd1.encode('utf-8'), bcrypt.gensalt()) conn = dbconn2.connect(dsn) curs = conn.cursor(MySQLdb.cursors.DictCursor) curs.execute('SELECT loginname FROM users WHERE loginname = %s', [username]) row = curs.fetchone() if row is not None: flash('That username is taken') return redirect(url_for('index')) curs.execute('INSERT into users(loginname,password) VALUES(%s,%s)', [username, hashed]) session['username'] = username session['logged_in'] = True session['visits'] = 1 flash('Welcome to CodeMode, ' + username + '.') flash( 'To get started you may like to chose a subject to be quizzed on.') return redirect(url_for('user', username=username)) except Exception as err: flash('form submission error ' + str(err)) return redirect(url_for('index'))
def registerProcess(): # When get, return empty login page if request.method == 'GET': return register() else: name = request.form['name'] email = request.form['email'] username = request.form['username'] passwd = request.form['passwd'] comPasswd = request.form['comPasswd'] # Sends back to register page if not all the fields were filled in. if ((name == "") or (email == "") or (username == "") or (passwd == "") or (comPasswd == "")): flash("Please fill out all fields") return register() conn = dbconn2.connect(DSN) # Checks for available username if (accounts.validUsername(conn, username)): flash("Username is taken") return register() # Checks that password matches if (passwd != comPasswd): flash("Passwords do not match") return register() # Hash password and register new account hashed = bcrypt.hashpw(passwd.encode('utf-8'), bcrypt.gensalt()) accounts.registerUser(conn, username, hashed, name, email) flash("Registration successful") return redirect(url_for('loginProcess'))
def editRoom(roomID): conn = dbconn2.connect(DSN) # username = request.cookies.get('username') username = '******' print username building = functions.getReshall(roomID[:3]) roomNum = roomID[3:6] review = functions.getReview(conn, roomID) review = review[0]['review'] roomIDs = functions.getRoomNums(conn) if username is not None: if request.method == "GET": print("get method!") return render_template("editForm.html", roomID=roomID, building=building, roomNum=roomNum, userreview=review) else: # POST print("post method!") flooring = request.form['flooring'] review = request.form['review'] rating = request.form['overallRating'] print flooring print review print rating functions.updateReview(conn, username, roomID, review, rating, flooring) flash('Thanks for your review! The database has been updated.') return redirect(url_for('reviewedRooms', roomIDs=roomIDs)) else: # if there's no username found yet flash("No userid; please login first.") return render_template('login.html')
def treasurerUpdateAppeal(sofc, costID): conn = dbconn2.connect(DSN) if 'CAS_USERNAME' in session: username = session['CAS_USERNAME'] deadline = session['deadline'] orgName = T.orgSOFC(conn, sofc) treasurer = T.isTreasurerOrg(conn, username, orgName) date = datetime.datetime.now() canEdit = date <= deadline if treasurer: costID = int(costID) eventID = T.getEventID(conn, costID) act = request.form['submit'] if act == "update": explanation = request.form['explanation'] pdf = request.form.get('pdf', None) T.updateAppeal(conn, username, costID, explanation, pdf) elif act == "delete": T.deleteAppeal(conn, username, costID) eventID = T.getEventID(conn, costID) return redirect( url_for('treasurerEvent', sofc=sofc, eventID=eventID)) else: return redirect(url_for('login'))
def dictCursor(): global dbconn dsn = dbconn2.read_cnf('/home/hugh9/.my.cnf') dsn['db'] = 'janice' dbconn = dbconn2.connect(dsn) curs = dbconn.cursor(MySQLdb.cursors.DictCursor) return curs
def server(database): '''Returns a cursor to the database''' dsn = dbconn2.read_cnf('/students/dormdata/.my.cnf') dsn['db'] = database conn = dbconn2.connect(dsn) conn.autocommit(True) return conn.cursor(MySQLdb.cursors.DictCursor)
def addNewReview(jobID): conn = dbconn2.connect(DSN) job = getJobName(conn, jobID) jobName = job['positionName'] if 'bnum' in session: bnum = session['bnum'] if 'CAS_USERNAME' in session: username = session['CAS_USERNAME'] else: flash('Please login to view this page content.') return redirect(url_for('login_pg')) src, exists = getSrc(conn, bnum) if request.method == 'GET': return render_template('review_form.html', jobName=jobName, uName=username, src=src, picture_exists=exists) if request.method == 'POST': if request.form['submit'] == 'Submit Review': jobYear = request.form[('jobYear')] review = request.form[('review')] addJob = addJobRev(conn, bnum, jobID, jobYear, review) if not addJob: flash("A review already exists for this job and user.") else: flash("Review added successfully.") return redirect(url_for('job', jobID=jobID))
def cursor(database=DATABASE): """Establish the connection with the database. Will change in beta version so that only one connection is used throughout app.""" DSN = dbconn2.read_cnf() DSN['db'] = database conn = dbconn2.connect(DSN) return conn.cursor(MySQLdb.cursors.DictCursor)
def displayHome(): conn = dbconn2.connect(DSN) if 'CAS_USERNAME' in session: username = session['CAS_USERNAME'] else: flash('Please login to view this page content') return redirect(url_for('login_pg')) if 'CAS_ATTRIBUTES' in session: attribs = session['CAS_ATTRIBUTES'] if 'bnum' in session: bnum = session['bnum'] else: session['bnum'] = attribs['cas:id'] bnum = session['bnum'] firstname = attribs['cas:givenName'] username = attribs['cas:sAMAccountName'] opp.addUser(conn, bnum, firstname, username) #grabs the profile picture the user if it exists src, exists = getSrc(conn, bnum) return render_template('home.html', uName=username, opportunities=getOpps(conn), picture_exists=exists, src=src)
def adminDeadlines(): conn = dbconn2.connect(DSN) if 'CAS_USERNAME' in session: username = session['CAS_USERNAME'] admin = A.isAdmin(conn, username) if admin: act = request.form['submit'] # allocate funds for deadline if act == "allocateDeadline": deadline = request.form['deadline'] A.calcAllocated(conn, deadline) # creating new deadline if act == "addDeadline": fType = request.form['fType'] deadline = request.form['deadline'] appealsDeadline = request.form['appealsDeadline'] budgetFood = request.form['budgetFood'] budgetNonFood = request.form['budgetNonFood'] A.addDeadline(conn, deadline, fType, budgetFood, budgetNonFood) # deleting deadline if act == "delete": deadline = request.form['deadline'] A.deleteDeadline(conn, deadline) deadlineList = G.allDeadlines(conn) return render_template('adminDeadlines.html', username=username, deadlineList=deadlineList) else: return redirect(url_for('login'))
def adminOrgs(): conn = dbconn2.connect(DSN) if 'CAS_USERNAME' in session: username = session['CAS_USERNAME'] admin = A.isAdmin(conn, username) orgList = G.allOrgs(conn) if admin: act = request.form['submit'] # adding a new org for sofc funding if act == "add": name = request.form['name'] classification = request.form['classification'] sofc = request.form['sofc'] profit = request.form.get('profit', None) A.addOrg(conn, name, classification, sofc, profit) # deleting an org or revoking sofc funding status if act == "delete": name = request.form['name'] A.deleteOrg(conn, name) # updating org info if act == "update": sofc = request.form['name'] return redirect(url_for('displayUpdateOrg', sofc=sofc)) return displayAdminOrgs() else: return redirect(url_for('login'))
def adminUsers(): conn = dbconn2.connect(DSN) if 'CAS_USERNAME' in session: username = session['CAS_USERNAME'] admin = A.isAdmin(conn, username) if admin: act = request.form['submit'] # adding a new treasurer if act == "addTreasurer": orgName = request.form['orgName'] treasurer = request.form['username'] A.addTreasurer(conn, orgName, treasurer) # removing user from being an treasurer if act == "removeTreasurer": orgName = request.form['orgName'] treasurer = request.form['username'] A.deleteTreasurer(conn, orgName, treasurer) # adding user to sofc group if act == "addSOFC": SOFC = request.form['username'] A.addSOFC(conn, SOFC) # removing user from sofc group if act == "removeSOFC": SOFC = request.form['username'] A.deleteSOFC(conn, SOFC) return displayAdminUsers() else: return redirect(url_for('login'))
def loginProcess(): # When get, return empty login page if request.method == 'GET': if 'username' in session: return redirect(url_for('newsfeed')) return render_template('login.html', title='Login') else: username = request.form['username'] passwd = request.form['passwd'] conn = dbconn2.connect(DSN) # If valid username and password if (accounts.validUsername(conn, username)): storedHash = accounts.getHashedPassword(conn, username) if (bcrypt.hashpw( passwd.encode('utf-8'), storedHash.encode('utf-8')) == storedHash.encode('utf-8')): # Save username to the session session['username'] = username return redirect(url_for('newsfeed')) else: # bad password flash("Login failed. Please try again") return render_template('login.html', title='Login') else: # bad username flash("Login failed. Please try again") return render_template('login.html', title='Login')
def connect(database, user): ''' Connects to the provided database using my cnf file and returns the connection ''' dsn = dbconn2.read_cnf('/students/' + user + '/.my.cnf') dsn['db'] = database conn = dbconn2.connect(dsn) return conn
def home(): #display all the rooms on the home page if request.method == 'GET': conn = dbconn2.connect(DSN) curs = conn.cursor(MySQLdb.cursors.DictCursor) curs.execute('SELECT roomID FROM room') roomsData = curs.fetchall() return render_template('home.html', roomsData=roomsData)
This is a file that includes helper functions that helps the CGI python file collect the data and display what the user wants. Last updated: 5/15/2016 ''' #imports import MySQLdb import dbconn2 #setup dsn = dbconn2.read_cnf('/students/calpal/.my.cnf') dsn['db'] = 'random' #current database being used dsn['host'] = 'localhost' conn = dbconn2.connect(dsn) curs = conn.cursor() #queryCourse() #Takes in the crn of a course and returns the entire course entry in raw data (in a tuple format) def queryCourse(crn): if (crn == '' or crn is None): return "Please enter CRN" curs.execute("SELECT * FROM course_data WHERE CRN = %s",(crn,)) courseList = curs.fetchone() if courseList is None or courseList == '': return "CRN not in database" return courseList #checkUser() #Takes in bNum of the student and checks if the student currently has any courses in their calendar