@@ -32,8 +32,11 @@ Consider a view for showing a user's tweets:
3232 from myproject.twitter import fetch_tweets
3333
3434 def show_tweets(request, username):
35- return render(request, 'tweets.html',
36- {'tweets': fetch_tweets(username)})
35+ return render(
36+ request,
37+ 'tweets.html',
38+ {'tweets': fetch_tweets(username)}
39+ )
3740
3841This works fine but the ``fetch_tweets `` function involves a HTTP round-trip and
3942is slow.
@@ -49,8 +52,11 @@ Performance can be improved by using Django's `low-level cache API`_:
4952 from myproject.twitter import fetch_tweets
5053
5154 def show_tweets(request, username):
52- return render(request, 'tweets.html',
53- {'tweets': fetch_cached_tweets(username)})
55+ return render(
56+ request,
57+ 'tweets.html',
58+ {'tweets': fetch_cached_tweets(username)}
59+ )
5460
5561 def fetch_cached_tweets(username):
5662 tweets = cache.get(username)
@@ -83,8 +89,11 @@ cache asynchronously instead of during the request/response cycle:
8389 from myproject.tasks import update_tweets
8490
8591 def show_tweets(request, username):
86- return render(request, 'tweets.html',
87- {'tweets': fetch_cached_tweets(username)})
92+ return render(
93+ request,
94+ 'tweets.html',
95+ {'tweets': fetch_cached_tweets(username)}
96+ )
8897
8998 def fetch_cached_tweets(username):
9099 item = cache.get(username)
@@ -142,8 +151,11 @@ Here's the same functionality implemented using a django-cacheback decorator:
142151 from cacheback.decorators import cacheback
143152
144153 def show_tweets(request, username):
145- return render(request, 'tweets.html',
146- {'tweets': cacheback(60*15, fetch_on_miss=False)(fetch_tweets)(username)})
154+ return render(
155+ request,
156+ 'tweets.html',
157+ {'tweets': cacheback(60*15, fetch_on_miss=False)(fetch_tweets)(username)}
158+ )
147159
148160Here the decorator simply wraps the ``fetch_tweets `` function - nothing else is
149161needed. Cacheback ships with a flexible Celery task that can run any function
@@ -185,6 +197,7 @@ Contents
185197
186198.. toctree ::
187199 :maxdepth: 2
200+ :glob:
188201
189202 installation
190203 usage
0 commit comments