Skip to content

Commit

Permalink
Merge branch 'master' of github.com:liangliangyy/DjangoBlog
Browse files Browse the repository at this point in the history
  • Loading branch information
liangliangyy committed Aug 12, 2017
2 parents 588d38d + 75243b4 commit 1805f8e
Show file tree
Hide file tree
Showing 11 changed files with 128 additions and 175 deletions.
100 changes: 100 additions & 0 deletions DjangoBlog/blog_signals.py
Original file line number Diff line number Diff line change
@@ -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)
15 changes: 4 additions & 11 deletions DjangoBlog/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import logging
import _thread
from django.core.mail import EmailMultiAlternatives
from django.conf import settings

logger = logging.getLogger('djangoblog')

Expand Down Expand Up @@ -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):
Expand Down
38 changes: 7 additions & 31 deletions blog/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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()
Expand All @@ -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):
Expand Down
37 changes: 0 additions & 37 deletions comments/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down
48 changes: 1 addition & 47 deletions comments/models.py
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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 = """
<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
17 changes: 3 additions & 14 deletions comments/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
9 changes: 0 additions & 9 deletions oauth/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
"""
10 changes: 0 additions & 10 deletions oauth/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,3 @@
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),
]
"""

0 comments on commit 1805f8e

Please sign in to comment.