Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

229 rindas
5.4 KiB

  1. from __future__ import unicode_literals
  2. import os
  3. import conf
  4. from startup.website import *
  5. import webnotes
  6. import webnotes.utils
  7. def render(page_name):
  8. """render html page"""
  9. try:
  10. if page_name:
  11. html = get_html(page_name)
  12. else:
  13. html = get_html('index')
  14. except Exception:
  15. html = get_html('error')
  16. from webnotes.handler import eprint, print_zip
  17. eprint("Content-Type: text/html; charset: utf-8")
  18. print_zip(html)
  19. def get_html(page_name):
  20. """get page html"""
  21. page_name = scrub_page_name(page_name)
  22. html = ''
  23. # load from cache, if auto cache clear is falsy
  24. if not (hasattr(conf, 'auto_cache_clear') and conf.auto_cache_clear or 0):
  25. if not get_page_settings().get(page_name, {}).get("no_cache"):
  26. html = webnotes.cache().get_value("page:" + page_name)
  27. from_cache = True
  28. if not html:
  29. from webnotes.auth import HTTPRequest
  30. webnotes.http_request = HTTPRequest()
  31. #webnotes.connect()
  32. html = load_into_cache(page_name)
  33. from_cache = False
  34. if not html:
  35. html = get_html("404")
  36. if page_name=="error":
  37. html = html.replace("%(error)s", webnotes.getTraceback())
  38. else:
  39. comments = "\n\npage:"+page_name+\
  40. "\nload status: " + (from_cache and "cache" or "fresh")
  41. html += """\n<!-- %s -->""" % webnotes.utils.cstr(comments)
  42. return html
  43. def scrub_page_name(page_name):
  44. if page_name.endswith('.html'):
  45. page_name = page_name[:-5]
  46. return page_name
  47. def page_name(title):
  48. """make page name from title"""
  49. import re
  50. name = title.lower()
  51. name = re.sub('[~!@#$%^&*()<>,."\']', '', name)
  52. name = re.sub('[:/]', '-', name)
  53. name = '-'.join(name.split())
  54. # replace repeating hyphens
  55. name = re.sub(r"(-)\1+", r"\1", name)
  56. return name
  57. def update_page_name(doc, title):
  58. """set page_name and check if it is unique"""
  59. webnotes.conn.set(doc, "page_name", page_name(title))
  60. if doc.page_name in get_standard_pages():
  61. webnotes.conn.sql("""Page Name cannot be one of %s""" % ', '.join(get_standard_pages()))
  62. res = webnotes.conn.sql("""\
  63. select count(*) from `tab%s`
  64. where page_name=%s and name!=%s""" % (doc.doctype, '%s', '%s'),
  65. (doc.page_name, doc.name))
  66. if res and res[0][0] > 0:
  67. webnotes.msgprint("""A %s with the same title already exists.
  68. Please change the title of %s and save again."""
  69. % (doc.doctype, doc.name), raise_exception=1)
  70. delete_page_cache(doc.page_name)
  71. def load_into_cache(page_name):
  72. args = prepare_args(page_name)
  73. if not args:
  74. return ""
  75. html = build_html(args)
  76. webnotes.cache().set_value("page:" + page_name, html)
  77. return html
  78. def build_html(args):
  79. from jinja2 import Environment, FileSystemLoader
  80. args["len"] = len
  81. jenv = Environment(loader = FileSystemLoader(webnotes.utils.get_base_path()))
  82. template_name = args['template']
  83. if not template_name.endswith(".html"):
  84. template_name = template_name + ".html"
  85. html = jenv.get_template(template_name).render(args)
  86. return html
  87. def get_standard_pages():
  88. return webnotes.get_config()["web"]["pages"].keys()
  89. def prepare_args(page_name):
  90. if page_name == 'index':
  91. page_name = get_home_page()
  92. pages = get_page_settings()
  93. if page_name in pages:
  94. page_info = pages[page_name]
  95. args = webnotes._dict({
  96. 'template': page_info["template"],
  97. 'name': page_name,
  98. })
  99. # additional args
  100. if "args_method" in page_info:
  101. args.update(webnotes.get_method(page_info["args_method"])())
  102. elif "args_doctype" in page_info:
  103. args.obj = webnotes.bean(page_info["args_doctype"]).obj
  104. else:
  105. args = get_doc_fields(page_name)
  106. if not args:
  107. return False
  108. update_template_args(page_name, args)
  109. return args
  110. def get_doc_fields(page_name):
  111. doc_type, doc_name = get_source_doc(page_name)
  112. if not doc_type:
  113. return False
  114. obj = webnotes.get_obj(doc_type, doc_name, with_children=True)
  115. if hasattr(obj, 'prepare_template_args'):
  116. obj.prepare_template_args()
  117. args = obj.doc.fields
  118. args['template'] = get_generators()[doc_type]["template"]
  119. args['obj'] = obj
  120. args['int'] = int
  121. return args
  122. def get_source_doc(page_name):
  123. """get source doc for the given page name"""
  124. for doctype in get_generators():
  125. name = webnotes.conn.sql("""select name from `tab%s` where
  126. page_name=%s and ifnull(%s, 0)=1""" % (doctype, "%s",
  127. get_generators()[doctype]["condition_field"]), page_name)
  128. if name:
  129. return doctype, name[0][0]
  130. return None, None
  131. def clear_cache(page_name=None):
  132. if page_name:
  133. delete_page_cache(page_name)
  134. else:
  135. cache = webnotes.cache()
  136. for p in get_all_pages():
  137. cache.delete_value("page:" + p)
  138. def get_all_pages():
  139. all_pages = get_standard_pages()
  140. for doctype in get_generators():
  141. all_pages += [p[0] for p in webnotes.conn.sql("""select distinct page_name
  142. from `tab%s`""" % doctype) if p[0]]
  143. return all_pages
  144. def delete_page_cache(page_name):
  145. if page_name:
  146. webnotes.cache().delete_value("page:" + page_name)
  147. def get_hex_shade(color, percent):
  148. def p(c):
  149. v = int(c, 16) + int(int('ff', 16) * (float(percent)/100))
  150. if v < 0:
  151. v=0
  152. if v > 255:
  153. v=255
  154. h = hex(v)[2:]
  155. if len(h) < 2:
  156. h = "0" + h
  157. return h
  158. r, g, b = color[0:2], color[2:4], color[4:6]
  159. avg = (float(int(r, 16) + int(g, 16) + int(b, 16)) / 3)
  160. # switch dark and light shades
  161. if avg > 128:
  162. percent = -percent
  163. # stronger diff for darker shades
  164. if percent < 25 and avg < 64:
  165. percent = percent * 2
  166. return p(r) + p(g) + p(b)
  167. def get_standard_pages():
  168. return webnotes.get_config()["web"]["pages"].keys()
  169. def get_generators():
  170. return webnotes.get_config()["web"]["generators"]
  171. def get_page_settings():
  172. return webnotes.get_config()["web"]["pages"]