Flask application settings

Introduction

This section describes Flask's application-related settings.

View function

Here, as an example, the user authentication function is described as an example.

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'] = 'Please enter your user name.'

        if not password:
            error['password'] = 'Please enter your password.'

        if not password_re:
            error['password_re'] = 'Please enter the password (for 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'] = 'The user name is already registered.'
            else:
                error['password_re'] = 'The passwords do not match.'

        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 = 'The user name or password is incorrect.'

        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

Summary

This section describes the basics of setting up Flask applications. Next time, I'll cover HTML templates.

Recommended Posts

Flask application settings
Flask initial settings
Flask database settings
Flask HTML template settings
Flask introduction-Blueprint application memo
Web application development with Flask
flask
flask
Web application with Python + Flask ② ③
Web application with Python + Flask ④
Creating a web application using Flask ①
Make Flask a Cloud Native application
Creating a web application using Flask ③
Creating a web application using Flask ④
Application development with Docker + Python + Flask
WEB application development using Django [Initial settings]
First Flask
Try using the web application framework Flask
samba settings
VIM settings
Launch Flask application with Docker on Heroku