我正在嘗試通過 PRAW(https://praw.readthedocs.io/en/stable/)與 Django一起使用 Reddit API ,并且正在考慮嘗試使用 functoolslru_cache裝飾器來實作某種快取,以便我可以快取類似 API 呼叫的結果,以減少進行的總體呼叫。我從來沒有做過這樣的事情,所以我一直主要關注實作@lru_cache裝飾器的例子。
我有 3 個檔案,主要與 API 呼叫/在此處顯示有關。我有:
帳號.html
{% extends 'myapp/base.html' %}
<h1> {{ name }} </h1>
<h3> {{ comment_karma }} </h3>
<h5> Top Posts </h5>
<table>
<tr>
<th> Post </th>
<th> Subreddit </th>
</tr>
{% for s in top_submissions %}
<tr>
<td> {{ s.title }} </td>
<td> {{ s.subreddit }} </td>
</tr>
{% endfor %}
</table>
視圖.py
from . import reddit
reddit = reddit.Reddit()
def account_page():
context = reddit.details(request.user.reddit_username)
return render(request, 'stats/dashboard.html', context)
reddit.py
from functools import lru_cache
class Reddit:
def __init__(self):
self.praw = praw.Reddit(
client_id = CLIENT_ID,
client_secret = CLIENT_SECRET,
user_agent = USER_AGENT
)
@lru_cache(maxsize = 256)
def details(self, redditor):
redditor = self.praw.redditor(redditor)
overview = {
'name': redditor.name,
'comment_karma': redditor.comment_karma,
'top_submissions': redditor.submissions.top(limit=10),
}
return overview
Here's the problem: when I don't have the lru_cache, then everything works fine and all the data comes in as always. However, when I do put the lru_cache option, then only the name and comment_karma come, while the submissions (an iterable list) just does not display on my page (so I assume it doesn't end up having any values).
Am I using lru_cache wrong? Essentially, my goal is if a redditor is passed into the function overview, I don't want to keep making the same API calls over and over, but instead want to put it into the cache and pull that same data if it's in the cache.
uj5u.com熱心網友回復:
PRAW 回傳惰性求值的生成器物件。您想在快取函式中評估它們。否則,生成器耗盡后,您將無法再次獲得結果。
所以作業版本應該是這樣的:
@lru_cache(maxsize = 256)
def details(self, redditor):
redditor = self.praw.redditor(redditor)
overview = {
'name': redditor.name,
'comment_karma': redditor.comment_karma,
'top_submissions': list(redditor.submissions.top(limit=10)),
}
return overview
list(redditor.submissions.top(limit=10)) 將使用生成器并且快取的結果將包含串列,而不是只能使用一次的生成器物件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/337553.html
