Skip to content

Instantly share code, notes, and snippets.

@macloo
Created April 9, 2017 14:34
Show Gist options
  • Save macloo/67caf0e0d0718d4723d88786e1db80fb to your computer and use it in GitHub Desktop.
Save macloo/67caf0e0d0718d4723d88786e1db80fb to your computer and use it in GitHub Desktop.
How Flask session variables work
# python 3
# a review of Python’s dictionary format
# create a new dict - named session - with three key:value pairs:
session = { 'logged_in': True, 'user': 'Harry Potter', 'password': 'parseltongue' }
# create a new dict - named session2 - with three key:value pairs
# another way to create a dict)
session2 = {}
session2['logged_in'] = False
session2['user'] = 'Hermione Granger'
session2['password'] = 'muggle-born'
# access a value by dict name and key
print( session['user'] )
print( session2['user'] )
# adapted from Head First Python, 2nd edition, by Paul Barry - chapter 10
# this is how a session variable allows you to pass values between pages
from flask import Flask, session
app = Flask(__name__)
app.secret_key = 'You Will Never Guess'
@app.route('/setuser/<user>')
def setuser(user):
session['user'] = user
return 'User value set to: ' + session['user']
@app.route('/getuser')
def getuser():
return 'User value was previously set to: ' + session['user']
if __name__ == '__main__':
app.run(debug=True)
# compare to quick_session.py - below in this gist - this version does NOT use session
# Therefore, it cannot pass variables to another route
from flask import Flask
app = Flask(__name__)
@app.route('/setuser/<user>')
def setuser(user):
new_user = user
return 'User value set to: ' + new_user
@app.route('/getuser')
def getuser():
return 'User value was previously set to: ' + new_user
if __name__ == '__main__':
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment