diff --git a/DjangoBlog/settings.py b/DjangoBlog/settings.py index ee65c96..5222bc7 100644 --- a/DjangoBlog/settings.py +++ b/DjangoBlog/settings.py @@ -51,9 +51,9 @@ MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.gzip.GZipMiddleware', - 'django.middleware.cache.UpdateCacheMiddleware', + # 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', - 'django.middleware.cache.FetchFromCacheMiddleware', + # 'django.middleware.cache.FetchFromCacheMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', @@ -144,6 +144,8 @@ HAYSTACK_CONNECTIONS = { } # 自动更新搜索索引 HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor' +#允许使用用户名或密码登录 +AUTHENTICATION_BACKENDS = ['accounts.user_login_backend.EmailOrUsernameModelBackend'] STATIC_ROOT = os.path.join(SITE_ROOT, 'collectedstatic') @@ -157,7 +159,7 @@ TIME_FORMAT = '%Y-%m-%d %H:%M:%S' DATE_TIME_FORMAT = '%Y-%m-%d' SITE_NAME = '且听风吟' -SITE_URL = 'http://blog.lylinux.org' +SITE_URL = 'http://www.lylinux.net' SITE_DESCRIPTION = '大巧无工,重剑无锋.' SITE_SEO_DESCRIPTION = '小站主要用来分享和记录学习经验,教程,记录个人生活的点滴以及一些随笔.欢迎大家访问小站' SITE_SEO_KEYWORDS = 'linux,apache,mysql,服务器,ubuntu,shell,web,csharp,.net,asp,mac,swift' @@ -196,7 +198,7 @@ OAHUTH = { 'sina': { 'appkey': '3161614143', 'appsecret': 'ee17c099317f872eeddb25204ea46721', - 'callbackurl': 'http://blog.lylinux.org/oauth/weibo' + 'callbackurl': 'http://www.lylinux.net/oauth/weibo' }, 'google': { 'appkey': os.environ.get('GOOGLE_APP_KEY'), diff --git a/DjangoBlog/utils.py b/DjangoBlog/utils.py index cdaf945..35f6e35 100644 --- a/DjangoBlog/utils.py +++ b/DjangoBlog/utils.py @@ -23,12 +23,14 @@ import logging logger = logging.getLogger('djangoblog') -def cache_decorator(expiration=3 * 60): +def cache_decorator(expiration=3 * 60, cache_key=None): def wrapper(func): def news(*args, **kwargs): - unique_str = repr((func, args, kwargs)) - m = md5(unique_str.encode('utf-8')) - key = m.hexdigest() + key = cache_key + if not key: + unique_str = repr((func, args, kwargs)) + m = md5(unique_str.encode('utf-8')) + key = m.hexdigest() value = cache.get(key) if value: logger.info('cache_decorator get cache %s' % func.__name__) diff --git a/accounts/forms.py b/accounts/forms.py index 593c8b3..ea25357 100644 --- a/accounts/forms.py +++ b/accounts/forms.py @@ -21,18 +21,18 @@ from django.contrib.auth import get_user_model class LoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) - self.fields['username'].widget = widgets.TextInput(attrs={'placeholder': "用户名", "class": "form-control"}) - self.fields['password'].widget = widgets.PasswordInput(attrs={'placeholder': "密码", "class": "form-control"}) + self.fields['username'].widget = widgets.TextInput(attrs={'placeholder': "username", "class": "form-control"}) + self.fields['password'].widget = widgets.PasswordInput(attrs={'placeholder': "password", "class": "form-control"}) class RegisterForm(UserCreationForm): def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) - self.fields['username'].widget = widgets.TextInput(attrs={'placeholder': "用户名", "class": "form-control"}) - self.fields['email'].widget = widgets.EmailInput(attrs={'placeholder': "邮箱", "class": "form-control"}) - self.fields['password1'].widget = widgets.PasswordInput(attrs={'placeholder': "密码", "class": "form-control"}) - self.fields['password2'].widget = widgets.PasswordInput(attrs={'placeholder': "确认密码", "class": "form-control"}) + self.fields['username'].widget = widgets.TextInput(attrs={'placeholder': "username", "class": "form-control"}) + self.fields['email'].widget = widgets.EmailInput(attrs={'placeholder': "email", "class": "form-control"}) + self.fields['password1'].widget = widgets.PasswordInput(attrs={'placeholder': "password", "class": "form-control"}) + self.fields['password2'].widget = widgets.PasswordInput(attrs={'placeholder': "repeat password", "class": "form-control"}) class Meta: model = get_user_model() diff --git a/accounts/user_login_backend.py b/accounts/user_login_backend.py new file mode 100644 index 0000000..aee3803 --- /dev/null +++ b/accounts/user_login_backend.py @@ -0,0 +1,39 @@ +#!/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: user_login_backend.py +@time: 2017/2/17 下午8:45 +""" +from django.conf import settings +from django.contrib.auth import get_user_model + + +class EmailOrUsernameModelBackend(object): + """ + 允许使用用户名或邮箱登录 + """ + def authenticate(self, username=None, password=None): + if '@' in username: + kwargs = {'email': username} + else: + kwargs = {'username': username} + try: + user = get_user_model().objects.get(**kwargs) + if user.check_password(password): + return user + except get_user_model().DoesNotExist: + return None + + def get_user(self, username): + try: + return get_user_model().objects.get(pk=username) + except get_user_model().DoesNotExist: + return None diff --git a/accounts/views.py b/accounts/views.py index 332476d..55ad8e8 100644 --- a/accounts/views.py +++ b/accounts/views.py @@ -12,6 +12,7 @@ from django.contrib import auth from django.views.decorators.cache import never_cache from django.shortcuts import redirect + # Create your views here. class RegisterView(FormView): @@ -20,9 +21,10 @@ class RegisterView(FormView): def form_valid(self, form): user = form.save(False) - user.save(True) - return HttpResponseRedirect('/') + url = reverse('accounts:login') + return HttpResponseRedirect(url) + @never_cache def LogOut(requests): diff --git a/blog/management/commands/clear_cache.py b/blog/management/commands/clear_cache.py new file mode 100644 index 0000000..db0dad2 --- /dev/null +++ b/blog/management/commands/clear_cache.py @@ -0,0 +1,24 @@ +#!/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: clear_cache.py +@time: 2017/2/17 下午10:30 +""" +from DjangoBlog.utils import cache +from django.core.management.base import BaseCommand + + +class Command(BaseCommand): + help = 'clear the whole cache' + + def handle(self, *args, **options): + cache.clear() + self.stdout.write(self.style.SUCCESS('Cleared cache\n')) diff --git a/blog/urls.py b/blog/urls.py index 0df4561..5588df9 100644 --- a/blog/urls.py +++ b/blog/urls.py @@ -24,7 +24,7 @@ urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^page/(?P\d+)$', views.IndexView.as_view(), name='index_page'), url(r'^article/(?P\d+)/(?P\d+)/(?P\d+)/(?P\d+)-(?P\S+).html$', - views.ArticleDetailView.as_view(), + cache_page(60 * 60 * 10)(views.ArticleDetailView.as_view()), name='detail'), url(r'^blogpage/(?P\d+)/(?P\d+)/(?P\d+)/(?P\d+)-(?P\S+).html$', views.ArticleDetailView.as_view(), diff --git a/blog/views.py b/blog/views.py index 650de52..5df1f8f 100644 --- a/blog/views.py +++ b/blog/views.py @@ -21,6 +21,7 @@ import datetime from django.views.decorators.csrf import csrf_exempt import os from django.contrib.auth.decorators import login_required +from DjangoBlog.utils import cache, cache_decorator """ class SeoProcessor(): @@ -79,7 +80,7 @@ class ArticleDetailView(DetailView): def get_context_data(self, **kwargs): articleid = int(self.kwargs[self.pk_url_kwarg]) - + print(str(articleid) + "get_context_data") comment_form = CommentForm() u = self.request.user @@ -91,6 +92,7 @@ class ArticleDetailView(DetailView): user = self.request.user comment_form.fields["email"].initial = user.email comment_form.fields["name"].initial = user.username + key = "article_comment_{}".format(articleid) article_comments = self.object.comment_set.all() @@ -222,9 +224,11 @@ def fileupload(request): @login_required def refresh_memcache(request): try: + if request.user.is_superuser: - result = os.popen(' service memcached restart ').readline() - return HttpResponse(result) + from DjangoBlog.utils import cache + cache.clear() + return HttpResponse("ok") else: from django.http import HttpResponseForbidden return HttpResponseForbidden() diff --git a/comments/models.py b/comments/models.py index d168ca3..c1a9c9d 100644 --- a/comments/models.py +++ b/comments/models.py @@ -5,6 +5,7 @@ from blog.models import Article from django.core.mail import EmailMultiAlternatives from django.contrib.sites.models import Site import _thread +from DjangoBlog.utils import cache # Create your models here. @@ -26,7 +27,10 @@ class Comment(models.Model): verbose_name_plural = verbose_name def send_comment_email(self, msg): - msg.send() + try: + msg.send() + except: + pass def save(self, *args, **kwargs): super().save(*args, **kwargs) @@ -47,6 +51,7 @@ class Comment(models.Model): 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: @@ -59,7 +64,8 @@ class Comment(models.Model): 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 + def __str__(self): + return self.body diff --git a/comments/views.py b/comments/views.py index 5751e19..c474d91 100644 --- a/comments/views.py +++ b/comments/views.py @@ -9,6 +9,7 @@ from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.contrib.auth import get_user_model from django import forms +from django.contrib import auth class CommentPostView(FormView): @@ -17,7 +18,9 @@ class CommentPostView(FormView): def get(self, request, *args, **kwargs): article_id = self.kwargs['article_id'] - url = reverse('blog:detail', kwargs={'article_id': article_id}) + + article = Article.objects.get(pk=article_id) + url = article.get_absolute_url() return HttpResponseRedirect(url + "#comments") def form_invalid(self, form): @@ -49,20 +52,17 @@ class CommentPostView(FormView): email = form.cleaned_data['email'] username = form.cleaned_data['name'] - user = get_user_model().objects.create_user(username=username, email=email, password=None, - nikename=username) - author_id = user.pk - + user = get_user_model().objects.get_or_create(username=username, email=email)[0] + # auth.login(self.request, user) comment = form.save(False) comment.article = article - comment.author = get_user_model().objects.get(pk=author_id) + comment.author = user if form.cleaned_data['parent_comment_id']: parent_comment = Comment.objects.get(pk=form.cleaned_data['parent_comment_id']) comment.parent_comment = parent_comment comment.save(True) - # return HttpResponseRedirect(article.get_absolute_url() + "#div-comment-" + comment.pk) return HttpResponseRedirect("%s#div-comment-%d" % (article.get_absolute_url(), comment.pk)) diff --git a/templates/account/login.html b/templates/account/login.html index a8c2d68..10800ba 100644 --- a/templates/account/login.html +++ b/templates/account/login.html @@ -23,7 +23,7 @@
- Need help? + {% comment %}Need help?{% endcomment %} @@ -33,7 +33,8 @@

- Create an account + Create Account + | Home Page

diff --git a/templates/account/registration_form.html b/templates/account/registration_form.html index ab551ed..776442d 100644 --- a/templates/account/registration_form.html +++ b/templates/account/registration_form.html @@ -3,7 +3,7 @@ {% block content %}
- + diff --git a/templates/blog/tags/sidebar.html b/templates/blog/tags/sidebar.html index ab7e155..90d20d2 100755 --- a/templates/blog/tags/sidebar.html +++ b/templates/blog/tags/sidebar.html @@ -85,7 +85,7 @@ {% else %} -
  • 登陆 +
  • 登录 {% endif %} diff --git a/templates/share_layout/base.html b/templates/share_layout/base.html index 8cc2fd8..87f4a2c 100644 --- a/templates/share_layout/base.html +++ b/templates/share_layout/base.html @@ -65,9 +65,8 @@ {% block content %} {% endblock %} - {% cache 36000 sidebar %} + {% cache 36000 sidebar request.user.username %} {% block sidebar %} - {% endblock %} {% endcache %}