Skip to content

Instantly share code, notes, and snippets.

@Yunaka12
Last active July 29, 2018 12:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yunaka12/ebe0ddcd2d1d439e683764f89590f1a5 to your computer and use it in GitHub Desktop.
Save Yunaka12/ebe0ddcd2d1d439e683764f89590f1a5 to your computer and use it in GitHub Desktop.
jsonを利用した簡易的なキャッシュ。
from tinydb import TinyDB, Query
import datetime
#重い処理の例
def omoi(i):
#データベースから読み込まれていない場合
if i == 0:
for i in range(100000000):
i = i + 1
if DB_length == 0:
#初回時データベースに挿入
DB.insert({'calc':i,'type':"calc"})
else:
#初回時以外はデータベースを更新
DB.update({'calc':i}, query.type == "calc")
#計算結果表示
print(i)
#データベースから読み込まれた場合
else:
#データベースの値を利用して表示
print(i)
#データベース作成
DB = TinyDB('cache.json')
#データベースの大きさ確認
DB_length = len(DB)
#初回起動時
if DB_length == 0:
#アクセス時間を取得 YYYY-MM-DD
access = datetime.datetime.now()
#計算を分かりやすくするためUNIX時間に変更
access_unix = access.timestamp()
#データベースに挿入
DB.insert({'time':access_unix,"type":"time"})
#重い処理とかAPIを利用した処理
omoi(0)
#初回時以外
else:
#データベースから前回アクセス時間読み込み
query = Query()
#リストで返ってくる
db_time_list = DB.search(query.type == "time")
#timeの値はリストのdb[0]['time']にある
db_time = db_time_list[0]['time']
#現在のアクセス時間を取得
access_now = datetime.datetime.now()
access_now_unix = access_now.timestamp()
#30秒以上なら処理
if access_now_unix - db_time > 30:
#重い処理とかAPIを利用した処理
omoi(0)
#データベースの時間を更新
DB.update({'time':access_now_unix}, query.type == "time")
#30秒未満ならデータベース読み込み
else:
#リストで返ってくる
db_calc_list = DB.search(query.type == "calc")
db_calc = db_calc_list[0]['calc']
#データベースから読み込んだ値を渡す
omoi(db_calc)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment