您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

238 行
5.6 KiB

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