Skip to content

Instantly share code, notes, and snippets.

@daGrevis
Created April 20, 2012 08:50
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save daGrevis/2427189 to your computer and use it in GitHub Desktop.
Save daGrevis/2427189 to your computer and use it in GitHub Desktop.
Simple sign in and sign out in Python's Flask
from flask import Flask, session, escape, request, redirect, url_for
from os import urandom
app = Flask(__name__)
app.debug = True
app.secret_key = urandom(24)
@app.route('/')
def index():
if 'username' in session:
return 'Hey, {}!'.format(escape(session['username']))
return 'You are not signed in!'
@app.route('/sign_in', methods=['GET', 'POST'])
def sign_in():
if request.method == 'POST':
session['username'] = request.form['username']
return redirect(url_for('index'))
return '''
<form action="" method="post">
<p>Username <input name="username">
<p><button>Sign in</button></p>
</form>
'''
@app.route('/sign_out')
def sign_out():
session.pop('username')
return redirect(url_for('index'))
if __name__ == "__main__":
app.run()
@jasperwork
Copy link

Used it. thanks.

@scubbae
Copy link

scubbae commented Dec 29, 2020

Thnk you

@NobayeneSehloho
Copy link

Thanks a lot!!!

@Larsene
Copy link

Larsene commented Apr 26, 2021

this is really simple, but be careful ! if you just pop one value from the session list, it won't clear the session. To to that properly, regardless the number of values in session(), you should replace your sign_out() with something like that :

@app.route('/sign_out')
def sign_out():
    session.clear()
    return redirect(url_for('index'))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment