Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

webutils.py 5.9 KiB

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