Skip to content

Commit eb63a80

Browse files
committed
缓存功能优化
1 parent 329cbc4 commit eb63a80

File tree

12 files changed

+97
-89
lines changed

12 files changed

+97
-89
lines changed

DjangoBlog/blog_signals.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
from django.db.models.signals import post_save
2323
from django.contrib.auth.signals import user_logged_in, user_logged_out, user_login_failed
2424

25-
from DjangoBlog.utils import cache, send_email, expire_view_cache, get_blog_setting, delete_view_cache
25+
from DjangoBlog.utils import cache, send_email, expire_view_cache, delete_sidebar_cache, delete_view_cache
2626
from DjangoBlog.spider_notify import SpiderNotify
2727
from oauth.models import OAuthUser
2828
from blog.models import Article, Category, Tag, Links, SideBar, BlogSettings
@@ -103,7 +103,8 @@ def model_post_save_callback(sender, instance, created, raw, using, update_field
103103
cache.delete('seo_processor')
104104
comment_cache_key = 'article_comments_{id}'.format(id=instance.article.id)
105105
cache.delete(comment_cache_key)
106-
delete_view_cache(instance.author.username)
106+
delete_sidebar_cache(instance.author.username)
107+
delete_view_cache('article_comments', [str(instance.article.pk)])
107108

108109
_thread.start_new(send_comment_email, (instance,))
109110

@@ -116,5 +117,5 @@ def model_post_save_callback(sender, instance, created, raw, using, update_field
116117
def user_auth_callback(sender, request, user, **kwargs):
117118
if user and user.username:
118119
logger.info(user)
119-
delete_view_cache(user.username)
120+
delete_sidebar_cache(user.username)
120121
cache.clear()

DjangoBlog/utils.py

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,6 @@ def get_md5(str):
4242
def cache_decorator(expiration=3 * 60):
4343
def wrapper(func):
4444
def news(*args, **kwargs):
45-
key = ''
4645
try:
4746
view = args[0]
4847
key = view.get_cache_key()
@@ -57,11 +56,17 @@ def news(*args, **kwargs):
5756
value = cache.get(key)
5857
if value:
5958
# logger.info('cache_decorator get cache:%s key:%s' % (func.__name__, key))
60-
return value
59+
if repr(value) == 'default':
60+
return None
61+
else:
62+
return value
6163
else:
6264
logger.info('cache_decorator set cache:%s key:%s' % (func.__name__, key))
6365
value = func(*args, **kwargs)
64-
cache.set(key, value, expiration)
66+
if not value:
67+
cache.set(key, 'default', expiration)
68+
else:
69+
cache.set(key, value, expiration)
6570
return value
6671

6772
return news
@@ -246,10 +251,16 @@ def save_user_avatar(url):
246251
return url
247252

248253

249-
def delete_view_cache(username):
254+
def delete_sidebar_cache(username):
250255
from django.core.cache.utils import make_template_fragment_key
251256
from blog.models import LINK_SHOW_TYPE
252257
keys = (make_template_fragment_key('sidebar', [username + x[0]]) for x in LINK_SHOW_TYPE)
253258
for k in keys:
254259
logger.info('delete sidebar key:' + k)
255260
cache.delete(k)
261+
262+
263+
def delete_view_cache(prefix, keys):
264+
from django.core.cache.utils import make_template_fragment_key
265+
key = make_template_fragment_key(prefix, keys)
266+
cache.delete(key)

accounts/tests.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from django.test import Client, RequestFactory, TestCase
22
from blog.models import Article, Category, Tag
33
from django.contrib.auth import get_user_model
4-
from DjangoBlog.utils import get_current_site
4+
from DjangoBlog.utils import delete_view_cache, delete_sidebar_cache
55
import datetime
66
from accounts.models import BlogUser
77
from django.urls import reverse
@@ -59,7 +59,7 @@ def test_validate_register(self):
5959
user.is_superuser = True
6060
user.is_staff = True
6161
user.save()
62-
delete_view_cache(user.username)
62+
delete_sidebar_cache(user.username)
6363
category = Category()
6464
category.name = "categoryaaa"
6565
category.created_time = datetime.datetime.now()

blog/models.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -117,20 +117,20 @@ def comment_list(self):
117117
return value
118118
else:
119119
comments = self.comment_set.filter(is_enable=True)
120-
cache.set(cache_key, comments)
120+
cache.set(cache_key, comments, 60 * 100)
121121
logger.info('set article comments:{id}'.format(id=self.id))
122122
return comments
123123

124124
def get_admin_url(self):
125125
info = (self._meta.app_label, self._meta.model_name)
126126
return reverse('admin:%s_%s_change' % info, args=(self.pk,))
127127

128-
@cached_property
128+
@cache_decorator(expiration=60 * 100)
129129
def next_article(self):
130130
# 下一篇
131131
return Article.objects.filter(id__gt=self.id, status='p').order_by('id').first()
132132

133-
@cached_property
133+
@cache_decorator(expiration=60 * 100)
134134
def prev_article(self):
135135
# 前一篇
136136
return Article.objects.filter(id__lt=self.id, status='p').first()

blog/views.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ class IndexView(ArticleListView):
8787
'''
8888
首页
8989
'''
90+
# 友情链接类型
9091
link_type = 'i'
9192

9293
def get_queryset_data(self):

oauth/oauthmanager.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
import json
2121
import logging
2222
import urllib.parse
23-
from DjangoBlog.utils import parse_dict_to_url
23+
from DjangoBlog.utils import parse_dict_to_url, cache_decorator
2424

2525
logger = logging.getLogger(__name__)
2626

@@ -426,6 +426,7 @@ def get_oauth_userinfo(self):
426426
return user
427427

428428

429+
@cache_decorator(expiration=100 * 60)
429430
def get_oauth_apps():
430431
configs = OAuthConfig.objects.filter(is_enable=True).all()
431432
if not configs:
@@ -438,7 +439,8 @@ def get_oauth_apps():
438439

439440
def get_manager_by_type(type):
440441
applications = get_oauth_apps()
441-
finds = list(filter(lambda x: x.ICON_NAME.lower() == type.lower(), applications))
442-
if finds:
443-
return finds[0]
442+
if applications:
443+
finds = list(filter(lambda x: x.ICON_NAME.lower() == type.lower(), applications))
444+
if finds:
445+
return finds[0]
444446
return None

oauth/templatetags/oauth_tags.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,15 @@
2323
@register.inclusion_tag('oauth/oauth_applications.html')
2424
def load_oauth_applications(request):
2525
applications = get_oauth_apps()
26-
baseurl = reverse('oauth:oauthlogin')
27-
path = request.get_full_path()
26+
if applications:
27+
baseurl = reverse('oauth:oauthlogin')
28+
path = request.get_full_path()
2829

29-
apps = list(map(lambda x: (x.ICON_NAME,
30-
'{baseurl}?type={type}&next_url={next}'
31-
.format(baseurl=baseurl, type=x.ICON_NAME, next=path)), applications))
30+
apps = list(map(lambda x: (x.ICON_NAME,
31+
'{baseurl}?type={type}&next_url={next}'
32+
.format(baseurl=baseurl, type=x.ICON_NAME, next=path)), applications))
33+
else:
34+
apps = []
3235
return {
3336
'apps': apps
3437
}

templates/blog/article_detail.html

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,7 @@ <h3 class="assistive-text">文章导航</h3>
5151
</div><!-- #content -->
5252
{% if article.comment_status == "o" and OPEN_SITE_COMMENT %}
5353

54-
{% comment %}{% load comments_tags %}
55-
{% load_post_comment article from %}{% endcomment %}
54+
5655
{% include 'comments/tags/comment_list.html' %}
5756
{% if user.is_authenticated %}
5857
{% include 'comments/tags/post_comment.html' %}

templates/blog/tags/article_info.html

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
{% load blog_tags %}
2+
{% load cache %}
23
<article id="post-{{ article.pk }} "
34
class="post-{{ article.pk }} post type-post status-publish format-standard hentry">
45
<header class="entry-header">
@@ -31,7 +32,9 @@ <h1 class="entry-title">
3132
<br/>
3233
{% if article.type == 'a' %}
3334
{% if not isindex %}
34-
{% load_breadcrumb article %}
35+
{% cache 36000 breadcrumb article.pk %}
36+
{% load_breadcrumb article %}
37+
{% endcache %}
3538
{% endif %}
3639
{% endif %}
3740
</header><!-- .entry-header -->
Lines changed: 33 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,33 @@
11
{% load blog_tags %}
2-
<footer class="entry-meta">
3-
本条目发布于<a href="{{ article.get_absolute_url }}" title="{% datetimeformat article.created_time %}"
4-
itemprop="datePublished" content="{% datetimeformat article.created_time %}"
5-
rel="bookmark">
2+
{% load cache %}
3+
{% with article.id|add:user.is_authenticated as cachekey %}
4+
{% cache 36000 metainfo cachekey %}
5+
<footer class="entry-meta">
6+
本条目发布于<a href="{{ article.get_absolute_url }}" title="{% datetimeformat article.created_time %}"
7+
itemprop="datePublished" content="{% datetimeformat article.created_time %}"
8+
rel="bookmark">
69

7-
<time class="entry-date updated"
8-
datetime="{{ article.created_time }}">
9-
{% datetimeformat article.created_time %}</time>
10-
</a>
11-
{% if article.type == 'a' %}
12-
。属于<a href="{{ article.category.get_absolute_url }}" rel="category tag">{{ article.category.name }}</a>分类,
13-
{% if article.tags.all %}
14-
被贴了
10+
<time class="entry-date updated"
11+
datetime="{{ article.created_time }}">
12+
{% datetimeformat article.created_time %}</time>
13+
</a>
14+
{% if article.type == 'a' %}
15+
。属于<a href="{{ article.category.get_absolute_url }}" rel="category tag">{{ article.category.name }}</a>
16+
分类,
17+
{% if article.tags.all %}
18+
被贴了
1519

16-
{% for t in article.tags.all %}
17-
<a href="{{ t.get_absolute_url }}" rel="tag">{{ t.name }}</a>
18-
{% if t != article.tags.all.last %}
19-
20-
{% endif %}
21-
{% endfor %}
20+
{% for t in article.tags.all %}
21+
<a href="{{ t.get_absolute_url }}" rel="tag">{{ t.name }}</a>
22+
{% if t != article.tags.all.last %}
23+
24+
{% endif %}
25+
{% endfor %}
2226

23-
标签。
24-
{% endif %}
25-
{% endif %}
26-
<span class="by-author">作者是
27+
标签。
28+
{% endif %}
29+
{% endif %}
30+
<span class="by-author">作者是
2731
<span class="author vcard">
2832
<a class="url fn n" href="{{ article.author.get_absolute_url }}"
2933
title="查看所有由{{ article.author.username }}发布的文章"
@@ -37,8 +41,11 @@
3741
</span>
3842
</a>
3943
</span>
40-
{% if user.is_authenticated %}
41-
<a href="{{ article.get_admin_url }}">编辑</a>
42-
{% endif %}
44+
{% if user.is_authenticated %}
45+
<a href="{{ article.get_admin_url }}">编辑</a>
46+
{% endif %}
4347
</span>
44-
</footer><!-- .entry-meta -->
48+
</footer><!-- .entry-meta -->
49+
50+
{% endcache %}
51+
{% endwith %}

0 commit comments

Comments
 (0)