def search(): try: if 'username' in session: employee_ID = session['username'] else: flash('you are not logged in. Please login or join to grab shifts') return redirect(url_for('index')) except Exception as err: flash('some kind of error ' + str(err)) return redirect(url_for('index')) if request.method == "GET": return render_template('search.html', title="Search by Employee") else: conn = dbi.connect() if (request.form.get('employee-username') == ""): flash('Please submit a non-empty form.') return render_template('search.html', title="Search by Employee") else: username = request.form.get('employee-username') existence = database.usernameAvailability(conn, username) if existence: return redirect(url_for('usershifts', username=username)) else: flash("Employee does not exist.") return render_template('search.html', title="Search by Employee")
def input_availability(): try: if 'username' in session: username = session['username'] else: flash( 'you are not logged in. Please login or join to input availability' ) return redirect(url_for('index')) except Exception as err: flash('some kind of error ' + str(err)) return redirect(url_for('index')) if request.method == "POST": submit = request.form.get('submit') day = request.form.get('day') start_time = str(request.form.get('start_time')) end_time = str(request.form.get('end_time')) conn = dbi.connect() database.insertAvailability(conn, username, start_time, end_time, day) flash("availability updated") return render_template('input_availability.html', title="Input Availability") else: return render_template('input_availability.html', title="Input Availability")
def request_coverage(): conn = dbi.connect() try: if 'username' in session: employee_ID = session['username'] else: flash('you are not logged in. Please login or join to grab shifts') return redirect(url_for('index')) except Exception as err: flash('some kind of error ' + str(err)) return redirect(url_for('index')) if request.method == 'GET': data = helper.getAllEmployees(conn) info = database.getSpecEmployeeShifts(conn, employee_ID) length = len(info) return render_template('request_coverage.html', shifts=info, length=length, title="Request Coverage") else: shift = request.form.get('shiftid') print(shift) print(employee_ID) database.requestCoverage(conn, employee_ID, shift) flash('You have successfully requested coverage') return render_template('request_coverage.html', title="Request Coverage")
def loginA(): try: username = request.form['username'] passwd = request.form['password'] conn = dbi.connect() curs = dbi.dict_cursor(conn) curs.execute( '''SELECT username,password FROM admin WHERE username = %s''', [username]) row = curs.fetchone() if row is None: # Same response as wrong password, # so no information about what went wrong flash('login incorrect. Try again or join') return redirect(url_for('index')) hashed = row['password'] hashed2 = bcrypt.hashpw(passwd.encode('utf-8'), hashed.encode('utf-8')) hashed2_str = hashed2.decode('utf-8') if hashed2_str == hashed: flash('successfully logged in as ' + username) session['username'] = username session['logged_in'] = True session['visits'] = 1 return redirect(url_for('user', username=username)) else: flash('login incorrect. Try again or join') return redirect(url_for('index')) except Exception as err: flash('form submission error ' + str(err)) return redirect(url_for('index'))
def join(): try: username = request.form['username'] passwd1 = request.form['password1'] passwd2 = request.form['password2'] name = request.form['name'] email = request.form['email'] if passwd1 != passwd2: flash('passwords do not match') return redirect(url_for('index')) hashed = bcrypt.hashpw(passwd1.encode('utf-8'), bcrypt.gensalt()) hashed_str = hashed.decode('utf-8') conn = dbi.connect() curs = dbi.cursor(conn) try: curs.execute( '''INSERT INTO employee1(username,password,name,email) VALUES(%s,%s,%s,%s)''', [username, hashed_str, name, email]) conn.commit() except Exception as err: flash('That username is taken: {}'.format(repr(err))) return redirect(url_for('index')) session['username'] = username session['logged_in'] = True session['visits'] = 1 return redirect(url_for('user', username=username)) except Exception as err: flash('form submission error ' + str(err)) return redirect(url_for('index'))
def favorite(): '''Adds or removes application from list of favorites when button is clicked.''' ###This should be done with Ajax so we don't have to reload the entire page. conn = dbi.connect() if (session.get('uid')): #if it exists uid = session['uid'] # Get data from form: data = request.form link = data['link'] fave = data['fave'] print('Link:' + link) print('Fave:' + fave) # Update database # if (fave == 0): if sqlHelper.isFavorite(conn, uid, link) != True: sqlHelper.handleFavorite(uid, link) else: pass # response dictionary resp_dic = {'link': link, 'fave': fave} print("respLink:" + resp_dic['link']) return jsonify(resp_dic) else: flash('You must be logged in to add to your favorites.') return redirect(url_for('index'))
def register(conn, username, password, email, school): '''Insert movie into database with tt, title, and release year.''' conn = dbi.connect() curs = dbi.cursor(conn) sql = '''insert into user (uid, password1, email, school) values(%s, %s, %s, %s);''' curs.execute(sql, [username, password, email, school]) conn.commit()
def deleteReview(uid, compName): #Given the uid and compName, deletes a review from the database. conn = dbi.connect() curs = dbi.cursor(conn) curs.execute('''delete from review where uid = %s and compName = %s;''', [uid, compName]) conn.commit()
def index(): '''Displays home page with most recent database.''' conn = dbi.connect() curs = dbi.cursor(conn) internships = sqlHelper.getInternships(conn) total = sqlHelper.getTotal(conn)['count(*)'] return render_template('main.html', internships=internships, total=total)
def user(uid): ''' Displays a user's name, friends, and playlists. Allows logged-in user to follow a friend. :param uid: unique id for a user :returns: the user's profile page ''' conn = dbi.connect() if (request.method == 'GET'): if 'CAS_USERNAME' in session: # information for the user whose page we are visiting user = userpage.get_user_from_id(conn, uid) friendsList = userpage.get_friends(conn, uid) playlists = userpage.get_user_playlists(conn, uid) return render_template("user.html", user= user, page_title = user['display_name'], friendsList = friendsList, playlists = playlists) else: flash('Please log in to access profile page') return redirect(url_for("explore")) else: # POST to follow friend friendId = request.form.get('friend') currentUser = request.form.get('currentUser') userpage.add_follow(conn,friendId,currentUser) currentInfo = userpage.get_user_from_id(conn,currentUser) return jsonify({'currentUser':currentInfo['display_name']})
def removeFavorite(uid, link): # Removes application from users' list of favorites''' conn = dbi.connect() curs = dbi.cursor(conn) sql = '''delete from favorites where uid = %s and link = %s''' curs.execute(sql, [uid, link]) conn.commit()
def saved(): conn = dbi.connect() if request.method == 'GET': if (session.get('uid')): #if it exists uid = session['uid'] if request.method == "GET": saved = sqlHelper.getFavorites(conn, uid) return render_template('saved.html', internships=saved) else: flash('You must be logged in to add to your favorites.') return redirect(url_for('index')) else: if (session.get('uid')): #if it exists uid = session['uid'] # Get data from form: data = request.form link = data['link'] print('Link:' + link) # Update database # remove from favs sqlHelper.removeFavorite(uid, link) # response dictionary resp_dic = {'link': link} print("respLink:" + resp_dic['link']) return jsonify(resp_dic)
def insertCompany(compName): # Given a company name, inserts it into the company table conn = dbi.connect() curs = dbi.cursor(conn) curs.execute('''INSERT INTO company(compName) values (%s);''', [compName]) conn.commit()
def handleFavorite(uid, link): # Adds application to users' list of favorites, or removes if needed conn = dbi.connect() curs = dbi.cursor(conn) curs.execute('''insert into favorites(uid, link) values (%s, %s);''', [uid, link]) conn.commit()
def booking(): conn = dbi.connect() customer = request.form['customer'] num_days = request.form['num_days'] allergies = request.form['allergies'] extra_care = request.form['extracare'] pet_name = request.form['pname'] species = request.form['ptype'] sex = request.form['gender'] neutered = request.form['neutered'] """If the customer is already in system""" if f.customerexists(customer, conn) != None: person_id = f.customerexists(customer, conn) person_id = person_id['person_id'] """Inserts the pet into dict from form details""" p_id = f.insertPet(person_id, pet_name, species, sex, neutered, conn) p_id = p_id['p_id'] print(p_id) f.makeBooking(num_days, allergies, extra_care, p_id, person_id, conn) """Completes booking process""" return redirect(url_for('booked', person_id=person_id, p_id=p_id)) else: person_id = f.insertCustomer(customer, conn) """ inserts customer if doesn't exist""" person_id = person_id['person_id'] pp_id = f.insertPet(person_id, pet_name, species, sex, neutered, conn) """Inserts info on a pet from form""" p_id = f.getpid(person_id, conn) p_id = p_id['p_id'] f.makeBooking(num_days, allergies, extra_care, p_id, person_id, conn) """Completes booking process""" return redirect(url_for('booked', person_id=person_id, p_id=p_id))
def getRecommended(): conn = dbi.connect() curs = dbi.dict_cursor(conn) curs.execute('''SELECT course.cid, course.title FROM course LIMIT 3''') results = curs.fetchall() return results
def upload(): '''Displays upload page, and allows user to submit an internship link to database.''' conn = dbi.connect() uid = session['uid'] # These forms go to the upload route if (session.get('uid')): #if it exists if request.method == 'GET': return render_template('upload.html') else: compName = request.form['compName'] link = request.form['link'] role = request.form['role'] seasonList = request.form.getlist('season') season = ','.join([str(elem) for elem in seasonList]) year = request.form['year'] experienceList = request.form.getlist('experience') experience = ','.join([str(elem) for elem in experienceList]) print(experience) print(uid) # Insert to database lock.acquire() if sqlHelper.companyExists(compName) == 0: sqlHelper.insertCompany(compName) lock.release() sqlHelper.insertApplication(link, compName, uid, role, season, year, experience) flash('Internship at ' + compName + ' was uploaded successfully') return render_template('upload.html') #User must login before uploading else: flash('You must be logged in to upload information.') return redirect(url_for('index'))
def submitListing(): conn = dbi.connect() #renders form if get if request.method == 'GET': stateCodes = ["AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DC", "DE", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY"] return render_template('submitListing.html', stateCodes = stateCodes) #otherwise adds inserted data into listing table else: address = request.form.get('address') listingTitle = request.form.get('listingTitle') username = request.form.get('username') price = request.form.get('price') city = request.form.get('city') state = request.form.get('state') bedroomNum = request.form.get('bedroomNum') roommatesNum = request.form.get('roommatesNum') bathroomNum = request.form.get('bathroomNum') sqrft = request.form.get('sqrft') area = request.form.get('area') nearbySchools = request.form.get('nearbySchools') openDate = request.form.get('openDate') closeDate = request.form.get('closeDate') description = request.form.get('description') availability = request.form.get('availability') modules.insertListing(conn, address, listingTitle, username, price, city, state, bedroomNum, roommatesNum, bathroomNum, sqrft, area, nearbySchools, openDate, closeDate, description, availability) flash("Listing successfully submitted!") return render_template('submitListing.html')
def createPlaylist(): ''' Returns rendered insert template if get method, or if post method, creates a playlist and flashes a link to the new playlist ''' conn = dbi.connect() if 'uid' in session: user_id = session['uid'] if request.method == 'GET': return render_template('createPlaylist.html', page_title="Create Playlist") else: #inserting movie action, making sure input is valid pName = request.form.get('playlist-name') pGenre = request.form.get('playlist-genre') #check if the playlist name already exists start_transaction(conn) # ensure thread safety if playlist.check_unique_playlist_name(conn, pName, user_id): playlist.createPlaylist(conn,pName,pGenre, user_id) pid = userpage.get_playlist(conn, pName, user_id)['playlist_id'] flash(pName + ' has been created!') commit_transaction(conn) # complete transaction return redirect(url_for('playlistPage', pid = pid)) else: #if playlist name by that user already in database commit_transaction(conn) # complete transaction flash('''This playlist name already exists in database, try a different name!''') return redirect(url_for('createPlaylist')) else: flash('Please log in to create playlist!') return redirect(url_for('explore'))
def explore(): """ This is the home page, listing out the genres currently existing in our database and allowing the user to search for a song, album, playlist, artist, or user. """ conn = dbi.connect() # acquire session information print('Session keys: ',list(session.keys())) for k in list(session.keys()): print(k,' => ',session[k]) if '_CAS_TOKEN' in session: token = session['_CAS_TOKEN'] if 'CAS_USERNAME' in session: is_logged_in = True username = session['CAS_USERNAME'] print(('CAS_USERNAME is: ',username)) else: is_logged_in = False username = None print('CAS_USERNAME is not in the session') # extract genres from the database to display genres = songPage.get_genres(conn) if 'CAS_USERNAME' in session: is_logged_in = True return render_template('main.html',page_title='home | coda', genres=genres, username=username) else: return render_template('login.html')
def getRecommended(): '''Gets recommended courses to display on the home page''' conn = dbi.connect() curs = dbi.dict_cursor(conn) curs.execute('''SELECT course.cid, course.title FROM course LIMIT 3''') results = curs.fetchall() return results
def lookupLastServed(fid): ''' return tuple of a food's last served location, date last served ''' conn = dbi.connect() curs = dbi.cursor(conn) curs.execute("select diningHall.name, lastServed from food inner join diningHall using (did) where fid = %s;", [fid]) return curs.fetchone()
def lookupFoodItem(fid): ''' return dictionary of a food's name, type, description, preference, label given an id ''' conn = dbi.connect() curs = dbi.dict_cursor(conn) curs.execute("select name, ingredients, preference, allergen, type from food inner join labels using (fid) where fid = %s;", [fid]) return curs.fetchone()
def insertReview(uid, compName, reviewText): #Given the uid, compName, and review, inserts a review into the database. conn = dbi.connect() curs = dbi.cursor(conn) curs.execute( '''insert into review(uid, compName, reviewText) values (%s, %s, %s);''', [uid, compName, reviewText]) conn.commit()
def addSyllabus(cid, syl): conn = dbi.connect() curs = dbi.dict_cursor(conn) query = curs.execute( ''' UPDATE course SET syl = (%s) WHERE cid = (%s)''', [syl, cid]) conn.commit()
def lookupComments(fid): ''' return a list of dictionaries for each comment for a given food item and with the comment's rating and user ''' conn = dbi.connect() curs = dbi.dict_cursor(conn) curs.execute("select username, rating, comment from feedback where fid = %s;", [fid]) return curs.fetchall()
def updateFoodItem(fid, ingredients): ''' edit food item and commit changes ''' conn = dbi.connect() curs = dbi.dict_cursor(conn) curs.execute("update labels set ingredients = %s where fid = %s;", [ingredients, fid]) conn.commit()
def search(): conn = dbi.connect() if request.method =='GET': return render_template('search.html') else: role = request.form['role'] appsList = sqlHelper.getByRole(conn, role) return render_template('searchResults.html', internships = appsList)
def addWebsite(cid, web): conn = dbi.connect() curs = dbi.dict_cursor(conn) query = curs.execute( ''' UPDATE course SET web = (%s) WHERE cid = (%s)''', [syl, web]) conn.commit()
def profile(username): if request.method == 'GET': conn = dbi.connect() info = query.get_user_info(conn,username) return render_template('profile.html', info=info, username=username) else: return render_template('home.html')