Ejemplo n.º 1
0
    def test_validate_account(self):
        site = get_current_site().domain
        user = BlogUser.objects.create_superuser(
            email="*****@*****.**",
            username="******",
            password="******")
        testuser = BlogUser.objects.get(username='******')

        loginresult = self.client.login(username='******',
                                        password='******')
        self.assertEqual(loginresult, True)
        response = self.client.get('/admin/')
        self.assertEqual(response.status_code, 200)

        category = Category()
        category.name = "categoryaaa"
        category.created_time = datetime.datetime.now()
        category.last_mod_time = datetime.datetime.now()
        category.save()

        article = Article()
        article.title = "nicetitleaaa"
        article.body = "nicecontentaaa"
        article.author = user
        article.category = category
        article.type = 'a'
        article.status = 'p'
        article.save()

        response = self.client.get(article.get_admin_url())
        self.assertEqual(response.status_code, 200)
Ejemplo n.º 2
0
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)
Ejemplo n.º 3
0
def send_comment_email(comment):
    site = get_current_site().domain
    subject = 'Thanks for your comment'
    article_url = "https://{site}{path}".format(
        site=site, path=comment.article.get_absolute_url())
    html_content = """
                   <p>Thank you very much for commenting on this site</p>
                   You can visit
                   <a href="%s" rel="bookmark">%s</a>
                   To see your comments,
                   Thank you again!
                   <br />
                   If the above link cannot be opened, please copy this link to your browser.
                   %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 = """
                    You are <a href="%s" rel="bookmark">%s</a> 的评论 <br/> %s <br/> Received a reply. Go and see
                    <br/>
                    If the above link cannot be opened, please copy this link to your browser.
                    %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)
Ejemplo n.º 4
0
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)
Ejemplo n.º 5
0
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 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()
Ejemplo n.º 6
0
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_view_cache(instance.author.username)

        _thread.start_new(send_comment_email, (instance,))

    if clearcache:
        cache.clear()
Ejemplo n.º 7
0
    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>Please click the link below to link your email</p>

                <a href="{url}" rel="bookmark">{url}</a>

                Thank you again!
                <br />
                If the link above cannot be opened, please copy this link to your browser.
                {url}
                """.format(url=url)
        send_email(emailto=[
            email,
        ], title='Link your email', content=content)
        url = reverse('oauth:bindsuccess', kwargs={'oauthid': oauthid})
        url = url + '?type=email'
        return HttpResponseRedirect(url)
Ejemplo n.º 8
0
    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()
Ejemplo n.º 9
0
    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
            })
Ejemplo n.º 10
0
    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_sha256(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)
Ejemplo n.º 11
0
 def get_view_on_site_url(self, obj=None):
     if obj:
         url = obj.get_full_url()
         return url
     else:
         from DjangoBlog.utils import get_current_site
         site = get_current_site().domain
         return site
Ejemplo n.º 12
0
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 DjangoBlog.utils import save_user_avatar
        oauthuser.picture = save_user_avatar(oauthuser.picture)
        oauthuser.save()

    delete_sidebar_cache(oauthuser.author.username)

    cache.clear()
Ejemplo n.º 13
0
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 DjangoBlog.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}
Ejemplo n.º 15
0
def send_comment_email(comment):
    site = get_current_site().domain
    # subject = '感谢您发表的评论'
    subject = 'Gracias por tu comentario'
    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)
    html_content = """
                   <p>Gracias por tu comentario</p>
                   Puedes visitar
                   <a href="%s" rel="bookmark">%s</a>
                   Para ver tu comentario,
                   Gracias de nuevo!
                   <br />
                   Si el enlace anterior no se abre, copie este enlace a su navegador.
                   %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)
            html_content = """
                    Estas en <a href="%s" rel="bookmark">%s</a> Comentario
                    <br/> %s <br/> 
                    Recibí una respuesta. Ve a verla.
                    <br/>           
                    Si el enlace anterior no se abre, copie este enlace a su navegador.
                    %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)
Ejemplo n.º 16
0
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)
    with transaction.atomic():
        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 "djangoblog" + 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>Congratulations, you have successfully bound your mailbox, you can use {type} to directly log in to this website without a password. Welcome to continue to pay attention to this site, the address is</p>

                <a href="{url}" rel="bookmark">{url}</a>

                Thank you again!
                <br />
                If the link above cannot be opened, please copy this link to your browser.
                {url}
    '''.format(type=oauthuser.type, url='http://' + site)

    send_email(emailto=[
        oauthuser.email,
    ],
               title='Congratulations on your successful linking!',
               content=content)
    url = reverse('oauth:bindsuccess', kwargs={'oauthid': id})
    url = url + '?type=success'
    return HttpResponseRedirect(url)
Ejemplo n.º 17
0
def emailconfirm(request, id, sign):
    print(1111111111111)
    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)
    with transaction.atomic():
        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 "djangoblog" + 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)
Ejemplo n.º 18
0
    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 = render_template('confirm_email.j2', vars=locals())
            subject = 'Подтвердите email адрес'
            if content is not None:
                send_email(emailto=[
                    user.email,
                ],
                           title=subject,
                           content=content,
                           images={
                               "logo.png": "image/png",
                               "mail_icon.png": "image/png"
                           })

            url = reverse('accounts:result') + '?type=register&id=' + str(
                user.id)
            messages.success(
                self.request,
                f"Новый аккаунт %s создан. Подтвердите свой почтовый ящик: %s"
                % (user.username, user.email))
            return HttpResponseRedirect(url)
        else:
            messages.error(self.request, form.errors)
            return self.render_to_response({'form': form})
Ejemplo n.º 19
0
    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>Please click the link below to verify your email</p>

                            <a href="{url}" rel="bookmark">{url}</a>

                            Thank you again!
                            <br />
                            If the link above cannot be opened, please copy this link to your browser.
                            {url}
                            """.format(url=url)
            send_email(emailto=[
                user.email,
            ],
                       title='Verify your email',
                       content=content)

            url = reverse('accounts:result') + \
                '?type=register&id=' + str(user.id)
            return HttpResponseRedirect(url)
        else:
            return self.render_to_response({'form': form})
Ejemplo n.º 20
0
    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 = timezone.now()
        category.last_mod_time = timezone.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()
        from blog.documents import ELASTICSEARCH_ENABLED
        if ELASTICSEARCH_ENABLED:
            call_command("build_index")
            response = self.client.get('/search', {'q': 'nicetitle'})
            self.assertEqual(response.status_code, 200)

        response = self.client.get(article.get_absolute_url())
        self.assertEqual(response.status_code, 200)
        from DjangoBlog.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 DjangoBlog.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('*****@*****.**')

        link = Links(
            sequence=1,
            name="lylinux",
            link='https://wwww.lylinux.net')
        link.save()
        response = self.client.get('/links.html')
        self.assertEqual(response.status_code, 200)

        rsp = self.client.get('/refresh')
        self.assertEqual(rsp.status_code, 200)

        response = self.client.get('/feed/')
        self.assertEqual(response.status_code, 200)

        response = self.client.get('/sitemap.xml')
        self.assertEqual(response.status_code, 200)
        from DjangoBlog.utils import block_code
        block = block_code("`python`", 'python')
        self.client.get("/admin/blog/article/1/delete/")
        self.client.get('/admin/servermanager/emailsendlog/')
        self.client.get('admin/admin/logentry/')
Ejemplo n.º 21
0
    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 = 'www.cxx1.com:80'
        path = reverse('oauth:email_confirm', kwargs={
            'id': oauthid,
            'sign': sign
        })
        url = "http://{site}{path}".format(site=site, path=path)

        content = """
                <div style="background-color:#ECECEC; padding: 35px;">
    <table cellpadding="0" align="center"
           style="width: 600px; margin: 0px auto; text-align: left; position: relative; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; font-size: 14px; font-family:微软雅黑, 黑体; line-height: 1.5; box-shadow: rgb(153, 153, 153) 0px 0px 5px; border-collapse: collapse; background-position: initial initial; background-repeat: initial initial;background:#fff;">
        <tbody>
        <tr>
            <th valign="middle"
                style="height: 25px; line-height: 25px; padding: 15px 35px; border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: #42a3d3; background-color: #49bcff; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 0px; border-bottom-left-radius: 0px;">
                <font face="微软雅黑" size="5" style="color: rgb(255, 255, 255); ">欢迎来到Cxx1.COM! </font>
            </th>
        </tr>
        <tr>
            <td>
                <div style="padding:25px 35px 40px; background-color:#fff;">
                    <h2 style="margin: 5px 0px; ">
                        <font color="#333333" style="line-height: 20px; ">
                            <font style="line-height: 22px; " size="4">
                                亲爱的用户请绑定邮箱</font>
                        </font>
                    </h2>
                    <p>首先感谢您加入本Cxx1站!请点击下方链接<br>
                        <b> <a href="{url}" rel="bookmark">{url}</a></b><br>
                        <b>如果没法打开请点击: {url} 并且复制到游览器</b>
                    <p align="right"></p>
                    <div style="width:700px;margin:0 auto;">
                        <div style="padding:10px 10px 0;border-top:1px solid #ccc;color:#747474;margin-bottom:20px;line-height:1.3em;font-size:12px;">
                            <p>此为系统邮件,请勿回复<br>
                                请保管好您的邮箱,避免账号被他人盗用
                            </p>
                            <p>©***</p>
                        </div>
                    </div>
                </div>
            </td>
        </tr>
        </tbody>
    </table>
</div>
                """.format(url=url)
        send_email(emailto=[email, ], title='绑定您的电子邮箱', content=content)
        url = reverse('oauth:bindsuccess', kwargs={
            'oauthid': oauthid
        })
        url = url + '?type=email'
        return HttpResponseRedirect(url)
Ejemplo n.º 22
0
 def get_full_url(self):
     site = get_current_site().domain
     url = "https://{site}{path}".format(site=site,
                                         path=self.get_absolute_url())
     return url
Ejemplo n.º 23
0
    def test_validate_article(self):
        site = get_current_site().domain
        user = BlogUser.objects.get_or_create(email="*****@*****.**",
                                              username="******")[0]
        user.set_password("superstrongz")
        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/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 DjangoBlog.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, '作者文章归档', 'superstrongz')

        p = Paginator(Article.objects.filter(category=category), 2)
        self.__check_pagination__(p, '分类目录归档', category.slug)

        f = BlogSearchForm()
        f.search()
        self.client.login(username='******', password='******')
        from DjangoBlog.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('*****@*****.**')
Ejemplo n.º 24
0
@version: ??
@author: superstrongz
@license: MIT Licence
@contact: [email protected]
@site: http://www.superstrongz.com/
@software: PyCharm
@file: ping_baidu.py
@time: ??
"""

from django.core.management.base import BaseCommand, CommandError
from blog.models import Article, Tag, Category
from DjangoBlog.spider_notify import SpiderNotify
from DjangoBlog.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):
        url = "https://{site}{path}".format(site=site, path=path)
        return url

    def handle(self, *args, **options):
        type = options['data_type']
Ejemplo n.º 25
0
    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)