我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用flask.session.clear()。
def logout(): user = User.query.filter_by(username=str(current_user.username)).first() user.is_active = False db.session.commit() session.clear() # Clear's chatBox session, # this closes the chatBOX hriks( 'Notification: %s Successfully Logged out' % ( current_user.username ) ) logout_user() # logout_user() is called which will # Logout user return redirect(url_for('index')) # When ever this method is chat box will be closed # and token for the group/user chatting will be # dropped.
def flush_data(): if session: session.clear() encrypted_token = request.args.get('token') if not encrypted_token or encrypted_token is None: return Response(status=403) decrypted_token = decrypt(token=encrypted_token, key_store=current_app.eq['key_store'], key_purpose=KEY_PURPOSE_AUTHENTICATION, leeway=current_app.config['EQ_JWT_LEEWAY_IN_SECONDS']) roles = decrypted_token.get('roles') if roles and 'flusher' in roles: user = _get_user(decrypted_token) if _submit_data(user): return Response(status=200) return Response(status=404) return Response(status=403)
def begin_call(): print "start /begin_call" from_number = request.values.get('From', None) if from_number in callers: session['caller'] = callers[from_number] else: session['caller'] = "unknown" resp = VoiceResponse() if session['caller'] != "unknown": resp.say("Hey " + session['caller'] + "!") gather = Gather(input='dtmf speech', timeout=5, num_digits=4, action='/set_date', method='GET') gather.say("Let's record a new "+os.environ['PODCASTNAME']+"!\n First, when will this episode air?\n Say the air date or punch it in using a Month Month Day Day format.\n For example, you could say October 31st or punch in 10 31.") resp.append(gather) resp.say("You didn't give me a date. Bye!") else: resp.say("Hey, this isn't for you. \nBoy Bye!") resp.hangup() session.clear() return str(resp) # validate date & record audio
def save_finish(): print "start /save_finish" resp = VoiceResponse() digits = int(request.values.get('Digits', None)) if digits == 1: resp.say("Alright, give me a hot second...") # save file to s3 with correct date as filename and end call if save_to_s3_url(session['mp3url']+".mp3", session['airdate'].strftime("%Y-%m-%d")+".mp3") is True: resp.say("And boom, you're good to go! See you next time " + session['caller'] +" !") else: resp.say("Yikes "+ session['caller'] + " we ran into an error saving to s3. Can you try calling in again? Sorry!!") else: resp.say("No problem, just hangup and call back again.") resp.hangup() session.clear() return str(resp) # process incoming email via mailgun routes (SUPER HACKY!!!)
def get(): if 'status' in session and session['status'] == 1: return "Your coffee is ready but you don't have milk in it.",406 if 'status' in session and session['status'] == 3: if 'milk' not in session or 'syrup' not in session: return 'Not acceptable',406 if session['milk'] != "Half-and-half": return "Your coffee is ready but you didn't put the right milk-type.",200 if session['syrup'] == '': return "Your coffee is ready but you didn't put syrup in it.",200 if session['syrup'] != 'Raspberry': return "Your coffee is ready but you didn't put the right syrup-type.",200 return 'Here is your coffee: INSA{April_Fool_of_Coffee_Machine}',200 else: session.clear() return 'Not acceptable',406
def when(): #Stop pouring milk if 'status' not in session or session['status'] != 2: session.clear() return 'Not acceptable',406 pouring_duration = (datetime.now() - session['start']).total_seconds() if timePouringMilkMin < pouring_duration < timePouringMilkMax: session['status'] = 3 return 'Milk is served.',200 elif pouring_duration < timePouringMilkMin: session.clear() return "Not enough milk, try again!",200 else: return "Milk overflow, try again!",200
def _load_user(token) -> typing.Union[UserClass, AnonymousUser]: """Loads a user by their token. :returns: returns a UserClass instance if logged in, or an AnonymousUser() if not. """ from ..api.utils import authentication if not token: return AnonymousUser() db_user = authentication.validate_this_token(token) if not db_user: # There is a token, but it's not valid. We should reset the user's session. session.clear() return AnonymousUser() user = UserClass.construct(token, db_user) return user
def user_session(func): @wraps(func) def wrapper(**kwargs): from app.models import Utils if Utils.getParam(request.args, 'session', default=None): user_data = session.get('_user', None) if user_data and user_data['is_admin']: session.clear() user_data = session.get('_user', None) kwargs['props'] = {'user': user_data, 'cdn': webapp.config['S3_HOST']+'website/', 'host': webapp.config['HOST']+'/' } return func(**kwargs) return wrapper
def logout(): """ Clears the session """ session.clear()
def logout(): if authed(): session.clear() return redirect('/')
def logout(): session.clear() return redirect("/")
def logout(): session.clear() flash('Logged out!', 'success') return redirect(url_for('login'))
def aresLogout(): """ """ session.clear() logout_user() return redirect(url_for('ares.aresLogin'))
def build_logout_response(arg_html_text): out_response = make_response(arg_html_text) out_response.set_cookie(SESSION_COOKIE_NAME, "", expires=0) session.clear() return out_response #------------ Web Server Entry Points -------------------------------- # Main entry point (/) # if in session, stay in session --> main_form # Else, present login form
def logout(self): session.clear()
def logout_user(self): session.clear() g.user = None flash('You are now logged out', 'success')
def logout(): session.clear() return redirect('/?message=logged_out')
def index(): session.clear() return render_template('index.html') # 1. dataMangement
def logout(): # remove the username from the session if it's there session.clear() return redirect(url_for('index'))
def logout(): session.clear() return redirect('/')
def store_session(metadata): """ Store new session and metadata :param metadata: metadata parsed from jwt token """ # clear the session entry in the database current_app.eq['session_storage'].delete_session_from_db() # also clear the secure cookie data session.clear() # get the hashed user id for eq id_generator = current_app.eq['id_generator'] user_id = id_generator.generate_id(metadata) user_ik = id_generator.generate_ik(metadata) # store the user id in the session current_app.eq['session_storage'].store_user_id(user_id) # store the user ik in the cookie current_app.eq['session_storage'].store_user_ik(user_ik) questionnaire_store = get_questionnaire_store(user_id, user_ik) questionnaire_store.metadata = metadata questionnaire_store.add_or_update() logger.info('user authenticated')
def logout(): logout_user() session.clear() return redirect(url_for('root'))
def remove_if_invalid(response): """Remove a stale session and session cookie.""" if "__invalidate__" in session: response.delete_cookie(app.session_cookie_name) session.clear() return response
def logout(): """Log out a logged user. Note: if the user has logged in via the University of Auckland SSO, show the message about the log out procedure and the linke to the instruction about SSO at the university. """ org_name = session.get("shib_O") try: logout_user() except Exception as ex: app.logger.exception("Failed to log out.") session.clear() session["__invalidate__"] = True if org_name: if EXTERNAL_SP: sp_url = urlparse(EXTERNAL_SP) sso_url_base = sp_url.scheme + "://" + sp_url.netloc else: sso_url_base = '' return redirect(sso_url_base + "/Shibboleth.sso/Logout?return=" + quote( url_for( "uoa_slo" if org_name and org_name == "University of Auckland" else "login", _external=True))) return redirect(url_for("login", logout=True))
def login_required(f): @wraps(f) def decorated_function(*args, **kwargs): if "logged_in" not in session or not session['logged_in'] \ or "key" not in session or current_session == None \ or not current_session.verify_password(): session.clear() return redirect(url_for("login")) return f(*args, **kwargs) return decorated_function
def logout(): session.clear() current_session = None return redirect(url_for("login"))
def logout(): session.clear() g.current_user = None g.current_tenant = None
def get_redirect_target(clear=True) -> str: if clear: session_target = session.pop('next', None) else: session_target = session.get('next') for target in request.values.get('next'), session_target: if not target: continue if is_safe_url(target): return target
def logout(): """Logs user out""" session.clear() flash("You have successfully logged out.") return redirect("/")
def get(self): session.clear() logout_user() return redirect(url_for('home.login'))
def logout(): if session.get('admin_user_info') is not None: session['user_info'] = session.get('admin_user_info') del session['admin_user_info'] return redirect(url_for('admin_user')) user = session.get('user_info') guest_diary(request, user.get('username')) session.clear() return redirect(url_for('login'))
def clear(): """Clears flask session and SQL tables once user is done .""" session.clear() db.session.query(Track).delete() db.session.query(Playlist).delete() db.session.query(UserAlbum).delete() db.session.query(Album).delete() db.session.query(Artist).delete() db.session.query(User).delete() db.session.commit() print "------User's session & data cleared from DB------" return redirect('/')
def reset_counter(): session.clear() message = "Your session has been reset." resp = twilio.twiml.Response() resp.sms(message) return str(resp)
def give_recommendation_and_address(options_arr): if len(options_arr) == 0: message = "Please consult with your doctors for options." else: message = "Possible forms of birth control are " + ", ".join(options_arr) resp = twilio.twiml.Response() resp.sms(message) session.clear() return str(resp)
def set_date(): print "start /set_date" resp = VoiceResponse() digits = request.values.get('Digits', None) speech = request.values.get('SpeechResult', None) print "dtmf digits: "+ str(digits) #print "speech recognition: " + speech #month=0 #digits=0 year=datetime.now().year if speech: cal = pdt.Calendar() time, status = cal.parse(speech) spoken_date = datetime(*time[:6]) print "spoken date: "+ spoken_date.strftime("%A, %B %-d, %Y") month = spoken_date.month day = spoken_date.day year = spoken_date.year else: month = int(str(digits[:2]).lstrip("0").replace(" 0", " ")) day = int(str(digits[-2:]).lstrip("0").replace(" 0", " ")) if isvaliddate(month, day, year) is True: session['airdate'] = datetime(year,month,day) print session['airdate'].strftime("%A, %B %-d, %Y") resp.say("Ok " + session['caller'] + ", this episode will air "+ session['airdate'].strftime("%A, %B %-d, %Y")) resp.say("Next, record up to 3 minutes of audio following the beep.\n Press any key when you're done.") resp.record(max_length="180", action="/play_schedule", RecordingChannels="dual", recording_channels="dual") # 3 min max else: resp.say("That's not a valid date, hang up and try again.") resp.hangup() session.clear() return str(resp) # replay audio & confirm scheduling
def logout_credentials(session_key): debugRequest(request) session.clear() return 'DELETE credentials called' # CLUSTER INFO #
def success(): token1 = session["TOKEN1"] token2 = session["TOKEN2"] access_token1 = token1["access_token"] access_token2 = token2["access_token"] session.clear() intersection_songs = INTERSECTION_DICT[access_token1 + "_" + access_token2] del INTERSECTION_DICT[access_token1 + "_" + access_token2] sp1 = spotipy.Spotify(auth=access_token1) sp2 = spotipy.Spotify(auth=access_token2) user_id1 = sp1.me()["id"] user_id2 = sp2.me()["id"] playlist_name = 'Compatify-' + user_id1 + '-' + user_id2 new_playlist1 = sp1.user_playlist_create(user_id1, playlist_name, public=False) new_playlist2 = sp2.user_playlist_create(user_id2, playlist_name, public=False) size = len(intersection_songs) index = 0 while True: current_num = size - index if current_num > 100: sp1.user_playlist_add_tracks(user_id1, new_playlist1["id"], intersection_songs[index:index+100], position=None) sp2.user_playlist_add_tracks(user_id2, new_playlist2["id"], intersection_songs[index:index+100], position=None) index += 100 elif current_num > 0: sp1.user_playlist_add_tracks(user_id1, new_playlist1["id"], intersection_songs[index:index+current_num], position=None) sp2.user_playlist_add_tracks(user_id2, new_playlist2["id"], intersection_songs[index:index+current_num], position=None) break else: break return render_template("success.html") # Methods
def logout_process(): """Processes logging out and clears session.""" session.clear() print "\nSession was cleared!\n" flash("You have logged out!") return redirect('/')
def clearsession(): # Clear the session session.clear() # Redirect the user to the main page return redirect(url_for('main'))
def logout_admin(): session.clear() return redirect((url_for('index')))
def logout_user(): """Forces a logout of the current user.""" from ..api.utils import authentication token = get_blender_id_oauth_token() if token: authentication.remove_token(token) session.clear() flask_login.logout_user() g.current_user = AnonymousUser()
def snake_enter_score(): status = 'no response' # make sure scorehash is correct for the given score score = int(request.form['score']) scorehash = int(request.form['scorehash']) if math.sqrt(scorehash - 1337) == score: if request.form['SNAKE_BLOCK'] == '1': # create recording string recTurn = request.form['recTurn'] recFrame = request.form['recFrame'] recFood = request.form['recFood'] recData = urlencode({ 'recTurn':recTurn, 'recFrame':recFrame, 'recFood':recFood }) # add the new score playerName = g.user.username#request.form['playerName']#re.sub('[&=#<>]', '', request.form['playerName']) score = Score(player=playerName, score=score, recording=recData) db.session.add(score) db.session.commit() # reset the high scores. the game requests rec#.txt files 0-9 by # default, so the recid field must be updated for the high scores # clear out current high scores for score in Score.query.all(): score.recid = None db.session.add(score) db.session.commit() # update the recid field to set the new high scores scores = Score.query.order_by(Score.score.desc()).limit(10).all() for i in range(0, len(scores)): scores[i].recid = i db.session.add(scores[i]) db.session.commit() status = 'ok' else: status = 'snake block not present' else: status = 'invalid scorehash' return urlencode({'status':status})
def logout(): session.pop('user_id', None) session.clear() return redirect(url_for('ph_bp.index')) # password recovery flow views