Cette section décrit les paramètres liés à l'application de Flask.
Ici, à titre d'exemple, la fonction d'authentification de l'utilisateur sera décrite à titre d'exemple.
auth.py
import functools
from flask import (
Blueprint, flash, g, redirect, render_template, request, session, url_for
)
from werkzeug.security import check_password_hash, generate_password_hash
from todo.db import get_db
bp = Blueprint('auth', __name__, url_prefix='/auth')
@bp.route('/signup', methods=('GET', 'POST'))
def signup():
error = {}
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
password_re = request.form['password-re']
db = get_db()
if not username:
error['username'] = 'S'il vous plaît entrez votre nom d'utilisateur.'
if not password:
error['password'] = 'S'il vous plait entrez votre mot de passe.'
if not password_re:
error['password_re'] = 'Veuillez saisir le mot de passe (pour confirmation).'
if username and password and password_re:
if password == password_re:
registered_user = db.execute(
'SELECT id FROM user WHERE username=?', (username,)
).fetchone()
if registered_user is not None:
error['username'] = 'Le nom d'utilisateur est déjà enregistré.'
else:
error['password_re'] = 'Le mot de passe ne correspond pas.'
if error == {}:
db.execute(
'INSERT INTO user (username, password) VALUES (?, ?)',
(username, generate_password_hash(password))
)
db.commit()
return redirect(url_for('auth.login'))
return render_template(
'auth/form.html',
type='signup',
error=error
)
@bp.route('/login', methods=('GET', 'POST'))
def login():
error = None
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
db = get_db()
user = db.execute(
'SELECT * FROM user WHERE username = ?', (username,)
).fetchone()
if user is None or not check_password_hash(user['password'], password):
error = 'Le pseudo ou mot de passe est incorect.'
if error is None:
session.clear()
session['user_id'] = user['id']
return redirect(url_for('index'))
return render_template(
'auth/form.html',
type='login',
error=error
)
@bp.before_app_request
def load_logged_in_user():
user_id = session.get('user_id')
if user_id is None:
g.user = None
else:
g.user = get_db().execute(
'SELECT * FROM user WHERE id = ?', (user_id,)
).fetchone()
@bp.route('/logout')
def logout():
session.clear()
return redirect(url_for('auth.login'))
def login_required(view):
@functools.wraps(view)
def wrapped_view(**kwargs):
if g.user is None:
return redirect(url_for('auth.login'))
return view(**kwargs)
return wrapped_view
Ici, nous avons expliqué les bases de la configuration des applications Flask. La prochaine fois, je couvrirai les modèles HTML.
Recommended Posts