views.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from django.template import Template, RequestContext
  2. from django.http import HttpResponse, Http404
  3. from django.conf import settings
  4. from django.shortcuts import render
  5. from os import path
  6. def articleVars(fn):
  7. file, url = file_for_url(fn)
  8. vars = {}
  9. with open(file, 'r') as f:
  10. l = f.readline().strip()
  11. while l:
  12. ll = l.split(':', 1)
  13. h = ll[0].strip()
  14. if len(ll) > 1:
  15. v = ll[1].strip()
  16. else:
  17. v = ""
  18. vars[h.lower()] = v
  19. l = f.readline().strip()
  20. return vars
  21. def loadArticle(request, url, f):
  22. vars = {'url': url}
  23. l = f.readline().strip()
  24. while l:
  25. ll = l.split(':', 1)
  26. h = ll[0].strip()
  27. if len(ll) > 1:
  28. v = ll[1].strip()
  29. else:
  30. v = ""
  31. if h.lower() == "display":
  32. return showarticle(request, v)
  33. vars[h.lower()] = v
  34. l = f.readline().strip()
  35. vars['article_text'] = f.read()
  36. if vars.get('previousfile'):
  37. f = vars['previousfile']
  38. print(f)
  39. vars['previous_url'] = '/' + f
  40. prev = articleVars(f)
  41. vars['previous_article'] = prev.get('title', '')
  42. if vars.get('nextfile'):
  43. f = vars['nextfile']
  44. vars['next_url'] = '/' + f
  45. nxt = articleVars(f)
  46. vars['next_article'] = nxt.get('title', '')
  47. return render(request, 'article.html', vars)
  48. def file_for_url(file):
  49. if file.startswith('/'):
  50. file = file[1:]
  51. full_path = path.join(settings.DOC_ROOT, file)
  52. if not path.exists(full_path):
  53. raise Http404
  54. if path.isdir(full_path):
  55. full_path = path.join(full_path, 'index')
  56. return full_path, '/' + file
  57. def showarticle(request, file):
  58. full_path, url = file_for_url(file)
  59. with open(full_path, 'r') as f:
  60. return loadArticle(request, url, f)