random_article.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import os.path
  4. from logging import info
  5. from codecs import open
  6. from pelican import signals
  7. HTML_TOP = """
  8. <!DOCTYPE html>
  9. <head>
  10. <title>random</title>
  11. <script type="text/javascript">
  12. function redirect(){
  13. var urls = [
  14. """
  15. HTML_BOTTOM = """
  16. ""];
  17. var index = Math.floor(Math.random() * (urls.length-1));
  18. window.location = urls[index];
  19. }
  20. </script>
  21. <body onload="redirect()">
  22. </body>
  23. </html>
  24. """
  25. ARTICLE_URL = """ "{0}/{1}",
  26. """
  27. class RandomArticleGenerator(object):
  28. """
  29. The structure is derived from sitemap plugin
  30. """
  31. def __init__(self, context, settings, path, theme, output_path, *null):
  32. self.output_path = output_path
  33. self.context = context
  34. self.siteurl = settings.get('SITEURL')
  35. self.randomurl = settings.get('RANDOM')
  36. def write_url(self, article, fd):
  37. if getattr(article, 'status', 'published') != 'published':
  38. return
  39. page_path = os.path.join(self.output_path, article.url)
  40. if not os.path.exists(page_path):
  41. return
  42. fd.write(ARTICLE_URL.format(self.siteurl, article.url))
  43. def generate_output(self, writer):
  44. path = os.path.join(self.output_path, self.randomurl)
  45. articles = self.context['articles']
  46. info('writing {0}'.format(path))
  47. if len(articles) == 0:
  48. return
  49. with open(path, 'w', encoding='utf-8') as fd:
  50. fd.write(HTML_TOP)
  51. for art in articles:
  52. self.write_url(art, fd)
  53. fd.write(HTML_BOTTOM)
  54. def get_generators(generators):
  55. return RandomArticleGenerator
  56. def register():
  57. signals.get_generators.connect(get_generators)