2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Flaskのアプリケーションの設定

Posted at

はじめに

ここでは、Flaskのアプリケーション関連設定について解説します。

ビュー関数

ここでは例として、ユーザー認証の機能を例に書きます。

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'] = 'ユーザー名を入力してください。'

        if not password:
            error['password'] = 'パスワードを入力してください。'

        if not password_re:
            error['password_re'] = 'パスワード(確認用)を入力してください。'
        
        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'] = 'そのユーザー名は既に登録されています。'
            else:
                error['password_re'] = 'パスワードが一致していません。'

        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 = 'ユーザー名かパスワードが間違っています。'

        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

まとめ

ここでは、Flaskのアプリケーションの設定の基本について解説しました。
次回はHTMLテンプレートについて取り上げる予定です。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?