LoginSignup
0
0

[Flask]生成したオブジェクトをリクエストを跨いで使いまわしたい

Last updated at Posted at 2023-08-24

アプリケーションレベルで値を使いまわす為にはアプリケーションのコンテキストを使用する。
Flaskではアプリケーションコンテキストには以下の2つが提供されている。

コンテキスト 生存期間
g リクエスト単位
current_app アプリケーション単位

gだとリクエストを跨いだ使いまわしは出来ないので今回はcurrent_appを使用する

from flask import Flask, current_app

app = Flask(__name__)


class Sample(object):
    def getObj(self):
        with app.app_context():
            if getattr(current_app, 'obj', None) is None: #オブジェクトの存在チェック
                current_app.obj = #使いまわしたいオブジェクトの生成

            return current_app.obj

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