forked from liangliangyy/DjangoBlog
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
81 lines (66 loc) · 2.21 KB
/
utils.py
File metadata and controls
81 lines (66 loc) · 2.21 KB
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
#!/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: utils.py
@time: 2017/1/19 上午2:30
"""
from django.core.cache import cache
from hashlib import md5
import mistune
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import html
import logging
logger = logging.getLogger('djangoblog')
def cache_decorator(expiration=3 * 60):
def wrapper(func):
def news(*args, **kwargs):
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__)
return value
else:
logger.info('cache_decorator set cache %s' % func.__name__)
value = func(*args, **kwargs)
cache.set(key, value, expiration)
return value
return news
return wrapper
def block_code(text, lang, inlinestyles=False, linenos=False):
if not lang:
text = text.strip()
return u'<pre><code>%s</code></pre>\n' % mistune.escape(text)
try:
lexer = get_lexer_by_name(lang, stripall=True)
formatter = html.HtmlFormatter(
noclasses=inlinestyles, linenos=linenos
)
code = highlight(text, lexer, formatter)
if linenos:
return '<div class="highlight">%s</div>\n' % code
return code
except:
return '<pre class="%s"><code>%s</code></pre>\n' % (
lang, mistune.escape(text)
)
class BlogMarkDownRenderer(mistune.Renderer):
def block_code(self, text, lang):
# renderer has an options
inlinestyles = self.options.get('inlinestyles')
linenos = self.options.get('linenos')
return block_code(text, lang, inlinestyles, linenos)
class common_markdown():
@staticmethod
def get_markdown(value):
renderer = BlogMarkDownRenderer(inlinestyles=False)
mdp = mistune.Markdown(escape=True, renderer=renderer)
return mdp(value)