Skip to content

Commit 3e7063e

Browse files
authored
Merge pull request liangliangyy#394 from liangliangyy/dev
格式化代码&&增加es配置文档
2 parents b3d04c1 + a332ce2 commit 3e7063e

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

62 files changed

+1007
-429
lines changed

DjangoBlog/admin_site.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
"""
66
@version: ??
77
@author: liangliangyy
8-
@license: MIT Licence
8+
@license: MIT Licence
99
@contact: liangliangyy@gmail.com
1010
@site: https://www.lylinux.net/
1111
@software: PyCharm

DjangoBlog/blog_signals.py

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
"""
66
@version: ??
77
@author: liangliangyy
8-
@license: MIT Licence
8+
@license: MIT Licence
99
@contact: liangliangyy@gmail.com
1010
@site: https://www.lylinux.net/
1111
@software: PyCharm
@@ -34,7 +34,8 @@
3434
logger = logging.getLogger(__name__)
3535

3636
oauth_user_login_signal = django.dispatch.Signal(providing_args=['id'])
37-
send_email_signal = django.dispatch.Signal(providing_args=['emailto', 'title', 'content'])
37+
send_email_signal = django.dispatch.Signal(
38+
providing_args=['emailto', 'title', 'content'])
3839

3940

4041
@receiver(send_email_signal)
@@ -43,7 +44,11 @@ def send_email_signal_handler(sender, **kwargs):
4344
title = kwargs['title']
4445
content = kwargs['content']
4546

46-
msg = EmailMultiAlternatives(title, content, from_email=settings.DEFAULT_FROM_EMAIL, to=emailto)
47+
msg = EmailMultiAlternatives(
48+
title,
49+
content,
50+
from_email=settings.DEFAULT_FROM_EMAIL,
51+
to=emailto)
4752
msg.content_subtype = "html"
4853

4954
from servermanager.models import EmailSendLog
@@ -77,7 +82,14 @@ def oauth_user_login_signal_handler(sender, **kwargs):
7782

7883

7984
@receiver(post_save)
80-
def model_post_save_callback(sender, instance, created, raw, using, update_fields, **kwargs):
85+
def model_post_save_callback(
86+
sender,
87+
instance,
88+
created,
89+
raw,
90+
using,
91+
update_fields,
92+
**kwargs):
8193
clearcache = False
8294
if isinstance(instance, LogEntry):
8395
return
@@ -98,10 +110,15 @@ def model_post_save_callback(sender, instance, created, raw, using, update_field
98110
if site.find(':') > 0:
99111
site = site[0:site.find(':')]
100112

101-
expire_view_cache(path, servername=site, serverport=80, key_prefix='blogdetail')
113+
expire_view_cache(
114+
path,
115+
servername=site,
116+
serverport=80,
117+
key_prefix='blogdetail')
102118
if cache.get('seo_processor'):
103119
cache.delete('seo_processor')
104-
comment_cache_key = 'article_comments_{id}'.format(id=instance.article.id)
120+
comment_cache_key = 'article_comments_{id}'.format(
121+
id=instance.article.id)
105122
cache.delete(comment_cache_key)
106123
delete_sidebar_cache(instance.author.username)
107124
delete_view_cache('article_comments', [str(instance.article.pk)])

DjangoBlog/elasticsearch_backend.py

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,11 @@
2929

3030
class ElasticSearchBackend(BaseSearchBackend):
3131
def __init__(self, connection_alias, **connection_options):
32-
super(ElasticSearchBackend, self).__init__(connection_alias, **connection_options)
32+
super(
33+
ElasticSearchBackend,
34+
self).__init__(
35+
connection_alias,
36+
**connection_options)
3337
self.manager = ArticleDocumentManager()
3438
# try:
3539
# self._rebuild(None)
@@ -75,16 +79,14 @@ def search(self, query_string, **kwargs):
7579
start_offset = kwargs.get('start_offset')
7680
end_offset = kwargs.get('end_offset')
7781

78-
q = Q('bool',
79-
should=[Q('match', body=query_string), Q('match', title=query_string)],
80-
minimum_should_match="70%"
81-
)
82+
q = Q('bool', should=[Q('match', body=query_string), Q(
83+
'match', title=query_string)], minimum_should_match="70%")
8284

8385
search = ArticleDocument.search() \
84-
.query('bool', filter=[q]) \
85-
.filter('term', status='p') \
86-
.filter('term', type='a') \
87-
.source(False)[start_offset: end_offset]
86+
.query('bool', filter=[q]) \
87+
.filter('term', status='p') \
88+
.filter('term', type='a') \
89+
.source(False)[start_offset: end_offset]
8890

8991
results = search.execute()
9092
hits = results['hits'].total
@@ -99,8 +101,12 @@ def search(self, query_string, **kwargs):
99101

100102
result_class = SearchResult
101103

102-
result = result_class(app_label, model_name, raw_result['_id'], raw_result['_score'],
103-
**additional_fields)
104+
result = result_class(
105+
app_label,
106+
model_name,
107+
raw_result['_id'],
108+
raw_result['_score'],
109+
**additional_fields)
104110
raw_results.append(result)
105111
facets = {}
106112
spelling_suggestion = None

DjangoBlog/logentryadmin.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
"""
66
@version: ??
77
@author: liangliangyy
8-
@license: MIT Licence
8+
@license: MIT Licence
99
@contact: liangliangyy@gmail.com
1010
@site: https://www.lylinux.net/
1111
@software: PyCharm
@@ -83,9 +83,9 @@ def has_add_permission(self, request):
8383

8484
def has_change_permission(self, request, obj=None):
8585
return (
86-
request.user.is_superuser or
87-
request.user.has_perm('admin.change_logentry')
88-
) and request.method != 'POST'
86+
request.user.is_superuser or
87+
request.user.has_perm('admin.change_logentry')
88+
) and request.method != 'POST'
8989

9090
def has_delete_permission(self, request, obj=None):
9191
return False

DjangoBlog/settings.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@ def env_to_bool(env, default):
2626
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
2727

2828
# SECURITY WARNING: keep the secret key used in production secret!
29-
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY') or 'n9ceqv38)#&mwuat@(mjb_p%em$e8$qyr#fw9ot!=ba6lijx-6'
29+
SECRET_KEY = os.environ.get(
30+
'DJANGO_SECRET_KEY') or 'n9ceqv38)#&mwuat@(mjb_p%em$e8$qyr#fw9ot!=ba6lijx-6'
3031
# SECURITY WARNING: don't run with debug turned on in production!
3132
DEBUG = env_to_bool('DJANGO_DEBUG', True)
3233
# DEBUG = False
@@ -108,10 +109,11 @@ def env_to_bool(env, default):
108109
'USER': os.environ.get('DJANGO_MYSQL_USER') or 'root',
109110
'PASSWORD': os.environ.get('DJANGO_MYSQL_PASSWORD') or 'djangoblog_123',
110111
'HOST': os.environ.get('DJANGO_MYSQL_HOST') or '127.0.0.1',
111-
'PORT': int(os.environ.get('DJANGO_MYSQL_PORT') or 3306),
112-
'OPTIONS': {'charset': 'utf8mb4'},
113-
}
114-
}
112+
'PORT': int(
113+
os.environ.get('DJANGO_MYSQL_PORT') or 3306),
114+
'OPTIONS': {
115+
'charset': 'utf8mb4'},
116+
}}
115117

116118
# Password validation
117119
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
@@ -157,7 +159,8 @@ def env_to_bool(env, default):
157159
# Automatically update searching index
158160
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
159161
# Allow user login with username and password
160-
AUTHENTICATION_BACKENDS = ['accounts.user_login_backend.EmailOrUsernameModelBackend']
162+
AUTHENTICATION_BACKENDS = [
163+
'accounts.user_login_backend.EmailOrUsernameModelBackend']
161164

162165
STATIC_ROOT = os.path.join(SITE_ROOT, 'collectedstatic')
163166

@@ -195,7 +198,7 @@ def env_to_bool(env, default):
195198

196199
SITE_ID = 1
197200
BAIDU_NOTIFY_URL = os.environ.get('DJANGO_BAIDU_NOTIFY_URL') \
198-
or 'http://data.zz.baidu.com/urls?site=https://www.lylinux.net&token=1uAOGrMsUm5syDGn'
201+
or 'http://data.zz.baidu.com/urls?site=https://www.lylinux.net&token=1uAOGrMsUm5syDGn'
199202

200203
# Email:
201204
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
@@ -210,7 +213,8 @@ def env_to_bool(env, default):
210213
# Setting debug=false did NOT handle except email notifications
211214
ADMINS = [('admin', os.environ.get('DJANGO_ADMIN_EMAIL') or 'admin@admin.com')]
212215
# WX ADMIN password(Two times md5)
213-
WXADMIN = os.environ.get('DJANGO_WXADMIN_PASSWORD') or '995F03AC401D6CABABAEF756FC4D43C7'
216+
WXADMIN = os.environ.get(
217+
'DJANGO_WXADMIN_PASSWORD') or '995F03AC401D6CABABAEF756FC4D43C7'
214218

215219
LOGGING = {
216220
'version': 1,

DjangoBlog/spider_notify.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
"""
66
@version: ??
77
@author: liangliangyy
8-
@license: MIT Licence
8+
@license: MIT Licence
99
@contact: liangliangyy@gmail.com
1010
@site: https://www.lylinux.net/
1111
@software: PyCharm

DjangoBlog/tests.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
"""
66
@version: ??
77
@author: liangliangyy
8-
@license: MIT Licence
8+
@license: MIT Licence
99
@contact: liangliangyy@gmail.com
1010
@site: https://www.lylinux.net/
1111
@software: PyCharm
@@ -30,17 +30,17 @@ def test_utils(self):
3030
md5 = get_md5('test')
3131
self.assertIsNotNone(md5)
3232
c = CommonMarkdown.get_markdown('''
33-
# Title1
34-
33+
# Title1
34+
3535
```python
3636
import os
37-
```
38-
39-
[url](https://www.lylinux.net/)
40-
41-
[ddd](http://www.baidu.com)
42-
43-
37+
```
38+
39+
[url](https://www.lylinux.net/)
40+
41+
[ddd](http://www.baidu.com)
42+
43+
4444
''')
4545
self.assertIsNotNone(c)
4646
d = {

DjangoBlog/urls.py

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -37,19 +37,20 @@
3737
handler500 = 'blog.views.server_error_view'
3838
handle403 = 'blog.views.permission_denied_view'
3939
urlpatterns = [
40-
url(r'^admin/', admin_site.urls),
41-
url(r'', include('blog.urls', namespace='blog')),
42-
url(r'mdeditor/', include('mdeditor.urls')),
43-
url(r'', include('comments.urls', namespace='comment')),
44-
url(r'', include('accounts.urls', namespace='account')),
45-
url(r'', include('oauth.urls', namespace='oauth')),
46-
url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps},
47-
name='django.contrib.sitemaps.views.sitemap'),
48-
url(r'^feed/$', DjangoBlogFeed()),
49-
url(r'^rss/$', DjangoBlogFeed()),
50-
url(r'^search', include('haystack.urls'), name='search'),
51-
url(r'', include('servermanager.urls', namespace='servermanager')),
52-
url(r'', include('owntracks.urls', namespace='owntracks'))
53-
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
40+
url(r'^admin/', admin_site.urls),
41+
url(r'', include('blog.urls', namespace='blog')),
42+
url(r'mdeditor/', include('mdeditor.urls')),
43+
url(r'', include('comments.urls', namespace='comment')),
44+
url(r'', include('accounts.urls', namespace='account')),
45+
url(r'', include('oauth.urls', namespace='oauth')),
46+
url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps},
47+
name='django.contrib.sitemaps.views.sitemap'),
48+
url(r'^feed/$', DjangoBlogFeed()),
49+
url(r'^rss/$', DjangoBlogFeed()),
50+
url(r'^search', include('haystack.urls'), name='search'),
51+
url(r'', include('servermanager.urls', namespace='servermanager')),
52+
url(r'', include('owntracks.urls', namespace='owntracks'))
53+
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
5454
if settings.DEBUG:
55-
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
55+
urlpatterns += static(settings.MEDIA_URL,
56+
document_root=settings.MEDIA_ROOT)

DjangoBlog/utils.py

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def news(*args, **kwargs):
4545
try:
4646
view = args[0]
4747
key = view.get_cache_key()
48-
except:
48+
except BaseException:
4949
key = None
5050
if not key:
5151
unique_str = repr((func, args, kwargs))
@@ -60,7 +60,9 @@ def news(*args, **kwargs):
6060
else:
6161
return value
6262
else:
63-
logger.info('cache_decorator set cache:%s key:%s' % (func.__name__, key))
63+
logger.info(
64+
'cache_decorator set cache:%s key:%s' %
65+
(func.__name__, key))
6466
value = func(*args, **kwargs)
6567
if value is None:
6668
cache.set(key, '__default_cache_value__', expiration)
@@ -120,7 +122,7 @@ def block_code(text, lang, inlinestyles=False, linenos=False):
120122
if linenos:
121123
return '<div class="highlight">%s</div>\n' % code
122124
return code
123-
except:
125+
except BaseException:
124126
return '<pre class="%s"><code>%s</code></pre>\n' % (
125127
lang, mistune.escape(text)
126128
)
@@ -163,7 +165,8 @@ def link(self, link, title, text):
163165
if not title:
164166
return '<a href="%s" %s>%s</a>' % (link, nofollow, text)
165167
title = escape(title, quote=True)
166-
return '<a href="%s" title="%s" %s>%s</a>' % (link, title, nofollow, text)
168+
return '<a href="%s" title="%s" %s>%s</a>' % (
169+
link, title, nofollow, text)
167170

168171

169172
class CommonMarkdown():
@@ -177,7 +180,11 @@ def get_markdown(value):
177180

178181
def send_email(emailto, title, content):
179182
from DjangoBlog.blog_signals import send_email_signal
180-
send_email_signal.send(send_email.__class__, emailto=emailto, title=title, content=content)
183+
send_email_signal.send(
184+
send_email.__class__,
185+
emailto=emailto,
186+
title=title,
187+
content=content)
181188

182189

183190
def parse_dict_to_url(dict):
@@ -225,15 +232,17 @@ def save_user_avatar(url):
225232
try:
226233
imgname = url.split('/')[-1]
227234
if imgname:
228-
path = r'{basedir}/avatar/{img}'.format(basedir=setting.resource_path, img=imgname)
235+
path = r'{basedir}/avatar/{img}'.format(
236+
basedir=setting.resource_path, img=imgname)
229237
if os.path.exists(path):
230238
os.remove(path)
231-
except:
239+
except BaseException:
232240
pass
233241
try:
234242
rsp = requests.get(url, timeout=2)
235243
if rsp.status_code == 200:
236-
basepath = r'{basedir}/avatar/'.format(basedir=setting.resource_path)
244+
basepath = r'{basedir}/avatar/'.format(
245+
basedir=setting.resource_path)
237246
if not os.path.exists(basepath):
238247
os.makedirs(basepath)
239248

@@ -253,7 +262,10 @@ def save_user_avatar(url):
253262
def delete_sidebar_cache(username):
254263
from django.core.cache.utils import make_template_fragment_key
255264
from blog.models import LINK_SHOW_TYPE
256-
keys = (make_template_fragment_key('sidebar', [username + x[0]]) for x in LINK_SHOW_TYPE)
265+
keys = (
266+
make_template_fragment_key(
267+
'sidebar', [
268+
username + x[0]]) for x in LINK_SHOW_TYPE)
257269
for k in keys:
258270
logger.info('delete sidebar key:' + k)
259271
cache.delete(k)

0 commit comments

Comments
 (0)