LoginSignup
5
0

More than 1 year has passed since last update.

はじめに

先日、株式会社オフグリッドに入社しました。

社内でQitaを投稿している方がいたので、
自分もアウトプットの習慣をつける為に記事を投稿していこうと思い本記事を執筆することにしました。

間違っていることが多々あると思いますが。。。

flask-loginとは?

Flaskでログイン機能を実装する際には使われることの多いライブラリ。

ここからはFlask-loginの使い方を読み解いていこうと思います。

インストール方法

インストール方法は

pip install flask-login

設定方法

pipのinstallが終わったら、アプリケーションにflask-loginの設定を反映させる

app.py
login_manager = LoginManager()

LoginManagerクラスのインスタンスを生成。
LoginManagerクラスはflask-loginの中核を担うクラス。

公式ドキュメントにてLoginManagerクラスの説明を確認。

Configuring Login
class flask_login.LoginManager(app=None, add_context_processor=True)[source]
This object is used to hold the settings used for logging in. Instances of LoginManager are not bound to specific apps, so you can create one in the main body of your code and then bind it to your app in a factory function.

このクラスはLoginの設定を保持するために必要となるクラス。
特定のアプリにバインドする必要があるので上記のコードが必要になる。

source codeの全容を確認する際はこちらのリンクから確認できる。
source_code

LoginManagerクラスをアプリに設定したら、次のコマンドを実施。

app.py
login_manager.init_app(app)

flask-loginはsession上でログインデータを管理している。
なので、実装をする際にはsecret_keyを設定する必要がある。

models.py
@login_manager.user_loader
def load_user(user_id):
    return User.get(user_id)

次にload_user関数を定義する。
こちらでuser_idを

flask-loginのドキュメント内
 def user_loader(self, callback):
        '''
        This sets the callback for reloading a user from the session. The
        function you set should take a user ID (a ``unicode``) and return a
        user object, or ``None`` if the user does not exist.

        :param callback: The callback for retrieving a user object.
        :type callback: callable
        '''
        self._user_callback = callback
        return callback

このようにuser_loader関数でsessionからuser_idをリロードしている。

また、Userクラスの実装を簡単にするためにUserMixinクラスが用意されている。

継承させたいクラスにUserMixinを継承させて使用すると、簡単にログイン機能が実装できる。

終わりに

尻切れになっている部分も過分にございますが。。。

今後もQitaで記事を投稿していくつもりなのでよろしくお願い致します。

5
0
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
5
0