我正试图通过PRAW (https://praw.readthedocs.io/en/stable/)和Django一起使用Reddit API,并且正在考虑使用functools lru_cache装饰器来实现某种类型的缓存,这样我就可以缓存类似API调用的结果,以减少总的调用。我从来没有做过这样的事情,所以我主要关注实现@lru_cache装饰器的例子。
这里有3个主要涉及API调用/显示的文件。我有:
account.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>views.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问题是:当我没有lru_cache时,一切正常,所有的数据都会如常出现。但是,当我放置lru_cache选项时,只有名称和comment_karma出现,而提交(可迭代列表)只是不显示在我的页面上(所以我假设它没有任何值)。
我用错了lru_cache吗?本质上,我的目标是如果一个redditor被传递到函数overview中,我不想一次又一次地进行相同的API调用,而是希望将其放入缓存中,如果缓存中有相同的数据,则提取相同的数据。
发布于 2021-10-26 22:51:47
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 overviewlist(redditor.submissions.top(limit=10))将使用生成器,缓存的结果将包含列表,而不是只能使用一次的生成器对象。
https://stackoverflow.com/questions/69730751
复制相似问题