Skip to content

Instantly share code, notes, and snippets.

@mercul3s
Created March 28, 2014 20:31
Show Gist options
  • Save mercul3s/9842339 to your computer and use it in GitHub Desktop.
Save mercul3s/9842339 to your computer and use it in GitHub Desktop.
A code snippet describing how to use Flask's Session object for user information.
<!DOCTYPE html>
<!-- layout.html -->
<html>
<head>
</head>
<body>
<div class="container">
<div id='nav'>
<a href='{{ url_for('index') }}'><img src="/static/images/monitor-head.png" width='60px' height='31px' alt='monitor-head' id='head-logo' /></a>
<ul id='nav-bar'>
<!-- This is where we check for an id in the session, which would mean that a user is logged in, and we
only display one of either login or logout depending on the state of the session. This is a very
simplified way of checking user login, but works for our purposes. -->
{% if 'id' in session %}
<li><a href="{{ url_for('logout') }}">Logout</a></li>
{% else %}
<li><a href="{{ url_for('login_page') }}">Login</a></li>
{% endif %}
<li><a href="{{ url_for('docs') }}">Docs</a></li>
<li><a href="{{ url_for('dashboard') }}">Dashboard</a></li>
</ul>
</div>
{% block body %}{% endblock %}
</div>
</body>
</html>
from flask import session
@app.route('/login', methods=['GET', 'POST'])
def login():
# this is where your user authentication code would go
# ie get username, pass, and check them in the database.
# Sessions are essentially a dictionary, and we can put anything
# we need in there
if authenticated == True:
session['username'] = username
session['id'] = user_id
return redirect('some other page')
else:
flash(error)
return redirect('/login')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment