Skip to content

Commit a537219

Browse files
authored
Adjust cache TTL for old posts (#545)
1 parent ef2df18 commit a537219

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

blog/tests.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
NoteFactory,
88
)
99
from blog.models import Tag, PreviousTagName
10+
from django.utils import timezone
11+
import datetime
1012
import json
1113

1214

@@ -73,6 +75,19 @@ def test_note(self):
7375
self.assertTemplateUsed(response, "note.html")
7476
self.assertEqual(response.context["note"].pk, note.pk)
7577

78+
def test_cache_header_for_old_content(self):
79+
old_date = timezone.now() - datetime.timedelta(days=181)
80+
entry = EntryFactory(created=old_date)
81+
response = self.client.get(entry.get_absolute_url())
82+
assert response.headers["cache-control"] == "s-maxage=%d" % (
83+
24 * 60 * 60
84+
)
85+
86+
def test_no_cache_header_for_recent_content(self):
87+
recent_entry = EntryFactory(created=timezone.now())
88+
response = self.client.get(recent_entry.get_absolute_url())
89+
assert "cache-control" not in response.headers
90+
7691
def test_archive_year(self):
7792
quotation = QuotationFactory()
7893
response = self.client.get("/{}/".format(quotation.created.year))

blog/views.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
)
1515
from django.http import Http404, HttpResponsePermanentRedirect as Redirect, HttpResponse
1616
from django.test import Client
17+
from django.utils import timezone
1718
from .models import (
1819
Blogmark,
1920
Entry,
@@ -133,6 +134,10 @@ def archive_item(request, year, month, day, slug):
133134
)
134135
if obj.is_draft:
135136
set_no_cache(response)
137+
else:
138+
six_months = datetime.timedelta(days=180)
139+
if obj.created < timezone.now() - six_months:
140+
response["Cache-Control"] = "s-maxage={}".format(24 * 60 * 60)
136141
response["x-enable-card"] = "1"
137142
return response
138143

0 commit comments

Comments
 (0)