-
Notifications
You must be signed in to change notification settings - Fork 844
/
Copy pathrandom_article.py
91 lines (65 loc) · 1.98 KB
/
random_article.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
# -*- coding: utf-8 -*-
"""
Random Article Plugin For Pelican
========================
This plugin generates a html file which redirect to a random article
using javascript's window.location. The generated html file is
saved at SITEURL.
"""
from __future__ import unicode_literals
import os.path
import logging
from codecs import open
from pelican import signals
log = logging.getLogger(__name__)
HTML_TOP = """
<!DOCTYPE html>
<head>
<title>random</title>
<script type="text/javascript">
function redirect(){
var urls = [
"""
HTML_BOTTOM = """
""];
var index = Math.floor(Math.random() * (urls.length-1));
window.location = urls[index];
}
</script>
<body onload="redirect()">
</body>
</html>
"""
ARTICLE_URL = """ "{0}/{1}",
"""
class RandomArticleGenerator(object):
"""
The structure is derived from sitemap plugin
"""
def __init__(self, context, settings, path, theme, output_path, *null):
self.output_path = output_path
self.context = context
self.siteurl = settings.get('SITEURL')
self.randomurl = settings.get('RANDOM')
def write_url(self, article, fd):
if getattr(article, 'status', 'published') != 'published':
return
page_path = os.path.join(self.output_path, article.url)
if not os.path.exists(page_path):
return
fd.write(ARTICLE_URL.format(self.siteurl, article.url))
def generate_output(self, writer):
path = os.path.join(self.output_path, self.randomurl)
articles = self.context['articles']
log.info('writing %r', path)
if len(articles) == 0:
return
with open(path, 'w', encoding='utf-8') as fd:
fd.write(HTML_TOP)
for art in articles:
self.write_url(art, fd)
fd.write(HTML_BOTTOM)
def get_generators(generators):
return RandomArticleGenerator
def register():
signals.get_generators.connect(get_generators)