Python flask.session 模块,clear() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用flask.session.clear()

项目:chat_api    作者:hriks    | 项目源码 | 文件源码
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.
项目:eq-survey-runner    作者:ONSdigital    | 项目源码 | 文件源码
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)
项目:wwalexa    作者:nealrs    | 项目源码 | 文件源码
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
项目:wwalexa    作者:nealrs    | 项目源码 | 文件源码
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!!!)
项目:inshack-2017    作者:HugoDelval    | 项目源码 | 文件源码
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
项目:inshack-2017    作者:HugoDelval    | 项目源码 | 文件源码
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
项目:pillar    作者:armadillica    | 项目源码 | 文件源码
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
项目:Ostrich    作者:anantzoid    | 项目源码 | 文件源码
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
项目:picoCTF    作者:picoCTF    | 项目源码 | 文件源码
def logout():
    """
    Clears the session
    """

    session.clear()
项目:picoCTF    作者:royragsdale    | 项目源码 | 文件源码
def logout():
    """
    Clears the session
    """

    session.clear()
项目:sysu-ctf    作者:ssst0n3    | 项目源码 | 文件源码
def logout():
    if authed():
        session.clear()
    return redirect('/')
项目:xgovctf    作者:alphagov    | 项目源码 | 文件源码
def logout():
    session.clear()
    return redirect("/")
项目:xgovctf    作者:alphagov    | 项目源码 | 文件源码
def logout():
    """
    Clears the session
    """

    session.clear()
项目:pyuniprot    作者:cebel    | 项目源码 | 文件源码
def logout():
    session.clear()
    flash('Logged out!', 'success')
    return redirect(url_for('login'))
项目:python-ares    作者:pynog    | 项目源码 | 文件源码
def aresLogout():
  """ """
  session.clear()
  logout_user()
  return redirect(url_for('ares.aresLogin'))
项目:diyca    作者:texadactyl    | 项目源码 | 文件源码
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
项目:gru    作者:similarweb    | 项目源码 | 文件源码
def logout(self):
        session.clear()
项目:crontab.py    作者:dengmin    | 项目源码 | 文件源码
def logout_user(self):
        session.clear()
        g.user = None
        flash('You are now logged out', 'success')
项目:bawk    作者:jttwnsnd    | 项目源码 | 文件源码
def logout():
    session.clear()
    return redirect('/?message=logged_out')
项目:bawk    作者:jttwnsnd    | 项目源码 | 文件源码
def logout():
    session.clear()
    return redirect('/?message=logged_out')
项目:MIGPU    作者:scuAILab    | 项目源码 | 文件源码
def index():
    session.clear()
    return render_template('index.html')


# 1. dataMangement
项目:duckpond    作者:alexmilowski    | 项目源码 | 文件源码
def logout():
    # remove the username from the session if it's there
    session.clear()
    return redirect(url_for('index'))
项目:graph-data-experiment    作者:occrp-attic    | 项目源码 | 文件源码
def logout():
    session.clear()
    return redirect('/')
项目:shiptoasting    作者:ccpgames    | 项目源码 | 文件源码
def logout():
    session.clear()
    return redirect("/")
项目:eq-survey-runner    作者:ONSdigital    | 项目源码 | 文件源码
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')
项目:actual_12_homework    作者:51reboot    | 项目源码 | 文件源码
def logout():
    session.clear()
    return redirect('/')
项目:sms2fa-flask    作者:TwilioDevEd    | 项目源码 | 文件源码
def logout():
    logout_user()
    session.clear()
    return redirect(url_for('root'))
项目:NZ-ORCID-Hub    作者:Royal-Society-of-New-Zealand    | 项目源码 | 文件源码
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
项目:NZ-ORCID-Hub    作者:Royal-Society-of-New-Zealand    | 项目源码 | 文件源码
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))
项目:secret-garden    作者:elc1798    | 项目源码 | 文件源码
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
项目:secret-garden    作者:elc1798    | 项目源码 | 文件源码
def logout():
    session.clear()
    current_session = None
    return redirect(url_for("login"))
项目:zeus    作者:getsentry    | 项目源码 | 文件源码
def logout():
    session.clear()
    g.current_user = None
    g.current_tenant = None
项目:zeus    作者:getsentry    | 项目源码 | 文件源码
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
项目:Fork-Spoon    作者:vivianhoang    | 项目源码 | 文件源码
def logout():
    """Logs user out"""

    session.clear()

    flash("You have successfully logged out.")
    return redirect("/")
项目:FXTest    作者:liwanlei    | 项目源码 | 文件源码
def get(self):
        session.clear()
        logout_user()
        return redirect(url_for('home.login'))
项目:crysadm    作者:HuiMi24    | 项目源码 | 文件源码
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'))
项目:happyfridays    作者:jessicaraepetersen    | 项目源码 | 文件源码
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('/')
项目:birth-control-bot    作者:smsukardi    | 项目源码 | 文件源码
def reset_counter():
  session.clear()
  message = "Your session has been reset."
  resp = twilio.twiml.Response()
  resp.sms(message)
  return str(resp)
项目:birth-control-bot    作者:smsukardi    | 项目源码 | 文件源码
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)
项目:wwalexa    作者:nealrs    | 项目源码 | 文件源码
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
项目:deb-python-hplefthandclient    作者:openstack    | 项目源码 | 文件源码
def logout_credentials(session_key):
    debugRequest(request)
    session.clear()
    return 'DELETE credentials called'

# CLUSTER INFO #
项目:compatify    作者:hatooku    | 项目源码 | 文件源码
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
项目:crysadm    作者:seatom    | 项目源码 | 文件源码
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'))
项目:playlist_project    作者:catliaw    | 项目源码 | 文件源码
def logout_process():
    """Processes logging out and clears session."""

    session.clear()
    print "\nSession was cleared!\n"

    flash("You have logged out!")

    return redirect('/')
项目:Cloud-Native-Python    作者:PacktPublishing    | 项目源码 | 文件源码
def clearsession():
    # Clear the session
    session.clear()
    # Redirect the user to the main page
    return redirect(url_for('main'))
项目:Cloud-Native-Python    作者:PacktPublishing    | 项目源码 | 文件源码
def clearsession():
    # Clear the session
    session.clear()
    # Redirect the user to the main page
    return redirect(url_for('main'))
项目:ActivityManager    作者:yichengchen    | 项目源码 | 文件源码
def logout_admin():
    session.clear()
    return redirect((url_for('index')))
项目:pillar    作者:armadillica    | 项目源码 | 文件源码
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()
项目:pwnedhub    作者:lanmaster53    | 项目源码 | 文件源码
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})
项目:pwnedhub    作者:lanmaster53    | 项目源码 | 文件源码
def logout():
    session.pop('user_id', None)
    session.clear()
    return redirect(url_for('ph_bp.index'))

# password recovery flow views