server.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import cherrypy
  2. import configparser
  3. import re
  4. import os
  5. from Configuration import *
  6. class HomePage:
  7. def __init__(self):
  8. self.HtmlPage=None
  9. @cherrypy.expose
  10. def index(self):
  11. if self.HtmlPage==None:
  12. templateFile=open(HomePageTemplateFile)
  13. self.HtmlPage=ConvertTemplateCode(templateFile.read(),LoopSource={'post':postIterator(PostsDir)})
  14. templateFile.close()
  15. return self.HtmlPage
  16. def ConvertTemplateCode(TemplateCode:str,VarsDictionary=DefaultVariables,LoopSource=None):
  17. result=TemplateCode
  18. searchPattern=re.compile(r'(\[::([^\]]*)])') #searching for template code variables
  19. for oldString,variableName in searchPattern.findall(result):
  20. if variableName in VarsDictionary:
  21. result=result.replace(oldString,VarsDictionary[variableName])
  22. if LoopSource!=None:
  23. for regGroups in re.findall(r'(\[::foreach (\w*)](\n(\s*((?!\[::end\]).)*\n?)*)\[::end])',result):
  24. #searching for template code foreach
  25. #foreach regex groups:
  26. # 0: old full string for replacing
  27. # 1: foreach source
  28. # 2: repeatable template
  29. # 3: the last content line.(no needed, just needed for regex algurithm)
  30. newHtml=''
  31. for localVarsDict in LoopSource[regGroups[1]]:
  32. sec=ConvertTemplateCode(regGroups[2])
  33. sec=ConvertTemplateCode(sec,localVarsDict)
  34. newHtml+=sec
  35. result=result.replace(regGroups[0],newHtml)
  36. return result
  37. class postIterator:
  38. def __init__(self,filesDir):
  39. self.filesDir=filesDir
  40. self.filesList= [os.path.join(filesDir,p) for p in os.listdir(filesDir)]
  41. def __iter__(self):
  42. return self
  43. def __next__(self):
  44. if len(self.filesList)>0:
  45. filePath=self.filesList.pop()
  46. f=open(filePath)
  47. header=f.readline()
  48. res=f.read()
  49. f.close()
  50. return {'header':header,'content':res}
  51. raise StopIteration
  52. if __name__ == "__main__":
  53. conf = {"global":
  54. {
  55. "server.socket_host": 'localhost',
  56. "server.socket_port": 80,
  57. "log.screen": True,
  58. "log.access_file": 'access.txt',
  59. "log.error_file": 'error.log',
  60. "tools.staticdir.root": '\\',
  61. "tools.staticdir.on": True,
  62. "tools.staticdir.dir": "",
  63. }
  64. }
  65. cherrypy.quickstart(HomePage(), "/", conf)