def load_logged_in_user(): """ Se un utente è memorizzato nella sessione, caricare l'oggetto utente dal database in g.user """ username = session.get('username') if username is None: g.user = None # se l'utente non è caricato vede se sono stati caricati dei dati in UserPreference if UserPreferences.loaded: db = get_db() # carica i dati nella table types for type in Types: percentage = UserPreferences.getPercentage(type) try: if percentage == 0: raise Exception("percentage is 0") db.execute( '''INSERT INTO types (username,type,percentage) VALUES (?,?,?)''', (UserPreferences.username, type.name.lower(), percentage)) db.commit() except sqlite3.IntegrityError: db.execute( '''UPDATE types SET percentage = ? WHERE username = ? AND type = ?''', (percentage, UserPreferences.username, type.name.lower())) db.commit() except Exception: continue # resetta UserPreferences UserPreferences.undoPreference() else: g.user = get_db().execute('''SELECT * FROM user WHERE username = ?''', (username, )).fetchone() # carica i dati in UserPreferences con i dati nella table types if not UserPreferences.loaded: UserPreferences.loaded = True UserPreferences.username = g.user['username'] types = array(get_db().execute( "SELECT type, percentage FROM types WHERE username = ?", (username, )).fetchall()) for type in types: index = Types[type[0].upper()].value UserPreferences.preference[index]['percentage'] = float( type[1]) UserPreferences.preference[index]['count'] = int( round(float(type[1]), 0)) UserPreferences.tot += UserPreferences.preference[index][ 'count']
def logout(): # cancella la sessione session.clear() db = get_db() # carica i dati nella table types for type in Types: percentage = UserPreferences.getPercentage(type) try: if percentage == 0: raise Exception("percentage is 0") db.execute( '''INSERT INTO types (username,type,percentage) VALUES (?,?,?)''', (UserPreferences.username, type.name.lower(), percentage)) db.commit() except sqlite3.IntegrityError: db.execute( '''UPDATE types SET percentage = ? WHERE username = ? AND type = ?''', (percentage, UserPreferences.username, type.name.lower())) db.commit() except Exception: continue # resetta UserPreferences UserPreferences.undoPreference() return redirect(url_for('Home.home'))
def moreUserInfo(username): if request.method == 'POST': address = request.form['country'] + ", " + request.form['city'] + ", " + request.form['province'] + ", " + \ request.form['address'] if address.replace(", ", ""): localization = localizzazione() # address) else: localization = localizzazione() address = None db = get_db() # Aggiunge le informazzioni supplementali all'utente nel database db.execute( '''UPDATE user SET address = ?, localization = ? WHERE username = ?''', ( address, localization, username, )) db.commit() return redirect(url_for('Auth.login')) return render_template('auth/moreUserInfo.html')
def search(): if request.method == 'POST': return redirect( url_for('Home.search', searchQuery=request.form['query'])) type = request.args.get('type') # tipi di posti da ricercare searchQuery = request.args.get( 'searchQuery') # query del posto da ricercare try: location = get_db().execute( "SELECT localization FROM user WHERE username = ?", (session['username'], )).fetchone()[0] if not location: raise Exception() except: location = localizzazione() # cerca i posti e li ordina per la valutazione places = GooglePlaces.textSearch( searchQuery, type=type, location=location, radius=3000) if type else GooglePlaces.textSearch( searchQuery, location=location, radius=3000) places.sort(reverse=True, key=lambda x: x['rating']) photo = photoKeyErrorControl(places) return render_template('home/search.html', ratings=[1, 2, 3, 4, 5], places=places, photo=photo)
def login(): if request.method == 'POST': loginCredentials = request.form[ 'loginCredentials'] # può essere l'email oppure username password = request.form['password'] db = get_db() error = None user = db.execute( '''SELECT * FROM user WHERE email = ? or username = ?''', (loginCredentials, loginCredentials)).fetchone() if user is None: error = 'Incorrect email or username.' elif not check_password_hash(user['password'], password): error = 'Incorrect password.' if error is None: # immagazzina l'identificativo dell'utente nella nuova sessione session.clear() session['username'] = user['username'] UserPreferences.loaded = True UserPreferences.username = user['username'] types = array(get_db().execute( "SELECT type, percentage FROM types WHERE username = ?", (user['username'], )).fetchall()) for type in types: index = Types[type[0].upper()].value UserPreferences.preference[index]['percentage'] = float( type[1]) UserPreferences.preference[index]['count'] = int( round(float(type[1]), 0)) UserPreferences.tot += UserPreferences.preference[index][ 'count'] return redirect(url_for('Home.home')) flash(error) return render_template('auth/login.html')
def update(): user = get_user(request.args.get('username')) db = get_db() if request.method == 'POST': name = request.form['name'] surname = request.form['surname'] email = request.form['email'] password = request.form['password'] address = request.form['country'] + ", " + request.form['city'] + ", " + request.form['province'] + ", " + \ request.form['address'] error = None #controlla che tutti i dati essenziali siano stati inseriti if not name: error = 'Name is required.' elif not surname: error = 'Surname is required.' elif not email: error = 'Email is required.' elif not password: error = 'Password is required.' elif db.execute( '''SELECT email FROM user WHERE email = ? AND username != ?''', ( email, user['username'], )).fetchone() is not None: error = 'User {0} is already registered.'.format(email) # se è stato inserito un indirizzo otteniamo la sua posizione tramite l'indirizzo altrimenti tramite l'ip if address.replace(", ", ""): localization = localizzazione(address) else: localization = localizzazione() address = None if error is not None: flash(error) else: # aggiorna i dati nel database db.execute( '''UPDATE user SET name = ?, surname = ?, email = ?, password = ?, address = ?, localization = ? WHERE username = ?''', (name, surname, email, generate_password_hash(password), address, localization, user['username'])) db.commit() return redirect(url_for('User.info', username=user['username'])) return render_template('user/update.html', user=user)
def register(): if request.method == 'POST': name = request.form['name'] surname = request.form['surname'] username = request.form['username'] email = request.form['email'] password = request.form['password'] db = get_db() error = None """ Controlla se sono stati immessi i seguenti dati: name, surname, username, email e password. Se non sono stati immessi genera un errore. Se l'username o l'email immessa sono gia state utilizzate genera un errore. """ if not name: error = 'Name is required.' elif not surname: error = 'Surname is required.' elif not username: error = 'Username is required.' elif db.execute('''SELECT username FROM user WHERE username = ?''', (username, )).fetchone() is not None: error = 'Username {0} is already taken.'.format(username) elif not email: error = 'Email is required.' elif db.execute('''SELECT username FROM user WHERE email = ?''', (email, )).fetchone() is not None: error = 'User {0} is already registered.'.format(email) elif not password: error = 'Password is required.' if error is None: # Salva il nuovo utente nel database db.execute( '''INSERT INTO user (name, surname, username, email, password) VALUES (?, ?, ?, ?, ?)''', (name, surname, username, email, generate_password_hash(password))) db.commit() return redirect(url_for('Auth.moreUserInfo', username=username)) flash(error) return render_template('auth/register.html')
def home(): if request.method == 'POST': return redirect( url_for('Home.search', searchQuery=request.form['query'])) recommendPhoto = {} recommend = [] try: loc = get_db().execute( "SELECT localization FROM user WHERE username = ?", (session['username'], )).fetchone()[0] if not loc: raise Exception() except: loc = localizzazione() results = GooglePlaces.nearbySearch(loc, 10000) if g.user is not None: recommend = [ place for place in results if UserPreferences.checkPreference(place.get('types')) ] # posti suggeriti recommendPhoto = photoKeyErrorControl(recommend) # foto nearby = results # posti vicini nearbyPhoto = photoKeyErrorControl(nearby) # foto mostPopular = [place for place in results if place['rating'] > 4.5] # posti con maggior votazione mostPopularPhoto = photoKeyErrorControl(mostPopular) # foto for result in results: print(result) return render_template('home/index.html', ratings=[1, 2, 3, 4, 5], recommend=recommend, recommendPhoto=recommendPhoto, nearby=nearby, nearbyPhoto=nearbyPhoto, mostPopular=mostPopular, mostPopularPhoto=mostPopularPhoto)