Created
April 20, 2012 08:50
-
-
Save daGrevis/2427189 to your computer and use it in GitHub Desktop.
Simple sign in and sign out in Python's Flask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Thnk you
Thanks a lot!!!
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
Used it. thanks.