精简代码,将文章,评论等保存后续动作修改为信号方式

pull/12/head
liangliang 9 years ago
parent 7e5c3eac12
commit f6ab2b7ccb

@ -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 = """
<p>非常感谢您在本站发表评论</p>
您可以访问
<a href="%s" rel="bookmark">%s</a>
来查看您的评论
再次感谢您
<br />
如果上面链接无法打开请将此链接复制至浏览器
%s
""" % (article_url, comment.article.title, article_url)
tomail = comment.author.email
send_email([tomail], subject, html_content)
if comment.parent_comment:
html_content = """
您在 <a href="%s" rel="bookmark">%s</a> 的评论 <br/> %s <br/> 收到回复啦.快去看看吧
<br/>
如果上面链接无法打开请将此链接复制至浏览器
%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)

@ -23,6 +23,7 @@ from pygments.formatters import html
import logging
import _thread
from django.core.mail import EmailMultiAlternatives
from django.conf import settings
logger = logging.getLogger('djangoblog')
@ -144,18 +145,10 @@ class CommonMarkdown():
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):

@ -2,7 +2,7 @@ from django.db import models
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 @@ class Article(BaseModel):
'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 @@ class Article(BaseModel):
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):

@ -18,28 +18,6 @@ from django.forms import ModelForm
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

@ -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 Comment(models.Model):
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 = """
<p>非常感谢您在本站发表评论</p>
您可以访问
<a href="%s" rel="bookmark">%s</a>
来查看您的评论
再次感谢您
<br />
如果上面链接无法打开请将此链接复制至浏览器
%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 = """
您在 <a href="%s" rel="bookmark">%s</a> 的评论 <br/> %s <br/> 收到回复啦.快去看看吧
<br/>
如果上面链接无法打开请将此链接复制至浏览器
%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

@ -62,25 +62,14 @@ class CommentPostView(FormView):
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))

@ -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)
"""

@ -24,13 +24,3 @@ urlpatterns = [
url(r'^oauth/bindsuccess/(?P<oauthid>\d+).html', views.bindsuccess, name='bindsuccess'),
url(r'^oauth/oauthlogin$', views.oauthlogin,name='oauthlogin')
]
"""
urlpatterns = [
url(r'^oauth/wbauthorize/(?P<sitename>\w+)$', views.wbauthorize),
url(r'^oauth/wboauthurl$', views.wboauthurl),
# url(r'^oauth/wbauthorize/(?P<sitename>\w+)$', views.wbauthorize),
url(r'^oauth/googleoauthurl', views.googleoauthurl),
url(r'^oauth/googleauthorize', views.googleauthorize),
]
"""

@ -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 = '''
<p>恭喜您您已经成功绑定您的邮箱您可以使用{type}来直接免密码登录本网站.欢迎您继续关注本站地址是</p>
<a href="{url}" rel="bookmark">{url}</a>
@ -129,7 +124,9 @@ def emailconfirm(request, id, sign):
<br />
如果上面链接无法打开请将此链接复制至浏览器
{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 @@ class RequireEmailView(FormView):
如果上面链接无法打开请将此链接复制至浏览器
{url}
""".format(url=url)
send_email('绑定您的电子邮箱', content, [email, ])
send_email(emailto=[email, ], title='绑定您的电子邮箱', content=content)
url = reverse('oauth:bindsuccess', kwargs={
'oauthid': oauthid
})

@ -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

@ -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

Loading…
Cancel
Save