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

webutils.py 5.7 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. has_app = True
  92. try:
  93. from startup.webutils import update_template_args, get_home_page
  94. except ImportError:
  95. has_app = False
  96. if page_name == 'index':
  97. if has_app:
  98. page_name = get_home_page()
  99. else:
  100. page_name = "login"
  101. pages = get_page_settings()
  102. if page_name in pages:
  103. page_info = pages[page_name]
  104. args = webnotes._dict({
  105. 'template': page_info["template"],
  106. 'name': page_name,
  107. })
  108. # additional args
  109. if "args_method" in page_info:
  110. args.update(webnotes.get_method(page_info["args_method"])())
  111. elif "args_doctype" in page_info:
  112. bean = webnotes.bean(page_info["args_doctype"])
  113. bean.run_method("onload")
  114. args.obj = bean.make_controller()
  115. else:
  116. args = get_doc_fields(page_name)
  117. if not args:
  118. return False
  119. if has_app:
  120. args = update_template_args(page_name, args)
  121. return args
  122. def get_doc_fields(page_name):
  123. doc_type, doc_name = get_source_doc(page_name)
  124. if not doc_type:
  125. return False
  126. obj = webnotes.get_obj(doc_type, doc_name, with_children=True)
  127. if hasattr(obj, 'prepare_template_args'):
  128. obj.prepare_template_args()
  129. args = obj.doc.fields
  130. args['template'] = get_generators()[doc_type]["template"]
  131. args['obj'] = obj
  132. args['int'] = int
  133. return args
  134. def get_source_doc(page_name):
  135. """get source doc for the given page name"""
  136. for doctype in get_generators():
  137. name = webnotes.conn.sql("""select name from `tab%s` where
  138. page_name=%s and ifnull(%s, 0)=1""" % (doctype, "%s",
  139. get_generators()[doctype]["condition_field"]), page_name)
  140. if name:
  141. return doctype, name[0][0]
  142. return None, None
  143. def clear_cache(page_name=None):
  144. if page_name:
  145. delete_page_cache(page_name)
  146. else:
  147. cache = webnotes.cache()
  148. for p in get_all_pages():
  149. cache.delete_value("page:" + p)
  150. def get_all_pages():
  151. all_pages = get_standard_pages()
  152. for doctype in get_generators():
  153. all_pages += [p[0] for p in webnotes.conn.sql("""select distinct page_name
  154. from `tab%s`""" % doctype) if p[0]]
  155. return all_pages
  156. def delete_page_cache(page_name):
  157. if page_name:
  158. webnotes.cache().delete_value("page:" + page_name)
  159. def get_hex_shade(color, percent):
  160. def p(c):
  161. v = int(c, 16) + int(int('ff', 16) * (float(percent)/100))
  162. if v < 0:
  163. v=0
  164. if v > 255:
  165. v=255
  166. h = hex(v)[2:]
  167. if len(h) < 2:
  168. h = "0" + h
  169. return h
  170. r, g, b = color[0:2], color[2:4], color[4:6]
  171. avg = (float(int(r, 16) + int(g, 16) + int(b, 16)) / 3)
  172. # switch dark and light shades
  173. if avg > 128:
  174. percent = -percent
  175. # stronger diff for darker shades
  176. if percent < 25 and avg < 64:
  177. percent = percent * 2
  178. return p(r) + p(g) + p(b)
  179. def get_standard_pages():
  180. return webnotes.get_config()["web"]["pages"].keys()
  181. def get_generators():
  182. return webnotes.get_config()["web"]["generators"]
  183. def get_page_settings():
  184. return webnotes.get_config()["web"]["pages"]