Flask login



examples/flask/17/app.py
from flask import Flask, render_template, url_for, redirect, request, session
app = Flask(__name__)
app.secret_key = 'loginner'

users = {
    'admin' : 'secret',
    'foo'   : 'myfoo',
}

@app.route("/")
def main():
    return render_template('main.html')

@app.route('/login')
def login_form():
    return render_template('login.html')

@app.route('/login', methods=['POST'])
def login():
    username = request.form.get('username')
    password = request.form.get('password')
    if username and password and username in users and users[username] == password:
        session['logged_in'] = True
        return redirect(url_for('account'))

    return render_template('login.html')

@app.route("/account")
def account():
    if not session.get('logged_in'):
        return redirect(url_for('login'))

    return render_template('account.html')

@app.route('/logout')
def logout():
    if not session.get('logged_in'):
        return "Not logged in"
    else:
        session['logged_in'] = False
    return render_template('logout.html')

examples/flask/17/templates/account.html
{% include 'header.html' %}
Account information.

examples/flask/17/templates/header.html
<div>
<a href="/">home</a> | <a href="/login">login</a> | <a href="/logout">logout</a> | <a href="/account">account</a>
</div>

examples/flask/17/templates/home.html
{% include 'header.html' %}
Home page

examples/flask/17/templates/login.html
{% include 'header.html' %}
<form method="POST">
<input name="username" placeholder="username">
<input name="password" placeholder="password" type="password">
<input type="submit" value="Login">
</form>

examples/flask/17/templates/logout.html
{% include 'header.html' %}
Bye bye

examples/flask/17/templates/main.html
{% include 'header.html' %}
Home