def model_post_save_callback(sender, instance, created, raw, using, update_fields, **kwargs): clearcache = False if isinstance(instance, LogEntry): return if 'get_full_url' in dir(instance): is_update_views = update_fields == {'views'} if not settings.TESTING and not is_update_views: try: notify_url = instance.get_full_url() SpiderNotify.baidu_notify([notify_url]) except Exception as ex: logger.error("notify sipder", ex) if not is_update_views: clearcache = True if isinstance(instance, Comment): path = instance.article.get_absolute_url() site = get_current_site().domain if site.find(':') > 0: site = site[0:site.find(':')] expire_view_cache(path, servername=site, serverport=80, key_prefix='blogdetail') if cache.get('seo_processor'): cache.delete('seo_processor') comment_cache_key = 'article_comments_{id}'.format(id=instance.article.id) cache.delete(comment_cache_key) delete_sidebar_cache(instance.author.username) delete_view_cache('article_comments', [str(instance.article.pk)]) _thread.start_new(send_comment_email, (instance,)) if clearcache: cache.clear()
def send_comment_email(comment): site = get_current_site().domain 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) try: if comment.parent_comment: html_content = """ 您在 <a href="%s" rel="bookmark">%s</a> 的评论 <br/> %s <br/> 收到回复啦.快去看看吧 <br/> 如果上面链接无法打开,请将此链接复制至浏览器。 %s """ % (article_url, comment.article.title, comment.parent_comment.body, article_url) tomail = comment.parent_comment.author.email send_email([tomail], subject, html_content) except Exception as e: logger.error(e)
def form_valid(self, form): email = form.cleaned_data['email'] oauthid = form.cleaned_data['oauthid'] oauthuser = get_object_or_404(OAuthUser, pk=oauthid) oauthuser.email = email oauthuser.save() sign = get_md5(settings.SECRET_KEY + str(oauthuser.id) + settings.SECRET_KEY) site = get_current_site().domain if settings.DEBUG: site = '127.0.0.1:8000' path = reverse('oauth:email_confirm', kwargs={ 'id': oauthid, 'sign': sign }) url = "http://{site}{path}".format(site=site, path=path) content = """ <p>请点击下面链接绑定您的邮箱</p> <a href="{url}" rel="bookmark">{url}</a> 再次感谢您! <br /> 如果上面链接无法打开,请将此链接复制至浏览器。 {url} """.format(url=url) send_email(emailto=[ email, ], title='绑定您的电子邮箱', content=content) url = reverse('oauth:bindsuccess', kwargs={'oauthid': oauthid}) url = url + '?type=email' return HttpResponseRedirect(url)
def form_valid(self, form): if form.is_valid(): user = form.save(False) user.is_active = False user.source = 'Register' user.save(True) site = get_current_site().domain sign = get_md5(get_md5(settings.SECRET_KEY + str(user.id))) if settings.DEBUG: site = '127.0.0.1:8000' path = reverse('account:result') url = "http://{site}{path}?type=validation&id={id}&sign={sign}".format(site=site, path=path, id=user.id, sign=sign) content = """ <p>请点击下面链接验证您的邮箱</p> <a href="{url}" rel="bookmark">{url}</a> 再次感谢您! <br /> 如果上面链接无法打开,请将此链接复制至浏览器。 {url} """.format(url=url) send_email(emailto=[user.email, ], title='验证您的电子邮箱', content=content) url = reverse('accounts:result') + '?type=register&id=' + str(user.id) return HttpResponseRedirect(url) else: return self.render_to_response({ 'form': form })
def get_view_on_site_url(self, obj=None): if obj: url = obj.get_full_url() return url else: from web.utils import get_current_site site = get_current_site().domain return site
def test_validate_comment(self): site = get_current_site().domain user = BlogUser.objects.create_superuser(email="*****@*****.**", username="******", password="******") self.client.login(username='******', password='******') c = Category() c.name = "categoryccc" c.created_time = datetime.datetime.now() c.last_mod_time = datetime.datetime.now() c.save() article = Article() article.title = "nicetitleccc" article.body = "nicecontentccc" article.author = user article.category = c article.type = 'a' article.status = 'p' article.save() s = TextMessage([]) s.content = "nice" rsp = search(s, None) rsp = category(None, None) self.assertIsNotNone(rsp) rsp = recents(None, None) self.assertTrue(rsp != '暂时还没有文章') cmd = commands() cmd.title = "test" cmd.command = "ls" cmd.describe = "test" cmd.save() cmdhandler = CommandHandler() rsp = cmdhandler.run('test') self.assertIsNotNone(rsp) s.source = 'u' s.content = 'test' msghandler = MessageHandler(s, {}) # msghandler.userinfo.isPasswordSet = True # msghandler.userinfo.isAdmin = True msghandler.handler() s.content = 'y' msghandler.handler() s.content = 'idcard:12321233' msghandler.handler() s.content = 'weather:上海' msghandler.handler() s.content = 'admin' msghandler.handler() s.content = '123' msghandler.handler() s.content = 'exit' msghandler.handler()
def oauth_user_login_signal_handler(sender, **kwargs): id = kwargs['id'] oauthuser = OAuthUser.objects.get(id=id) site = get_current_site().domain if oauthuser.picture and not oauthuser.picture.find(site) >= 0: from web.utils import save_user_avatar oauthuser.picture = save_user_avatar(oauthuser.picture) oauthuser.save() delete_sidebar_cache(oauthuser.author.username) cache.clear()
def get_redirecturl(request): nexturl = request.GET.get('next_url', None) if not nexturl or nexturl == '/login/' or nexturl == '/login': nexturl = '/' return nexturl p = urlparse(nexturl) if p.netloc: site = get_current_site().domain if not p.netloc.replace('www.', '') == site.replace('www.', ''): logger.info('非法url:' + nexturl) return "/" return nexturl
def load_breadcrumb(article): """ 获得文章面包屑 :param article: :return: """ names = article.get_category_tree() from web.utils import get_blog_setting blogsetting = get_blog_setting() site = get_current_site().domain names.append((blogsetting.sitename, '/')) names = names[::-1] return {'names': names, 'title': article.title}
def emailconfirm(request, id, sign): if not sign: return HttpResponseForbidden() if not get_md5(settings.SECRET_KEY + str(id) + settings.SECRET_KEY).upper() == sign.upper(): return HttpResponseForbidden() oauthuser = get_object_or_404(OAuthUser, pk=id) if oauthuser.author: author = get_user_model().objects.get(pk=oauthuser.author_id) else: result = get_user_model().objects.get_or_create(email=oauthuser.email) author = result[0] if result[1]: author.source = 'emailconfirm' author.username = oauthuser.nikename.strip( ) if oauthuser.nikename.strip( ) else "web" + datetime.datetime.now().strftime('%y%m%d%I%M%S') author.save() oauthuser.author = author oauthuser.save() oauth_user_login_signal.send(sender=emailconfirm.__class__, id=oauthuser.id) login(request, author) site = get_current_site().domain content = ''' <p>恭喜您,您已经成功绑定您的邮箱,您可以使用{type}来直接免密码登录本网站.欢迎您继续关注本站,地址是</p> <a href="{url}" rel="bookmark">{url}</a> 再次感谢您! <br /> 如果上面链接无法打开,请将此链接复制至浏览器。 {url} '''.format(type=oauthuser.type, url='http://' + site) send_email(emailto=[ oauthuser.email, ], title='恭喜您绑定成功!', content=content) url = reverse('oauth:bindsuccess', kwargs={'oauthid': id}) url = url + '?type=success' return HttpResponseRedirect(url)
def get_full_url(self): site = get_current_site().domain url = "https://{site}{path}".format(site=site, path=self.get_absolute_url()) return url
@version: ?? @author: liangliangyy @license: MIT Licence @contact: [email protected] @site: https://www.lylinux.net/ @software: PyCharm @file: ping_baidu.py @time: 2017/1/17 下午15:29 """ from django.core.management.base import BaseCommand, CommandError from blog.models import Article, Tag, Category from web.spider_notify import SpiderNotify from web.utils import get_current_site site = get_current_site().domain class Command(BaseCommand): help = 'notify baidu url' def add_arguments(self, parser): parser.add_argument( 'data_type', type=str, choices=['all', 'article', 'tag', 'category'], help= 'article : all article,tag : all tag,category: all category,all: All of these' ) def get_full_url(self, path):
def test_validate_article(self): site = get_current_site().domain user = BlogUser.objects.get_or_create(email="*****@*****.**", username="******")[0] user.set_password("liangliangyy") user.is_staff = True user.is_superuser = True user.save() response = self.client.get(user.get_absolute_url()) self.assertEqual(response.status_code, 200) response = self.client.get('/admin/servermanager/emailsendlog/') response = self.client.get('admin/admin/logentry/') s = SideBar() s.sequence = 1 s.name = 'test' s.content = 'test content' s.is_enable = True s.save() category = Category() category.name = "category" category.created_time = datetime.datetime.now() category.last_mod_time = datetime.datetime.now() category.save() tag = Tag() tag.name = "nicetag" tag.save() article = Article() article.title = "nicetitle" article.body = "nicecontent" article.author = user article.category = category article.type = 'a' article.status = 'p' article.save() self.assertEqual(0, article.tags.count()) article.tags.add(tag) article.save() self.assertEqual(1, article.tags.count()) for i in range(20): article = Article() article.title = "nicetitle" + str(i) article.body = "nicetitle" + str(i) article.author = user article.category = category article.type = 'a' article.status = 'p' article.save() article.tags.add(tag) article.save() response = self.client.get(article.get_absolute_url()) self.assertEqual(response.status_code, 200) from web.spider_notify import SpiderNotify SpiderNotify.notify(article.get_absolute_url()) response = self.client.get(tag.get_absolute_url()) self.assertEqual(response.status_code, 200) response = self.client.get(category.get_absolute_url()) self.assertEqual(response.status_code, 200) response = self.client.get('/search', {'q': 'django'}) self.assertEqual(response.status_code, 200) s = load_articletags(article) self.assertIsNotNone(s) rsp = self.client.get('/refresh') self.assertEqual(rsp.status_code, 302) self.client.login(username='******', password='******') rsp = self.client.get('/refresh') self.assertEqual(rsp.status_code, 200) response = self.client.get(reverse('blog:archives')) self.assertEqual(response.status_code, 200) p = Paginator(Article.objects.all(), 2) self.__check_pagination__(p, '', '') p = Paginator(Article.objects.filter(tags=tag), 2) self.__check_pagination__(p, '分类标签归档', tag.slug) p = Paginator(Article.objects.filter(author__username='******'), 2) self.__check_pagination__(p, '作者文章归档', 'liangliangyy') p = Paginator(Article.objects.filter(category=category), 2) self.__check_pagination__(p, '分类目录归档', category.slug) f = BlogSearchForm() f.search() self.client.login(username='******', password='******') from web.spider_notify import SpiderNotify SpiderNotify.baidu_notify([article.get_full_url()]) from blog.templatetags.blog_tags import gravatar_url, gravatar u = gravatar_url('*****@*****.**') u = gravatar('*****@*****.**')
def test_validate_comment(self): site = get_current_site().domain user = BlogUser.objects.create_superuser( email="*****@*****.**", username="******", password="******") self.client.login(username='******', password='******') category = Category() category.name = "categoryccc" category.created_time = datetime.datetime.now() category.last_mod_time = datetime.datetime.now() category.save() article = Article() article.title = "nicetitleccc" article.body = "nicecontentccc" article.author = user article.category = category article.type = 'a' article.status = 'p' article.save() commenturl = reverse('comments:postcomment', kwargs={'article_id': article.id}) response = self.client.post(commenturl, {'body': '123ffffffffff'}) self.assertEqual(response.status_code, 200) article = Article.objects.get(pk=article.pk) self.assertEqual(len(article.comment_list()), 0) response = self.client.post(commenturl, { 'body': '123ffffffffff', 'email': user.email, 'name': user.username }) self.assertEqual(response.status_code, 302) article = Article.objects.get(pk=article.pk) self.assertEqual(len(article.comment_list()), 1) parent_comment_id = article.comment_list()[0].id response = self.client.post( commenturl, { 'body': ''' # Title1 ```python import os ``` [url](https://www.lylinux.net/) [ddd](http://www.baidu.com) ''', 'email': user.email, 'name': user.username, 'parent_comment_id': parent_comment_id }) self.assertEqual(response.status_code, 302) article = Article.objects.get(pk=article.pk) self.assertEqual(len(article.comment_list()), 2) comment = Comment.objects.get(id=parent_comment_id) tree = parse_commenttree(article.comment_list(), comment) self.assertEqual(len(tree), 1) data = show_comment_item(comment, True) self.assertIsNotNone(data) s = get_max_articleid_commentid() self.assertIsNotNone(s)