From 1624c4c90c21cf2bc3f2147cef226ad8721a7f0e Mon Sep 17 00:00:00 2001 From: lza_menace Date: Fri, 16 Apr 2021 15:07:49 -0700 Subject: [PATCH] add super hacky "cache" for top posts --- suchwow/routes/post.py | 33 ++++++++++++++++++++++++++++++--- suchwow/templates/post/top.html | 2 +- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/suchwow/routes/post.py b/suchwow/routes/post.py index 3a2de0b..a35aabb 100644 --- a/suchwow/routes/post.py +++ b/suchwow/routes/post.py @@ -1,3 +1,5 @@ +import pickle +from datetime import datetime from os import path, remove from io import BytesIO from base64 import b64encode @@ -20,17 +22,42 @@ bp = Blueprint("post", "post") @bp.route("/posts/top") def top(): top_posts = {} + pickle_file = path.join(config.DATA_FOLDER, 'top_posts.pkl') + + try: + mtime_ts = path.getmtime(pickle_file) + mtime = datetime.fromtimestamp(mtime_ts) + now = datetime.now() + diff = now - mtime + + # If pickled data file is less than an hour old, load it and render page + # Otherwise, determine balances, build json, store pickled data, and render page + if diff.seconds < 3600: + with open(pickle_file, 'rb') as f: + print('Loading pickled data for /posts/top') + pickled_data = pickle.load(f) + return render_template("post/top.html", posts=pickled_data) + except: + pass + + print('Generating and pickling new data for /posts/top') posts = Post.select().where(Post.approved==True) for post in posts: transfers = [] incoming = wownero.Wallet().incoming_transfers(post.account_index) if "transfers" in incoming: for xfer in incoming["transfers"]: - transfers.append(wownero.from_atomic(xfer["amount"])) - total = sum(transfers) + transfers.append(xfer["amount"]) + total = wownero.from_atomic(sum(transfers)) if total > 0: top_posts[float(total)] = post - return render_template("post/top.html", posts=sorted(top_posts.items(), reverse=True)) + + _t = sorted(top_posts.items(), reverse=True)[0:10] + + with open(pickle_file, 'wb') as f: + f.write(pickle.dumps(_t)) + + return render_template("post/top.html", posts=_t) @bp.route("/post/") def read(id): diff --git a/suchwow/templates/post/top.html b/suchwow/templates/post/top.html index b2221ac..0f96da2 100644 --- a/suchwow/templates/post/top.html +++ b/suchwow/templates/post/top.html @@ -5,7 +5,7 @@
-

{% block title %}Top Posts{% endblock %}

+

{% block title %}Top 10 Posts{% endblock %}

{% if posts %}