From f6ab2b7ccb8ea53809f143b8a4e664f5d5891892 Mon Sep 17 00:00:00 2001 From: liangliang Date: Sun, 13 Aug 2017 04:12:17 +0800 Subject: [PATCH] =?UTF-8?q?=E7=B2=BE=E7=AE=80=E4=BB=A3=E7=A0=81=EF=BC=8C?= =?UTF-8?q?=E5=B0=86=E6=96=87=E7=AB=A0=EF=BC=8C=E8=AF=84=E8=AE=BA=E7=AD=89?= =?UTF-8?q?=E4=BF=9D=E5=AD=98=E5=90=8E=E7=BB=AD=E5=8A=A8=E4=BD=9C=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E4=B8=BA=E4=BF=A1=E5=8F=B7=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DjangoBlog/blog_signals.py | 100 +++++++++++++++++++++++++++++++++++ DjangoBlog/utils.py | 15 ++---- blog/models.py | 38 +++---------- comments/forms.py | 37 ------------- comments/models.py | 48 +---------------- comments/views.py | 17 ++---- oauth/admin.py | 9 ---- oauth/urls.py | 10 ---- oauth/views.py | 13 ++--- requirements.txt | 8 +-- travis_test/requirements.txt | 8 +-- 11 files changed, 128 insertions(+), 175 deletions(-) create mode 100644 DjangoBlog/blog_signals.py diff --git a/DjangoBlog/blog_signals.py b/DjangoBlog/blog_signals.py new file mode 100644 index 00000000..8e33bfd3 --- /dev/null +++ b/DjangoBlog/blog_signals.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python +# encoding: utf-8 + + +""" +@version: ?? +@author: liangliangyy +@license: MIT Licence +@contact: liangliangyy@gmail.com +@site: https://www.lylinux.org/ +@software: PyCharm +@file: blog_signals.py +@time: 2017/8/12 上午10:18 +""" + +import django.dispatch +from django.dispatch import receiver +from django.conf import settings +from DjangoBlog.utils import cache, send_email, expire_view_cache, logger +from DjangoBlog.spider_notify import SpiderNotify +from django.contrib.sites.models import Site + +comment_save_signal = django.dispatch.Signal(providing_args=["comment_id", "username", "serverport"]) +article_save_signal = django.dispatch.Signal(providing_args=['id', 'is_update_views']) +user_login_logout_signal = django.dispatch.Signal(providing_args=['id', 'type']) + + +@receiver(article_save_signal) +def article_save_callback(sender, **kwargs): + id = kwargs['id'] + is_update_views = kwargs['is_update_views'] + type = sender.__name__ + obj = None + from blog.models import Article, Category, Tag + if type == 'Article': + obj = Article.objects.get(id=id) + elif type == 'Category': + obj = Category.objects.get(id=id) + elif type == 'Tag': + obj = Tag.objects.get(id=id) + if obj is not None: + if not settings.TESTING and not is_update_views: + try: + notify_url = obj.get_full_url() + SpiderNotify.baidu_notify([notify_url]) + except Exception as ex: + logger.error("notify sipder", ex) + print(ex) + + +@receiver(comment_save_signal) +def comment_save_callback(sender, **kwargs): + from comments.models import Comment + + serverport = kwargs['serverport'] + username = kwargs['username'] + comment = Comment.objects.get(id=kwargs['comment_id']) + site = Site.objects.get_current().domain + article = comment.article + # if not settings.DEBUG: + if True: + subject = '感谢您发表的评论' + article_url = "https://{site}{path}".format(site=site, path=comment.article.get_absolute_url()) + html_content = """ +

非常感谢您在本站发表评论

+ 您可以访问 + %s + 来查看您的评论, + 再次感谢您! +
+ 如果上面链接无法打开,请将此链接复制至浏览器。 + %s + """ % (article_url, comment.article.title, article_url) + tomail = comment.author.email + send_email([tomail], subject, html_content) + + if comment.parent_comment: + html_content = """ + 您在 %s 的评论
%s
收到回复啦.快去看看吧 +
+ 如果上面链接无法打开,请将此链接复制至浏览器。 + %s + """ % (article_url, article.title, comment.parent_comment.body, article_url) + tomail = comment.parent_comment.author.email + send_email([tomail], subject, html_content) + + path = article.get_absolute_url() + site = Site.objects.get_current().domain + if site.find(':') > 0: + site = site[0:site.find(':')] + + expire_view_cache(path, servername=site, serverport=serverport, key_prefix='blogdetail') + if cache.get('seo_processor'): + cache.delete('seo_processor') + comment_cache_key = 'article_comments_{id}'.format(id=article.id) + cache.delete(comment_cache_key) + from django.core.cache.utils import make_template_fragment_key + + key = make_template_fragment_key('sidebar', [username]) + cache.delete(key) diff --git a/DjangoBlog/utils.py b/DjangoBlog/utils.py index c1516a3a..6b44ff34 100644 --- a/DjangoBlog/utils.py +++ b/DjangoBlog/utils.py @@ -23,6 +23,7 @@ import logging import _thread from django.core.mail import EmailMultiAlternatives +from django.conf import settings logger = logging.getLogger('djangoblog') @@ -144,18 +145,10 @@ def get_markdown(value): return mdp(value) -def send_email(subject, html_content, tomail): - msg = EmailMultiAlternatives(subject, html_content, from_email='no-reply@lylinux.net', to=tomail) +def send_email(emailto, title, content): + msg = EmailMultiAlternatives(title, content, from_email=settings.DEFAULT_FROM_EMAIL, to=emailto) msg.content_subtype = "html" - - def send_comment_email(msg): - try: - msg.send() - except: - print('send email error') - pass - - _thread.start_new_thread(send_comment_email, (msg,)) + _thread.start_new_thread(msg.send, (msg,)) def parse_dict_to_url(dict): diff --git a/blog/models.py b/blog/models.py index 28d8fc23..22f8436d 100644 --- a/blog/models.py +++ b/blog/models.py @@ -2,7 +2,7 @@ from django.core.urlresolvers import reverse from django.conf import settings from uuslug import slugify -from DjangoBlog.spider_notify import SpiderNotify + from django.contrib.sites.models import Site from DjangoBlog.utils import cache_decorator, logger, cache from django.utils.functional import cached_property @@ -12,21 +12,15 @@ class BaseModel(models.Model): slug = models.SlugField(default='no-slug', max_length=60, blank=True) def save(self, *args, **kwargs): + from DjangoBlog.blog_signals import article_save_signal if not self.slug or self.slug == 'no-slug' or not self.id: - # Only set the slug when the object is created. slug = self.title if 'title' in self.__dict__ else self.name self.slug = slugify(slug) super().save(*args, **kwargs) - - if 'update_fields' in kwargs and len(kwargs['update_fields']) == 1 and kwargs['update_fields'][0] == 'views': - return - try: - if not settings.TESTING: - notify_url = self.get_full_url() - SpiderNotify.baidu_notify([notify_url]) - except Exception as ex: - logger.error("notify sipder", ex) - print(ex) + # type = self.__class__.__name__ + is_update_views = 'update_fields' in kwargs and len(kwargs['update_fields']) == 1 and kwargs['update_fields'][ + 0] == 'views' + article_save_signal.send(sender=self.__class__, is_update_views=is_update_views, id=self.id) def get_full_url(self): site = Site.objects.get_current().domain @@ -82,17 +76,6 @@ def get_absolute_url(self): 'day': self.created_time.day }) - # todo remove - """ - return reverse('blog:detail', kwargs={ - 'article_id': self.id, - 'year': self.created_time.year, - 'month': self.created_time.month, - 'day': self.created_time.day, - 'slug': self.slug - }) - """ - @cache_decorator(60 * 60 * 10) def get_category_tree(self): tree = self.category.get_category_tree() @@ -101,17 +84,10 @@ def get_category_tree(self): return names def save(self, *args, **kwargs): - # self.summary = self.summary or self.body[:settings.ARTICLE_SUB_LENGTH] if not self.slug or self.slug == 'no-slug' or not self.id: # Only set the slug when the object is created. self.slug = slugify(self.title) - """ - try: - notify = sipder_notify() - notify.notify(self.get_full_url()) - except Exception as e: - print(e) - """ + super().save(*args, **kwargs) def viewed(self): diff --git a/comments/forms.py b/comments/forms.py index afb750c6..3cf8fda2 100644 --- a/comments/forms.py +++ b/comments/forms.py @@ -18,28 +18,6 @@ from django.contrib.auth.models import User from django.contrib.auth import get_user_model -""" -class CommentForm(forms.Form): - url = forms.URLField(label='网址', required=False) - email = forms.EmailField(label='电子邮箱', required=False) - name = forms.CharField(label='姓名') - body = forms.CharField(widget=forms.Textarea, label='评论') - parent_comment_id = forms.IntegerField(widget=forms.HiddenInput, required=False) - - - -class LoginCommentForm(ModelForm): - url = forms.URLField(label='网址', required=False) - email = forms.EmailField(label='电子邮箱', required=False, widget=forms.HiddenInput) - name = forms.CharField(label='姓名', widget=forms.HiddenInput) - parent_comment_id = forms.IntegerField(widget=forms.HiddenInput, required=False) - def __init__(self): - pass - class Meta: - model = Comment - fields = ['body'] -""" - class CommentForm(ModelForm): url = forms.URLField(label='网址', required=False) @@ -49,21 +27,6 @@ class CommentForm(ModelForm): 'aria-required': 'true'} )) parent_comment_id = forms.IntegerField(widget=forms.HiddenInput, required=False) - """ - if get_user_model().is_authenticated: - email = forms.EmailField(label='电子邮箱', required=False, widget=forms.HiddenInput) - name = forms.CharField(label='姓名', widget=forms.HiddenInput) - """ - """ - def __init__(self, user, *args, **kwargs): - self.user = user - super(CommentForm, self).__init__(*args, **kwargs) - if self.user.is_authenticated: - self.fields.update({ - 'email': forms.CharField(widget=forms.HiddenInput()), - 'name': forms.CharField(widget=forms.HiddenInput()), - }) - """ class Meta: model = Comment diff --git a/comments/models.py b/comments/models.py index 6b5a22e5..b13b780b 100644 --- a/comments/models.py +++ b/comments/models.py @@ -1,11 +1,7 @@ from django.db import models from django.conf import settings -from django.core.mail import send_mail -from django.core.mail import EmailMultiAlternatives -from django.contrib.sites.models import Site -import _thread from blog.models import Article -from DjangoBlog.utils import cache +from DjangoBlog.utils import logger # Create your models here. @@ -24,50 +20,8 @@ class Meta: verbose_name_plural = verbose_name get_latest_by = 'created_time' - def send_comment_email(self, msg): - try: - msg.send() - except: - pass - def __str__(self): return self.body def save(self, *args, **kwargs): super().save(*args, **kwargs) - if not settings.DEBUG: - subject = '感谢您发表的评论' - site = Site.objects.get_current().domain - article_url = "https://{site}{path}".format(site=site, path=self.article.get_absolute_url()) - html_content = """ -

非常感谢您在本站发表评论

- 您可以访问 - %s - 来查看您的评论, - 再次感谢您! -
- 如果上面链接无法打开,请将此链接复制至浏览器。 - %s - """ % (article_url, self.article.title, article_url) - tomail = self.author.email - msg = EmailMultiAlternatives(subject, html_content, from_email='no-reply@lylinux.net', to=[tomail]) - - msg.content_subtype = "html" - - _thread.start_new_thread(self.send_comment_email, (msg,)) - - if self.parent_comment: - html_content = """ - 您在 %s 的评论
%s
收到回复啦.快去看看吧 -
- 如果上面链接无法打开,请将此链接复制至浏览器。 - %s - """ % (article_url, self.article.title, self.parent_comment.body, article_url) - tomail = self.parent_comment.author.email - msg = EmailMultiAlternatives(subject, html_content, from_email='no-reply@lylinux.net', to=[tomail]) - msg.content_subtype = "html" - - _thread.start_new_thread(self.send_comment_email, (msg,)) - - def __str__(self): - return self.body diff --git a/comments/views.py b/comments/views.py index 0c8bf7d1..34c9338b 100644 --- a/comments/views.py +++ b/comments/views.py @@ -62,25 +62,14 @@ def form_valid(self, form): comment.parent_comment = parent_comment comment.save(True) - from DjangoBlog.utils import expire_view_cache, cache - from django.contrib.sites.models import Site - path = article.get_absolute_url() - site = Site.objects.get_current().domain - if site.find(':') > 0: - site = site[0:site.find(':')] + + from DjangoBlog.blog_signals import comment_save_signal port = 80 try: # django1.8 没有这个方法... port = self.request.get_port() except: pass - expire_view_cache(path, servername=site, serverport=port, key_prefix='blogdetail') - if cache.get('seo_processor'): - cache.delete('seo_processor') - comment_cache_key = 'article_comments_{id}'.format(id=article_id) - cache.delete(comment_cache_key) - from django.core.cache.utils import make_template_fragment_key username = self.request.user.username if self.request.user else '' - key = make_template_fragment_key('sidebar', [username]) - cache.delete(key) + comment_save_signal.send(sender=self.__class__, comment_id=comment.id, username=username, serverport=port) return HttpResponseRedirect("%s#div-comment-%d" % (article.get_absolute_url(), comment.pk)) diff --git a/oauth/admin.py b/oauth/admin.py index 9d738294..8ec2eec7 100644 --- a/oauth/admin.py +++ b/oauth/admin.py @@ -11,12 +11,3 @@ class OAuthUserAdmin(admin.ModelAdmin): admin.site.register(OAuthUser, OAuthUserAdmin) -""" -author = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='用户', blank=True, null=True) - openid = models.CharField(max_length=50) - nikename = models.CharField(max_length=50, verbose_name='昵称') - token = models.CharField(max_length=150) - picture = models.CharField(max_length=350, blank=True, null=True) - type = models.CharField(blank=False, null=False, max_length=50) - email = models.CharField(max_length=50, null=True, blank=True) -""" diff --git a/oauth/urls.py b/oauth/urls.py index a10fc7e7..c0bc44af 100644 --- a/oauth/urls.py +++ b/oauth/urls.py @@ -24,13 +24,3 @@ url(r'^oauth/bindsuccess/(?P\d+).html', views.bindsuccess, name='bindsuccess'), url(r'^oauth/oauthlogin$', views.oauthlogin,name='oauthlogin') ] - -""" -urlpatterns = [ - url(r'^oauth/wbauthorize/(?P\w+)$', views.wbauthorize), - url(r'^oauth/wboauthurl$', views.wboauthurl), - # url(r'^oauth/wbauthorize/(?P\w+)$', views.wbauthorize), - url(r'^oauth/googleoauthurl', views.googleoauthurl), - url(r'^oauth/googleauthorize', views.googleauthorize), -] -""" diff --git a/oauth/views.py b/oauth/views.py index d7212843..58b96df5 100644 --- a/oauth/views.py +++ b/oauth/views.py @@ -80,12 +80,7 @@ def authorize(request): login(request, author) return HttpResponseRedirect(nexturl) if not email: - # todo - # 未避免用户名重复,暂时使用oauth用户名+openid这种方式来创建用户 - # author = get_user_model().objects.get_or_create(username=user.nikename + '_' + str(user.openid))[0] - # user.author = author user.save() - url = reverse('oauth:require_email', kwargs={ 'oauthid': user.id }) @@ -120,7 +115,7 @@ def emailconfirm(request, id, sign): login(request, author) site = Site.objects.get_current().domain - send_email('恭喜您绑定成功!', ''' + content = '''

恭喜您,您已经成功绑定您的邮箱,您可以使用{type}来直接免密码登录本网站.欢迎您继续关注本站,地址是

{url} @@ -129,7 +124,9 @@ def emailconfirm(request, id, sign):
如果上面链接无法打开,请将此链接复制至浏览器。 {url} - '''.format(type=oauthuser.type, url='http://' + site), [oauthuser.email, ]) + '''.format(type=oauthuser.type, url='http://' + site) + + send_email(emailto=[oauthuser.email, ], title='恭喜您绑定成功!', content=content) url = reverse('oauth:bindsuccess', kwargs={ 'oauthid': id }) @@ -190,7 +187,7 @@ def form_valid(self, form): 如果上面链接无法打开,请将此链接复制至浏览器。 {url} """.format(url=url) - send_email('绑定您的电子邮箱', content, [email, ]) + send_email(emailto=[email, ], title='绑定您的电子邮箱', content=content) url = reverse('oauth:bindsuccess', kwargs={ 'oauthid': oauthid }) diff --git a/requirements.txt b/requirements.txt index 259a207e..d2f72735 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,5 +1,5 @@ appdirs==1.4.3 -Django==1.11.2 +Django==1.11.4 django-appconf==1.0.2 django-autoslug==1.9.3 django-compressor==2.1.1 @@ -13,7 +13,7 @@ markdown2==2.3.4 mistune==0.7.4 olefile==0.44 packaging==16.8 -Pillow==4.1.1 +Pillow==4.2.1 Pygments==2.2.0 PyMySQL==0.7.11 pyparsing==2.2.0 @@ -21,10 +21,10 @@ python-memcached==1.58 python-slugify==1.2.4 pytz==2017.2 rcssmin==1.0.6 -requests==2.17.3 +requests==2.18.3 rjsmin==1.0.12 six==1.10.0 sqlparse==0.2.3 -Unidecode==0.4.20 +Unidecode==0.4.21 webencodings==0.5.1 Whoosh==2.7.4 diff --git a/travis_test/requirements.txt b/travis_test/requirements.txt index f87da8c5..a148d608 100644 --- a/travis_test/requirements.txt +++ b/travis_test/requirements.txt @@ -1,5 +1,5 @@ appdirs==1.4.3 -Django==1.11.2 +Django==1.11.4 django-appconf==1.0.2 django-autoslug==1.9.3 django-compressor==2.1.1 @@ -13,17 +13,17 @@ markdown2==2.3.4 mistune==0.7.4 olefile==0.44 packaging==16.8 -Pillow==4.1.1 +Pillow==4.2.1 Pygments==2.2.0 PyMySQL==0.7.11 pyparsing==2.2.0 python-slugify==1.2.4 pytz==2017.2 rcssmin==1.0.6 -requests==2.17.3 +requests==2.18.3 rjsmin==1.0.12 six==1.10.0 sqlparse==0.2.3 -Unidecode==0.4.20 +Unidecode==0.4.21 webencodings==0.5.1 Whoosh==2.7.4