Created
March 28, 2014 20:31
-
-
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.
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
<!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> |
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 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