/
views.py
255 lines (208 loc) · 8.97 KB
/
views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
from django.db.models import Count
from django.http import Http404, HttpResponseForbidden, JsonResponse, HttpResponseBadRequest
from django.shortcuts import get_object_or_404, render, reverse
from django.utils.text import slugify
from django.views import generic
from django.conf import settings
from django.views.decorators.http import require_http_methods
from .models import Article, Tag, Category, Timeline, Silian, AboutBlog
from .utils import site_full_url
from django.core.cache import cache
import markdown
from markdown.extensions.toc import TocExtension # 锚点的拓展
from pygments.formatters import HtmlFormatter
from markdown.extensions.codehilite import CodeHiliteExtension
import time
from haystack.generic_views import SearchView # 导入搜索视图
from haystack.query import SearchQuerySet
class CustomHtmlFormatter(HtmlFormatter):
def __init__(self, lang_str='', **options):
super().__init__(**options)
# lang_str has the value {lang_prefix}{lang}
# specified by the CodeHilite's options
self.lang_str = lang_str
def _wrap_code(self, source):
yield 0, f'<code class="{self.lang_str}">'
yield from source
yield 0, '</code>'
# Create your views here.
def test_page_view(request):
return render(request, '403.html')
class ArchiveView(generic.ListView):
model = Article
template_name = 'blog/archive.html'
context_object_name = 'articles'
paginate_by = 200
paginate_orphans = 50
class IndexView(generic.ListView):
model = Article
template_name = 'blog/index.html'
context_object_name = 'articles'
paginate_by = getattr(settings, 'BASE_PAGE_BY', None)
paginate_orphans = getattr(settings, 'BASE_ORPHANS', 0)
def get_ordering(self):
# url参数中可以传排序参数
sort = self.request.GET.get('sort')
if sort == 'views':
return '-views', '-update_date', '-id'
return '-is_top', '-create_date'
def get_queryset(self, **kwargs):
queryset = super(IndexView, self).get_queryset()
sort = self.request.GET.get('sort')
if sort == 'comment':
queryset = queryset.annotate(com=Count('article_comments')).order_by('-com', '-views')
return queryset
class DetailView(generic.DetailView):
model = Article
template_name = 'blog/detail.html'
context_object_name = 'article'
def get_object(self, queryset=None):
obj = super(DetailView, self).get_object()
# 设置浏览量增加时间判断,同一篇文章两次浏览超过半小时才重新统计阅览量,作者浏览忽略
u = self.request.user
ses = self.request.session
the_key = self.context_object_name + ':read:{}'.format(obj.id)
is_read_time = ses.get(the_key)
if u == obj.author or u.is_superuser:
pass
else:
if not is_read_time:
obj.update_views()
ses[the_key] = time.time()
else:
now_time = time.time()
t = now_time - is_read_time
if t > 60 * 30:
obj.update_views()
ses[the_key] = time.time()
# 获取文章更新的时间,判断是否从缓存中取文章的markdown,可以避免每次都转换
ud = obj.update_date.strftime("%Y%m%d%H%M%S")
md_key = self.context_object_name + ':markdown:{}:{}'.format(obj.id, ud)
cache_md = cache.get(md_key)
if cache_md and settings.DEBUG is False:
obj.body, obj.toc = cache_md
else:
md = markdown.Markdown(extensions=[
'markdown.extensions.extra',
# 'markdown.extensions.codehilite',
CodeHiliteExtension(pygments_formatter=CustomHtmlFormatter),
TocExtension(slugify=slugify),
])
obj.body = md.convert(obj.body)
obj.toc = md.toc
cache.set(md_key, (obj.body, obj.toc), 3600 * 24 * 7)
return obj
class CategoryView(generic.ListView):
model = Article
template_name = 'blog/category.html'
context_object_name = 'articles'
paginate_by = getattr(settings, 'BASE_PAGE_BY', None)
paginate_orphans = getattr(settings, 'BASE_ORPHANS', 0)
def get_ordering(self):
ordering = super(CategoryView, self).get_ordering()
# url参数中可以传排序参数
sort = self.request.GET.get('sort')
if sort == 'views':
return '-views', '-update_date', '-id'
return ordering
def get_queryset(self, **kwargs):
queryset = super(CategoryView, self).get_queryset()
cate = get_object_or_404(Category, slug=self.kwargs.get('slug'))
return queryset.filter(category=cate)
def get_context_data(self, **kwargs):
context_data = super(CategoryView, self).get_context_data()
cate = get_object_or_404(Category, slug=self.kwargs.get('slug'))
context_data['search_tag'] = '文章分类'
context_data['search_instance'] = cate
return context_data
class TagView(generic.ListView):
model = Article
template_name = 'blog/tag.html'
context_object_name = 'articles'
paginate_by = getattr(settings, 'BASE_PAGE_BY', None)
paginate_orphans = getattr(settings, 'BASE_ORPHANS', 0)
def get_ordering(self):
ordering = super(TagView, self).get_ordering()
# url参数中可以传排序参数
sort = self.request.GET.get('sort')
if sort == 'views':
return '-views', '-update_date', '-id'
return ordering
def get_queryset(self, **kwargs):
queryset = super(TagView, self).get_queryset()
tag = get_object_or_404(Tag, slug=self.kwargs.get('slug'))
return queryset.filter(tags=tag)
def get_context_data(self, **kwargs):
context_data = super(TagView, self).get_context_data()
tag = get_object_or_404(Tag, slug=self.kwargs.get('slug'))
context_data['search_tag'] = '文章标签'
context_data['search_instance'] = tag
return context_data
def AboutView(request):
obj = AboutBlog.objects.first()
if obj:
ud = obj.update_date.strftime("%Y%m%d%H%M%S")
md_key = 'about:markdown:{}:{}'.format(obj.id, ud)
cache_md = cache.get(md_key)
if cache_md and settings.DEBUG is False:
body = cache_md
else:
body = obj.body_to_markdown()
cache.set(md_key, body, 3600 * 24 * 15)
else:
repo_url = 'https://github.com/Hopetree'
body = '<li>作者 Github 地址:<a href="{}">{}</a></li>'.format(repo_url, repo_url)
return render(request, 'blog/about.html', context={'body': body})
class TimelineView(generic.ListView):
model = Timeline
template_name = 'blog/timeline.html'
context_object_name = 'timeline_list'
def get_ordering(self):
return '-update_date',
class SilianView(generic.ListView):
model = Silian
template_name = 'blog/silian.xml'
context_object_name = 'badurls'
# 重写搜索视图,可以增加一些额外的参数,且可以重新定义名称
class MySearchView(SearchView):
template_name = 'search/blog/search.html'
context_object_name = 'search_list'
paginate_by = getattr(settings, 'BASE_PAGE_BY', None)
paginate_orphans = getattr(settings, 'BASE_ORPHANS', 0)
queryset = SearchQuerySet().order_by('-views')
def robots(request):
site_url = site_full_url()
return render(request, 'robots.txt', context={'site_url': site_url}, content_type='text/plain')
class DetailEditView(generic.DetailView):
"""
文章编辑视图
"""
model = Article
template_name = 'blog/articleEdit.html'
context_object_name = 'article'
def get_object(self, queryset=None):
obj = super(DetailEditView, self).get_object()
# 非作者及超管无权访问
if not self.request.user.is_superuser and obj.author != self.request.user:
raise Http404('Invalid request.')
return obj
@require_http_methods(["POST"])
def update_article(request):
"""更新文章,仅管理员和作者可以更新"""
if request.method == 'POST' and request.is_ajax():
article_slug = request.POST.get('article_slug')
article_body = request.POST.get('article_body')
try:
article = Article.objects.get(slug=article_slug)
# 检查当前用户是否是作者
if not request.user.is_superuser and article.author != request.user:
return HttpResponseForbidden("You don't have permission to update this article.")
# 更新article模型的数据
article.body = article_body
article.save()
callback = reverse('blog:detail', kwargs={'slug': article_slug})
response_data = {'message': 'Success', 'data': {'callback': callback}, 'code': 0}
return JsonResponse(response_data)
except Article.DoesNotExist:
return HttpResponseBadRequest("Article not found.")
return HttpResponseBadRequest("Invalid request.")