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

1401 行
43 KiB

  1. # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. """
  4. globals attached to frappe module
  5. + some utility functions that should probably be moved
  6. """
  7. from __future__ import unicode_literals, print_function
  8. from six import iteritems, binary_type, text_type, string_types
  9. from werkzeug.local import Local, release_local
  10. import os, sys, importlib, inspect, json
  11. # public
  12. from .exceptions import *
  13. from .utils.jinja import get_jenv, get_template, render_template, get_email_from_template
  14. __version__ = '9.2.3'
  15. __title__ = "Frappe Framework"
  16. local = Local()
  17. class _dict(dict):
  18. """dict like object that exposes keys as attributes"""
  19. def __getattr__(self, key):
  20. ret = self.get(key)
  21. if not ret and key.startswith("__"):
  22. raise AttributeError()
  23. return ret
  24. def __setattr__(self, key, value):
  25. self[key] = value
  26. def __getstate__(self):
  27. return self
  28. def __setstate__(self, d):
  29. self.update(d)
  30. def update(self, d):
  31. """update and return self -- the missing dict feature in python"""
  32. super(_dict, self).update(d)
  33. return self
  34. def copy(self):
  35. return _dict(dict(self).copy())
  36. def _(msg, lang=None):
  37. """Returns translated string in current lang, if exists."""
  38. from frappe.translate import get_full_dict
  39. if not hasattr(local, 'lang'):
  40. local.lang = lang or 'en'
  41. if not lang:
  42. lang = local.lang
  43. # msg should always be unicode
  44. msg = as_unicode(msg).strip()
  45. # return lang_full_dict according to lang passed parameter
  46. return get_full_dict(lang).get(msg) or msg
  47. def as_unicode(text, encoding='utf-8'):
  48. '''Convert to unicode if required'''
  49. if isinstance(text, text_type):
  50. return text
  51. elif text==None:
  52. return ''
  53. elif isinstance(text, binary_type):
  54. return text_type(text, encoding)
  55. else:
  56. return text_type(text)
  57. def get_lang_dict(fortype, name=None):
  58. """Returns the translated language dict for the given type and name.
  59. :param fortype: must be one of `doctype`, `page`, `report`, `include`, `jsfile`, `boot`
  60. :param name: name of the document for which assets are to be returned."""
  61. from frappe.translate import get_dict
  62. return get_dict(fortype, name)
  63. def set_user_lang(user, user_language=None):
  64. """Guess and set user language for the session. `frappe.local.lang`"""
  65. from frappe.translate import get_user_lang
  66. local.lang = get_user_lang(user)
  67. # local-globals
  68. db = local("db")
  69. conf = local("conf")
  70. form = form_dict = local("form_dict")
  71. request = local("request")
  72. response = local("response")
  73. session = local("session")
  74. user = local("user")
  75. flags = local("flags")
  76. error_log = local("error_log")
  77. debug_log = local("debug_log")
  78. message_log = local("message_log")
  79. lang = local("lang")
  80. def init(site, sites_path=None, new_site=False):
  81. """Initialize frappe for the current site. Reset thread locals `frappe.local`"""
  82. if getattr(local, "initialised", None):
  83. return
  84. if not sites_path:
  85. sites_path = '.'
  86. local.error_log = []
  87. local.message_log = []
  88. local.debug_log = []
  89. local.realtime_log = []
  90. local.flags = _dict({
  91. "ran_schedulers": [],
  92. "currently_saving": [],
  93. "redirect_location": "",
  94. "in_install_db": False,
  95. "in_install_app": False,
  96. "in_import": False,
  97. "in_test": False,
  98. "mute_messages": False,
  99. "ignore_links": False,
  100. "mute_emails": False,
  101. "has_dataurl": False,
  102. "new_site": new_site
  103. })
  104. local.rollback_observers = []
  105. local.test_objects = {}
  106. local.site = site
  107. local.sites_path = sites_path
  108. local.site_path = os.path.join(sites_path, site)
  109. local.request_ip = None
  110. local.response = _dict({"docs":[]})
  111. local.task_id = None
  112. local.conf = _dict(get_site_config())
  113. local.lang = local.conf.lang or "en"
  114. local.lang_full_dict = None
  115. local.module_app = None
  116. local.app_modules = None
  117. local.system_settings = _dict()
  118. local.user = None
  119. local.user_perms = None
  120. local.session = None
  121. local.role_permissions = {}
  122. local.valid_columns = {}
  123. local.new_doc_templates = {}
  124. local.link_count = {}
  125. local.jenv = None
  126. local.jloader =None
  127. local.cache = {}
  128. local.meta_cache = {}
  129. local.form_dict = _dict()
  130. local.session = _dict()
  131. setup_module_map()
  132. local.initialised = True
  133. def connect(site=None, db_name=None):
  134. """Connect to site database instance.
  135. :param site: If site is given, calls `frappe.init`.
  136. :param db_name: Optional. Will use from `site_config.json`."""
  137. from frappe.database import Database
  138. if site:
  139. init(site)
  140. local.db = Database(user=db_name or local.conf.db_name)
  141. set_user("Administrator")
  142. def get_site_config(sites_path=None, site_path=None):
  143. """Returns `site_config.json` combined with `sites/common_site_config.json`.
  144. `site_config` is a set of site wide settings like database name, password, email etc."""
  145. config = {}
  146. sites_path = sites_path or getattr(local, "sites_path", None)
  147. site_path = site_path or getattr(local, "site_path", None)
  148. if sites_path:
  149. common_site_config = os.path.join(sites_path, "common_site_config.json")
  150. if os.path.exists(common_site_config):
  151. config.update(get_file_json(common_site_config))
  152. if site_path:
  153. site_config = os.path.join(site_path, "site_config.json")
  154. if os.path.exists(site_config):
  155. config.update(get_file_json(site_config))
  156. elif local.site and not local.flags.new_site:
  157. print("{0} does not exist".format(local.site))
  158. sys.exit(1)
  159. #raise IncorrectSitePath, "{0} does not exist".format(site_config)
  160. return _dict(config)
  161. def get_conf(site=None):
  162. if hasattr(local, 'conf'):
  163. return local.conf
  164. else:
  165. # if no site, get from common_site_config.json
  166. with init_site(site):
  167. return local.conf
  168. class init_site:
  169. def __init__(self, site=None):
  170. '''If site==None, initialize it for empty site ('') to load common_site_config.json'''
  171. self.site = site or ''
  172. def __enter__(self):
  173. init(self.site)
  174. return local
  175. def __exit__(self, type, value, traceback):
  176. destroy()
  177. def destroy():
  178. """Closes connection and releases werkzeug local."""
  179. if db:
  180. db.close()
  181. release_local(local)
  182. # memcache
  183. redis_server = None
  184. def cache():
  185. """Returns memcache connection."""
  186. global redis_server
  187. if not redis_server:
  188. from frappe.utils.redis_wrapper import RedisWrapper
  189. redis_server = RedisWrapper.from_url(conf.get('redis_cache')
  190. or "redis://localhost:11311")
  191. return redis_server
  192. def get_traceback():
  193. """Returns error traceback."""
  194. from frappe.utils import get_traceback
  195. return get_traceback()
  196. def errprint(msg):
  197. """Log error. This is sent back as `exc` in response.
  198. :param msg: Message."""
  199. msg = as_unicode(msg)
  200. if not request or (not "cmd" in local.form_dict) or conf.developer_mode:
  201. print(msg.encode('utf-8'))
  202. error_log.append(msg)
  203. def log(msg):
  204. """Add to `debug_log`.
  205. :param msg: Message."""
  206. if not request:
  207. if conf.get("logging") or False:
  208. print(repr(msg))
  209. debug_log.append(as_unicode(msg))
  210. def msgprint(msg, title=None, raise_exception=0, as_table=False, indicator=None, alert=False):
  211. """Print a message to the user (via HTTP response).
  212. Messages are sent in the `__server_messages` property in the
  213. response JSON and shown in a pop-up / modal.
  214. :param msg: Message.
  215. :param title: [optional] Message title.
  216. :param raise_exception: [optional] Raise given exception and show message.
  217. :param as_table: [optional] If `msg` is a list of lists, render as HTML table.
  218. """
  219. from frappe.utils import encode
  220. out = _dict(message=msg)
  221. def _raise_exception():
  222. if raise_exception:
  223. if flags.rollback_on_exception:
  224. db.rollback()
  225. import inspect
  226. if inspect.isclass(raise_exception) and issubclass(raise_exception, Exception):
  227. raise raise_exception(encode(msg))
  228. else:
  229. raise ValidationError(encode(msg))
  230. if flags.mute_messages:
  231. _raise_exception()
  232. return
  233. if as_table and type(msg) in (list, tuple):
  234. out.msg = '<table border="1px" style="border-collapse: collapse" cellpadding="2px">' + ''.join(['<tr>'+''.join(['<td>%s</td>' % c for c in r])+'</tr>' for r in msg]) + '</table>'
  235. if flags.print_messages and out.msg:
  236. print("Message: " + repr(out.msg).encode("utf-8"))
  237. if title:
  238. out.title = title
  239. if not indicator and raise_exception:
  240. indicator = 'red'
  241. if indicator:
  242. out.indicator = indicator
  243. if alert:
  244. out.alert = 1
  245. message_log.append(json.dumps(out))
  246. _raise_exception()
  247. def clear_messages():
  248. local.message_log = []
  249. def throw(msg, exc=ValidationError, title=None):
  250. """Throw execption and show message (`msgprint`).
  251. :param msg: Message.
  252. :param exc: Exception class. Default `frappe.ValidationError`"""
  253. msgprint(msg, raise_exception=exc, title=title, indicator='red')
  254. def emit_js(js, user=False, **kwargs):
  255. from frappe.async import publish_realtime
  256. if user == False:
  257. user = session.user
  258. publish_realtime('eval_js', js, user=user, **kwargs)
  259. def create_folder(path, with_init=False):
  260. """Create a folder in the given path and add an `__init__.py` file (optional).
  261. :param path: Folder path.
  262. :param with_init: Create `__init__.py` in the new folder."""
  263. from frappe.utils import touch_file
  264. if not os.path.exists(path):
  265. os.makedirs(path)
  266. if with_init:
  267. touch_file(os.path.join(path, "__init__.py"))
  268. def set_user(username):
  269. """Set current user.
  270. :param username: **User** name to set as current user."""
  271. local.session.user = username
  272. local.session.sid = username
  273. local.cache = {}
  274. local.form_dict = _dict()
  275. local.jenv = None
  276. local.session.data = _dict()
  277. local.role_permissions = {}
  278. local.new_doc_templates = {}
  279. local.user_perms = None
  280. def get_user():
  281. from frappe.utils.user import UserPermissions
  282. if not local.user_perms:
  283. local.user_perms = UserPermissions(local.session.user)
  284. return local.user_perms
  285. def get_roles(username=None):
  286. """Returns roles of current user."""
  287. if not local.session:
  288. return ["Guest"]
  289. if username:
  290. import frappe.permissions
  291. return frappe.permissions.get_roles(username)
  292. else:
  293. return get_user().get_roles()
  294. def get_request_header(key, default=None):
  295. """Return HTTP request header.
  296. :param key: HTTP header key.
  297. :param default: Default value."""
  298. return request.headers.get(key, default)
  299. def sendmail(recipients=[], sender="", subject="No Subject", message="No Message",
  300. as_markdown=False, delayed=True, reference_doctype=None, reference_name=None,
  301. unsubscribe_method=None, unsubscribe_params=None, unsubscribe_message=None,
  302. attachments=None, content=None, doctype=None, name=None, reply_to=None,
  303. cc=[], message_id=None, in_reply_to=None, send_after=None, expose_recipients=None,
  304. send_priority=1, communication=None, retry=1, now=None, read_receipt=None, is_notification=False,
  305. inline_images=None, template=None, args=None, header=None):
  306. """Send email using user's default **Email Account** or global default **Email Account**.
  307. :param recipients: List of recipients.
  308. :param sender: Email sender. Default is current user.
  309. :param subject: Email Subject.
  310. :param message: (or `content`) Email Content.
  311. :param as_markdown: Convert content markdown to HTML.
  312. :param delayed: Send via scheduled email sender **Email Queue**. Don't send immediately. Default is true
  313. :param send_priority: Priority for Email Queue, default 1.
  314. :param reference_doctype: (or `doctype`) Append as communication to this DocType.
  315. :param reference_name: (or `name`) Append as communication to this document name.
  316. :param unsubscribe_method: Unsubscribe url with options email, doctype, name. e.g. `/api/method/unsubscribe`
  317. :param unsubscribe_params: Unsubscribe paramaters to be loaded on the unsubscribe_method [optional] (dict).
  318. :param attachments: List of attachments.
  319. :param reply_to: Reply-To Email Address.
  320. :param message_id: Used for threading. If a reply is received to this email, Message-Id is sent back as In-Reply-To in received email.
  321. :param in_reply_to: Used to send the Message-Id of a received email back as In-Reply-To.
  322. :param send_after: Send after the given datetime.
  323. :param expose_recipients: Display all recipients in the footer message - "This email was sent to"
  324. :param communication: Communication link to be set in Email Queue record
  325. :param inline_images: List of inline images as {"filename", "filecontent"}. All src properties will be replaced with random Content-Id
  326. :param template: Name of html template from templates/emails folder
  327. :param args: Arguments for rendering the template
  328. :param header: Append header in email
  329. """
  330. text_content = None
  331. if template:
  332. message, text_content = get_email_from_template(template, args)
  333. message = content or message
  334. if as_markdown:
  335. from markdown2 import markdown
  336. message = markdown(message)
  337. if not delayed:
  338. now = True
  339. from frappe.email import queue
  340. queue.send(recipients=recipients, sender=sender,
  341. subject=subject, message=message, text_content=text_content,
  342. reference_doctype = doctype or reference_doctype, reference_name = name or reference_name,
  343. unsubscribe_method=unsubscribe_method, unsubscribe_params=unsubscribe_params, unsubscribe_message=unsubscribe_message,
  344. attachments=attachments, reply_to=reply_to, cc=cc, message_id=message_id, in_reply_to=in_reply_to,
  345. send_after=send_after, expose_recipients=expose_recipients, send_priority=send_priority,
  346. communication=communication, now=now, read_receipt=read_receipt, is_notification=is_notification,
  347. inline_images=inline_images, header=header)
  348. whitelisted = []
  349. guest_methods = []
  350. xss_safe_methods = []
  351. def whitelist(allow_guest=False, xss_safe=False):
  352. """
  353. Decorator for whitelisting a function and making it accessible via HTTP.
  354. Standard request will be `/api/method/[path.to.method]`
  355. :param allow_guest: Allow non logged-in user to access this method.
  356. Use as:
  357. @frappe.whitelist()
  358. def myfunc(param1, param2):
  359. pass
  360. """
  361. def innerfn(fn):
  362. global whitelisted, guest_methods, xss_safe_methods
  363. whitelisted.append(fn)
  364. if allow_guest:
  365. guest_methods.append(fn)
  366. if xss_safe:
  367. xss_safe_methods.append(fn)
  368. return fn
  369. return innerfn
  370. def only_for(roles):
  371. """Raise `frappe.PermissionError` if the user does not have any of the given **Roles**.
  372. :param roles: List of roles to check."""
  373. if local.flags.in_test:
  374. return
  375. if not isinstance(roles, (tuple, list)):
  376. roles = (roles,)
  377. roles = set(roles)
  378. myroles = set(get_roles())
  379. if not roles.intersection(myroles):
  380. raise PermissionError
  381. def get_domain_data(module):
  382. try:
  383. domain_data = get_hooks('domains')
  384. if module in domain_data:
  385. return _dict(get_attr(get_hooks('domains')[module][0] + '.data'))
  386. else:
  387. return _dict()
  388. except ImportError:
  389. if local.flags.in_test:
  390. return _dict()
  391. else:
  392. raise
  393. def clear_cache(user=None, doctype=None):
  394. """Clear **User**, **DocType** or global cache.
  395. :param user: If user is given, only user cache is cleared.
  396. :param doctype: If doctype is given, only DocType cache is cleared."""
  397. import frappe.sessions
  398. if doctype:
  399. import frappe.model.meta
  400. frappe.model.meta.clear_cache(doctype)
  401. reset_metadata_version()
  402. elif user:
  403. frappe.sessions.clear_cache(user)
  404. else: # everything
  405. from frappe import translate
  406. frappe.sessions.clear_cache()
  407. translate.clear_cache()
  408. reset_metadata_version()
  409. local.cache = {}
  410. local.new_doc_templates = {}
  411. for fn in get_hooks("clear_cache"):
  412. get_attr(fn)()
  413. local.role_permissions = {}
  414. def has_permission(doctype=None, ptype="read", doc=None, user=None, verbose=False, throw=False):
  415. """Raises `frappe.PermissionError` if not permitted.
  416. :param doctype: DocType for which permission is to be check.
  417. :param ptype: Permission type (`read`, `write`, `create`, `submit`, `cancel`, `amend`). Default: `read`.
  418. :param doc: [optional] Checks User permissions for given doc.
  419. :param user: [optional] Check for given user. Default: current user."""
  420. if not doctype and doc:
  421. doctype = doc.doctype
  422. import frappe.permissions
  423. out = frappe.permissions.has_permission(doctype, ptype, doc=doc, verbose=verbose, user=user)
  424. if throw and not out:
  425. if doc:
  426. frappe.throw(_("No permission for {0}").format(doc.doctype + " " + doc.name))
  427. else:
  428. frappe.throw(_("No permission for {0}").format(doctype))
  429. return out
  430. def has_website_permission(doc=None, ptype='read', user=None, verbose=False, doctype=None):
  431. """Raises `frappe.PermissionError` if not permitted.
  432. :param doctype: DocType for which permission is to be check.
  433. :param ptype: Permission type (`read`, `write`, `create`, `submit`, `cancel`, `amend`). Default: `read`.
  434. :param doc: Checks User permissions for given doc.
  435. :param user: [optional] Check for given user. Default: current user."""
  436. if not user:
  437. user = session.user
  438. if doc:
  439. if isinstance(doc, string_types):
  440. doc = get_doc(doctype, doc)
  441. doctype = doc.doctype
  442. if doc.flags.ignore_permissions:
  443. return True
  444. # check permission in controller
  445. if hasattr(doc, 'has_website_permission'):
  446. return doc.has_website_permission(ptype, verbose=verbose)
  447. hooks = (get_hooks("has_website_permission") or {}).get(doctype, [])
  448. if hooks:
  449. for method in hooks:
  450. result = call(method, doc=doc, ptype=ptype, user=user, verbose=verbose)
  451. # if even a single permission check is Falsy
  452. if not result:
  453. return False
  454. # else it is Truthy
  455. return True
  456. else:
  457. return False
  458. def is_table(doctype):
  459. """Returns True if `istable` property (indicating child Table) is set for given DocType."""
  460. def get_tables():
  461. return db.sql_list("select name from tabDocType where istable=1")
  462. tables = cache().get_value("is_table", get_tables)
  463. return doctype in tables
  464. def get_precision(doctype, fieldname, currency=None, doc=None):
  465. """Get precision for a given field"""
  466. from frappe.model.meta import get_field_precision
  467. return get_field_precision(get_meta(doctype).get_field(fieldname), doc, currency)
  468. def generate_hash(txt=None, length=None):
  469. """Generates random hash for given text + current timestamp + random string."""
  470. import hashlib, time
  471. from .utils import random_string
  472. digest = hashlib.sha224(((txt or "") + repr(time.time()) + repr(random_string(8))).encode()).hexdigest()
  473. if length:
  474. digest = digest[:length]
  475. return digest
  476. def reset_metadata_version():
  477. """Reset `metadata_version` (Client (Javascript) build ID) hash."""
  478. v = generate_hash()
  479. cache().set_value("metadata_version", v)
  480. return v
  481. def new_doc(doctype, parent_doc=None, parentfield=None, as_dict=False):
  482. """Returns a new document of the given DocType with defaults set.
  483. :param doctype: DocType of the new document.
  484. :param parent_doc: [optional] add to parent document.
  485. :param parentfield: [optional] add against this `parentfield`."""
  486. from frappe.model.create_new import get_new_doc
  487. return get_new_doc(doctype, parent_doc, parentfield, as_dict=as_dict)
  488. def set_value(doctype, docname, fieldname, value=None):
  489. """Set document value. Calls `frappe.client.set_value`"""
  490. import frappe.client
  491. return frappe.client.set_value(doctype, docname, fieldname, value)
  492. def get_doc(*args, **kwargs):
  493. """Return a `frappe.model.document.Document` object of the given type and name.
  494. :param arg1: DocType name as string **or** document JSON.
  495. :param arg2: [optional] Document name as string.
  496. Examples:
  497. # insert a new document
  498. todo = frappe.get_doc({"doctype":"ToDo", "description": "test"})
  499. tood.insert()
  500. # open an existing document
  501. todo = frappe.get_doc("ToDo", "TD0001")
  502. """
  503. import frappe.model.document
  504. return frappe.model.document.get_doc(*args, **kwargs)
  505. def get_last_doc(doctype):
  506. """Get last created document of this type."""
  507. d = get_all(doctype, ["name"], order_by="creation desc", limit_page_length=1)
  508. if d:
  509. return get_doc(doctype, d[0].name)
  510. else:
  511. raise DoesNotExistError
  512. def get_single(doctype):
  513. """Return a `frappe.model.document.Document` object of the given Single doctype."""
  514. return get_doc(doctype, doctype)
  515. def get_meta(doctype, cached=True):
  516. """Get `frappe.model.meta.Meta` instance of given doctype name."""
  517. import frappe.model.meta
  518. return frappe.model.meta.get_meta(doctype, cached=cached)
  519. def get_meta_module(doctype):
  520. import frappe.modules
  521. return frappe.modules.load_doctype_module(doctype)
  522. def delete_doc(doctype=None, name=None, force=0, ignore_doctypes=None, for_reload=False,
  523. ignore_permissions=False, flags=None, ignore_on_trash=False, ignore_missing=True):
  524. """Delete a document. Calls `frappe.model.delete_doc.delete_doc`.
  525. :param doctype: DocType of document to be delete.
  526. :param name: Name of document to be delete.
  527. :param force: Allow even if document is linked. Warning: This may lead to data integrity errors.
  528. :param ignore_doctypes: Ignore if child table is one of these.
  529. :param for_reload: Call `before_reload` trigger before deleting.
  530. :param ignore_permissions: Ignore user permissions."""
  531. import frappe.model.delete_doc
  532. frappe.model.delete_doc.delete_doc(doctype, name, force, ignore_doctypes, for_reload,
  533. ignore_permissions, flags, ignore_on_trash, ignore_missing)
  534. def delete_doc_if_exists(doctype, name, force=0):
  535. """Delete document if exists."""
  536. if db.exists(doctype, name):
  537. delete_doc(doctype, name, force=force)
  538. def reload_doctype(doctype, force=False, reset_permissions=False):
  539. """Reload DocType from model (`[module]/[doctype]/[name]/[name].json`) files."""
  540. reload_doc(scrub(db.get_value("DocType", doctype, "module")), "doctype", scrub(doctype),
  541. force=force, reset_permissions=reset_permissions)
  542. def reload_doc(module, dt=None, dn=None, force=False, reset_permissions=False):
  543. """Reload Document from model (`[module]/[doctype]/[name]/[name].json`) files.
  544. :param module: Module name.
  545. :param dt: DocType name.
  546. :param dn: Document name.
  547. :param force: Reload even if `modified` timestamp matches.
  548. """
  549. import frappe.modules
  550. return frappe.modules.reload_doc(module, dt, dn, force=force, reset_permissions=reset_permissions)
  551. def rename_doc(*args, **kwargs):
  552. """Rename a document. Calls `frappe.model.rename_doc.rename_doc`"""
  553. from frappe.model.rename_doc import rename_doc
  554. return rename_doc(*args, **kwargs)
  555. def get_module(modulename):
  556. """Returns a module object for given Python module name using `importlib.import_module`."""
  557. return importlib.import_module(modulename)
  558. def scrub(txt):
  559. """Returns sluggified string. e.g. `Sales Order` becomes `sales_order`."""
  560. return txt.replace(' ','_').replace('-', '_').lower()
  561. def unscrub(txt):
  562. """Returns titlified string. e.g. `sales_order` becomes `Sales Order`."""
  563. return txt.replace('_',' ').replace('-', ' ').title()
  564. def get_module_path(module, *joins):
  565. """Get the path of the given module name.
  566. :param module: Module name.
  567. :param *joins: Join additional path elements using `os.path.join`."""
  568. module = scrub(module)
  569. return get_pymodule_path(local.module_app[module] + "." + module, *joins)
  570. def get_app_path(app_name, *joins):
  571. """Return path of given app.
  572. :param app: App name.
  573. :param *joins: Join additional path elements using `os.path.join`."""
  574. return get_pymodule_path(app_name, *joins)
  575. def get_site_path(*joins):
  576. """Return path of current site.
  577. :param *joins: Join additional path elements using `os.path.join`."""
  578. return os.path.join(local.site_path, *joins)
  579. def get_pymodule_path(modulename, *joins):
  580. """Return path of given Python module name.
  581. :param modulename: Python module name.
  582. :param *joins: Join additional path elements using `os.path.join`."""
  583. if not "public" in joins:
  584. joins = [scrub(part) for part in joins]
  585. return os.path.join(os.path.dirname(get_module(scrub(modulename)).__file__), *joins)
  586. def get_module_list(app_name):
  587. """Get list of modules for given all via `app/modules.txt`."""
  588. return get_file_items(os.path.join(os.path.dirname(get_module(app_name).__file__), "modules.txt"))
  589. def get_all_apps(with_internal_apps=True, sites_path=None):
  590. """Get list of all apps via `sites/apps.txt`."""
  591. if not sites_path:
  592. sites_path = local.sites_path
  593. apps = get_file_items(os.path.join(sites_path, "apps.txt"), raise_not_found=True)
  594. if with_internal_apps:
  595. for app in get_file_items(os.path.join(local.site_path, "apps.txt")):
  596. if app not in apps:
  597. apps.append(app)
  598. if "frappe" in apps:
  599. apps.remove("frappe")
  600. apps.insert(0, 'frappe')
  601. return apps
  602. def get_installed_apps(sort=False, frappe_last=False):
  603. """Get list of installed apps in current site."""
  604. if getattr(flags, "in_install_db", True):
  605. return []
  606. if not db:
  607. connect()
  608. installed = json.loads(db.get_global("installed_apps") or "[]")
  609. if sort:
  610. installed = [app for app in get_all_apps(True) if app in installed]
  611. if frappe_last:
  612. if 'frappe' in installed:
  613. installed.remove('frappe')
  614. installed.append('frappe')
  615. return installed
  616. def get_doc_hooks():
  617. '''Returns hooked methods for given doc. It will expand the dict tuple if required.'''
  618. if not hasattr(local, 'doc_events_hooks'):
  619. hooks = get_hooks('doc_events', {})
  620. out = {}
  621. for key, value in iteritems(hooks):
  622. if isinstance(key, tuple):
  623. for doctype in key:
  624. append_hook(out, doctype, value)
  625. else:
  626. append_hook(out, key, value)
  627. local.doc_events_hooks = out
  628. return local.doc_events_hooks
  629. def get_hooks(hook=None, default=None, app_name=None):
  630. """Get hooks via `app/hooks.py`
  631. :param hook: Name of the hook. Will gather all hooks for this name and return as a list.
  632. :param default: Default if no hook found.
  633. :param app_name: Filter by app."""
  634. def load_app_hooks(app_name=None):
  635. hooks = {}
  636. for app in [app_name] if app_name else get_installed_apps(sort=True):
  637. app = "frappe" if app=="webnotes" else app
  638. try:
  639. app_hooks = get_module(app + ".hooks")
  640. except ImportError:
  641. if local.flags.in_install_app:
  642. # if app is not installed while restoring
  643. # ignore it
  644. pass
  645. print('Could not find app "{0}"'.format(app_name))
  646. if not request:
  647. sys.exit(1)
  648. raise
  649. for key in dir(app_hooks):
  650. if not key.startswith("_"):
  651. append_hook(hooks, key, getattr(app_hooks, key))
  652. return hooks
  653. if app_name:
  654. hooks = _dict(load_app_hooks(app_name))
  655. else:
  656. hooks = _dict(cache().get_value("app_hooks", load_app_hooks))
  657. if hook:
  658. return hooks.get(hook) or (default if default is not None else [])
  659. else:
  660. return hooks
  661. def append_hook(target, key, value):
  662. '''appends a hook to the the target dict.
  663. If the hook key, exists, it will make it a key.
  664. If the hook value is a dict, like doc_events, it will
  665. listify the values against the key.
  666. '''
  667. if isinstance(value, dict):
  668. # dict? make a list of values against each key
  669. target.setdefault(key, {})
  670. for inkey in value:
  671. append_hook(target[key], inkey, value[inkey])
  672. else:
  673. # make a list
  674. target.setdefault(key, [])
  675. if not isinstance(value, list):
  676. value = [value]
  677. target[key].extend(value)
  678. def setup_module_map():
  679. """Rebuild map of all modules (internal)."""
  680. _cache = cache()
  681. if conf.db_name:
  682. local.app_modules = _cache.get_value("app_modules")
  683. local.module_app = _cache.get_value("module_app")
  684. if not (local.app_modules and local.module_app):
  685. local.module_app, local.app_modules = {}, {}
  686. for app in get_all_apps(True):
  687. if app=="webnotes": app="frappe"
  688. local.app_modules.setdefault(app, [])
  689. for module in get_module_list(app):
  690. module = scrub(module)
  691. local.module_app[module] = app
  692. local.app_modules[app].append(module)
  693. if conf.db_name:
  694. _cache.set_value("app_modules", local.app_modules)
  695. _cache.set_value("module_app", local.module_app)
  696. def get_file_items(path, raise_not_found=False, ignore_empty_lines=True):
  697. """Returns items from text file as a list. Ignores empty lines."""
  698. import frappe.utils
  699. content = read_file(path, raise_not_found=raise_not_found)
  700. if content:
  701. content = frappe.utils.strip(content)
  702. return [p.strip() for p in content.splitlines() if (not ignore_empty_lines) or (p.strip() and not p.startswith("#"))]
  703. else:
  704. return []
  705. def get_file_json(path):
  706. """Read a file and return parsed JSON object."""
  707. with open(path, 'r') as f:
  708. return json.load(f)
  709. def read_file(path, raise_not_found=False):
  710. """Open a file and return its content as Unicode."""
  711. if isinstance(path, text_type):
  712. path = path.encode("utf-8")
  713. if os.path.exists(path):
  714. with open(path, "r") as f:
  715. return as_unicode(f.read())
  716. elif raise_not_found:
  717. raise IOError("{} Not Found".format(path))
  718. else:
  719. return None
  720. def get_attr(method_string):
  721. """Get python method object from its name."""
  722. app_name = method_string.split(".")[0]
  723. if not local.flags.in_install and app_name not in get_installed_apps():
  724. throw(_("App {0} is not installed").format(app_name), AppNotInstalledError)
  725. modulename = '.'.join(method_string.split('.')[:-1])
  726. methodname = method_string.split('.')[-1]
  727. return getattr(get_module(modulename), methodname)
  728. def call(fn, *args, **kwargs):
  729. """Call a function and match arguments."""
  730. if isinstance(fn, string_types):
  731. fn = get_attr(fn)
  732. if hasattr(fn, 'fnargs'):
  733. fnargs = fn.fnargs
  734. else:
  735. fnargs, varargs, varkw, defaults = inspect.getargspec(fn)
  736. newargs = {}
  737. for a in kwargs:
  738. if (a in fnargs) or varkw:
  739. newargs[a] = kwargs.get(a)
  740. if "flags" in newargs:
  741. del newargs["flags"]
  742. return fn(*args, **newargs)
  743. def make_property_setter(args, ignore_validate=False, validate_fields_for_doctype=True):
  744. """Create a new **Property Setter** (for overriding DocType and DocField properties).
  745. If doctype is not specified, it will create a property setter for all fields with the
  746. given fieldname"""
  747. args = _dict(args)
  748. if not args.doctype_or_field:
  749. args.doctype_or_field = 'DocField'
  750. if not args.property_type:
  751. args.property_type = db.get_value('DocField',
  752. {'parent': 'DocField', 'fieldname': args.property}, 'fieldtype') or 'Data'
  753. if not args.doctype:
  754. doctype_list = db.sql_list('select distinct parent from tabDocField where fieldname=%s', args.fieldname)
  755. else:
  756. doctype_list = [args.doctype]
  757. for doctype in doctype_list:
  758. if not args.property_type:
  759. args.property_type = db.get_value('DocField',
  760. {'parent': doctype, 'fieldname': args.fieldname}, 'fieldtype') or 'Data'
  761. ps = get_doc({
  762. 'doctype': "Property Setter",
  763. 'doctype_or_field': args.doctype_or_field,
  764. 'doc_type': doctype,
  765. 'field_name': args.fieldname,
  766. 'property': args.property,
  767. 'value': args.value,
  768. 'property_type': args.property_type or "Data",
  769. '__islocal': 1
  770. })
  771. ps.flags.ignore_validate = ignore_validate
  772. ps.flags.validate_fields_for_doctype = validate_fields_for_doctype
  773. ps.validate_fieldtype_change()
  774. ps.insert()
  775. def import_doc(path, ignore_links=False, ignore_insert=False, insert=False):
  776. """Import a file using Data Import Tool."""
  777. from frappe.core.page.data_import_tool import data_import_tool
  778. data_import_tool.import_doc(path, ignore_links=ignore_links, ignore_insert=ignore_insert, insert=insert)
  779. def copy_doc(doc, ignore_no_copy=True):
  780. """ No_copy fields also get copied."""
  781. import copy
  782. def remove_no_copy_fields(d):
  783. for df in d.meta.get("fields", {"no_copy": 1}):
  784. if hasattr(d, df.fieldname):
  785. d.set(df.fieldname, None)
  786. fields_to_clear = ['name', 'owner', 'creation', 'modified', 'modified_by']
  787. if not local.flags.in_test:
  788. fields_to_clear.append("docstatus")
  789. if not isinstance(doc, dict):
  790. d = doc.as_dict()
  791. else:
  792. d = doc
  793. newdoc = get_doc(copy.deepcopy(d))
  794. newdoc.set("__islocal", 1)
  795. for fieldname in (fields_to_clear + ['amended_from', 'amendment_date']):
  796. newdoc.set(fieldname, None)
  797. if not ignore_no_copy:
  798. remove_no_copy_fields(newdoc)
  799. for i, d in enumerate(newdoc.get_all_children()):
  800. d.set("__islocal", 1)
  801. for fieldname in fields_to_clear:
  802. d.set(fieldname, None)
  803. if not ignore_no_copy:
  804. remove_no_copy_fields(d)
  805. return newdoc
  806. def compare(val1, condition, val2):
  807. """Compare two values using `frappe.utils.compare`
  808. `condition` could be:
  809. - "^"
  810. - "in"
  811. - "not in"
  812. - "="
  813. - "!="
  814. - ">"
  815. - "<"
  816. - ">="
  817. - "<="
  818. - "not None"
  819. - "None"
  820. """
  821. import frappe.utils
  822. return frappe.utils.compare(val1, condition, val2)
  823. def respond_as_web_page(title, html, success=None, http_status_code=None,
  824. context=None, indicator_color=None, primary_action='/', primary_label = None, fullpage=False,
  825. width=None):
  826. """Send response as a web page with a message rather than JSON. Used to show permission errors etc.
  827. :param title: Page title and heading.
  828. :param message: Message to be shown.
  829. :param success: Alert message.
  830. :param http_status_code: HTTP status code
  831. :param context: web template context
  832. :param indicator_color: color of indicator in title
  833. :param primary_action: route on primary button (default is `/`)
  834. :param primary_label: label on primary button (defaut is "Home")
  835. :param fullpage: hide header / footer
  836. :param width: Width of message in pixels
  837. """
  838. local.message_title = title
  839. local.message = html
  840. local.response['type'] = 'page'
  841. local.response['route'] = 'message'
  842. if http_status_code:
  843. local.response['http_status_code'] = http_status_code
  844. if not context:
  845. context = {}
  846. if not indicator_color:
  847. if success:
  848. indicator_color = 'green'
  849. elif http_status_code and http_status_code > 300:
  850. indicator_color = 'red'
  851. else:
  852. indicator_color = 'blue'
  853. context['indicator_color'] = indicator_color
  854. context['primary_label'] = primary_label
  855. context['primary_action'] = primary_action
  856. context['error_code'] = http_status_code
  857. context['fullpage'] = fullpage
  858. if width:
  859. context['card_width'] = width
  860. local.response['context'] = context
  861. def redirect_to_message(title, html, http_status_code=None, context=None, indicator_color=None):
  862. """Redirects to /message?id=random
  863. Similar to respond_as_web_page, but used to 'redirect' and show message pages like success, failure, etc. with a detailed message
  864. :param title: Page title and heading.
  865. :param message: Message to be shown.
  866. :param http_status_code: HTTP status code.
  867. Example Usage:
  868. frappe.redirect_to_message(_('Thank you'), "<div><p>You will receive an email at test@example.com</p></div>")
  869. """
  870. message_id = generate_hash(length=8)
  871. message = {
  872. 'context': context or {},
  873. 'http_status_code': http_status_code or 200
  874. }
  875. message['context'].update({
  876. 'header': title,
  877. 'title': title,
  878. 'message': html
  879. })
  880. if indicator_color:
  881. message['context'].update({
  882. "indicator_color": indicator_color
  883. })
  884. cache().set_value("message_id:{0}".format(message_id), message, expires_in_sec=60)
  885. location = '/message?id={0}'.format(message_id)
  886. if not getattr(local, 'is_ajax', False):
  887. local.response["type"] = "redirect"
  888. local.response["location"] = location
  889. else:
  890. return location
  891. def build_match_conditions(doctype, as_condition=True):
  892. """Return match (User permissions) for given doctype as list or SQL."""
  893. import frappe.desk.reportview
  894. return frappe.desk.reportview.build_match_conditions(doctype, as_condition)
  895. def get_list(doctype, *args, **kwargs):
  896. """List database query via `frappe.model.db_query`. Will also check for permissions.
  897. :param doctype: DocType on which query is to be made.
  898. :param fields: List of fields or `*`.
  899. :param filters: List of filters (see example).
  900. :param order_by: Order By e.g. `modified desc`.
  901. :param limit_page_start: Start results at record #. Default 0.
  902. :param limit_page_length: No of records in the page. Default 20.
  903. Example usage:
  904. # simple dict filter
  905. frappe.get_list("ToDo", fields=["name", "description"], filters = {"owner":"test@example.com"})
  906. # filter as a list of lists
  907. frappe.get_list("ToDo", fields="*", filters = [["modified", ">", "2014-01-01"]])
  908. # filter as a list of dicts
  909. frappe.get_list("ToDo", fields="*", filters = {"description": ("like", "test%")})
  910. """
  911. import frappe.model.db_query
  912. return frappe.model.db_query.DatabaseQuery(doctype).execute(None, *args, **kwargs)
  913. def get_all(doctype, *args, **kwargs):
  914. """List database query via `frappe.model.db_query`. Will **not** check for conditions.
  915. Parameters are same as `frappe.get_list`
  916. :param doctype: DocType on which query is to be made.
  917. :param fields: List of fields or `*`. Default is: `["name"]`.
  918. :param filters: List of filters (see example).
  919. :param order_by: Order By e.g. `modified desc`.
  920. :param limit_page_start: Start results at record #. Default 0.
  921. :param limit_page_length: No of records in the page. Default 20.
  922. Example usage:
  923. # simple dict filter
  924. frappe.get_all("ToDo", fields=["name", "description"], filters = {"owner":"test@example.com"})
  925. # filter as a list of lists
  926. frappe.get_all("ToDo", fields=["*"], filters = [["modified", ">", "2014-01-01"]])
  927. # filter as a list of dicts
  928. frappe.get_all("ToDo", fields=["*"], filters = {"description": ("like", "test%")})
  929. """
  930. kwargs["ignore_permissions"] = True
  931. if not "limit_page_length" in kwargs:
  932. kwargs["limit_page_length"] = 0
  933. return get_list(doctype, *args, **kwargs)
  934. def get_value(*args, **kwargs):
  935. """Returns a document property or list of properties.
  936. Alias for `frappe.db.get_value`
  937. :param doctype: DocType name.
  938. :param filters: Filters like `{"x":"y"}` or name of the document. `None` if Single DocType.
  939. :param fieldname: Column name.
  940. :param ignore: Don't raise exception if table, column is missing.
  941. :param as_dict: Return values as dict.
  942. :param debug: Print query in error log.
  943. """
  944. return db.get_value(*args, **kwargs)
  945. def as_json(obj, indent=1):
  946. from frappe.utils.response import json_handler
  947. return json.dumps(obj, indent=indent, sort_keys=True, default=json_handler)
  948. def are_emails_muted():
  949. from frappe.utils import cint
  950. return flags.mute_emails or cint(conf.get("mute_emails") or 0) or False
  951. def get_test_records(doctype):
  952. """Returns list of objects from `test_records.json` in the given doctype's folder."""
  953. from frappe.modules import get_doctype_module, get_module_path
  954. path = os.path.join(get_module_path(get_doctype_module(doctype)), "doctype", scrub(doctype), "test_records.json")
  955. if os.path.exists(path):
  956. with open(path, "r") as f:
  957. return json.loads(f.read())
  958. else:
  959. return []
  960. def format_value(*args, **kwargs):
  961. """Format value with given field properties.
  962. :param value: Value to be formatted.
  963. :param df: (Optional) DocField object with properties `fieldtype`, `options` etc."""
  964. import frappe.utils.formatters
  965. return frappe.utils.formatters.format_value(*args, **kwargs)
  966. def format(*args, **kwargs):
  967. """Format value with given field properties.
  968. :param value: Value to be formatted.
  969. :param df: (Optional) DocField object with properties `fieldtype`, `options` etc."""
  970. import frappe.utils.formatters
  971. return frappe.utils.formatters.format_value(*args, **kwargs)
  972. def get_print(doctype=None, name=None, print_format=None, style=None, html=None, as_pdf=False, doc=None, output = None):
  973. """Get Print Format for given document.
  974. :param doctype: DocType of document.
  975. :param name: Name of document.
  976. :param print_format: Print Format name. Default 'Standard',
  977. :param style: Print Format style.
  978. :param as_pdf: Return as PDF. Default False."""
  979. from frappe.website.render import build_page
  980. from frappe.utils.pdf import get_pdf
  981. local.form_dict.doctype = doctype
  982. local.form_dict.name = name
  983. local.form_dict.format = print_format
  984. local.form_dict.style = style
  985. local.form_dict.doc = doc
  986. if not html:
  987. html = build_page("printview")
  988. if as_pdf:
  989. return get_pdf(html, output = output)
  990. else:
  991. return html
  992. def attach_print(doctype, name, file_name=None, print_format=None, style=None, html=None, doc=None):
  993. from frappe.utils import scrub_urls
  994. if not file_name: file_name = name
  995. file_name = file_name.replace(' ','').replace('/','-')
  996. print_settings = db.get_singles_dict("Print Settings")
  997. local.flags.ignore_print_permissions = True
  998. if int(print_settings.send_print_as_pdf or 0):
  999. out = {
  1000. "fname": file_name + ".pdf",
  1001. "fcontent": get_print(doctype, name, print_format=print_format, style=style, html=html, as_pdf=True, doc=doc)
  1002. }
  1003. else:
  1004. out = {
  1005. "fname": file_name + ".html",
  1006. "fcontent": scrub_urls(get_print(doctype, name, print_format=print_format, style=style, html=html, doc=doc)).encode("utf-8")
  1007. }
  1008. local.flags.ignore_print_permissions = False
  1009. return out
  1010. def publish_progress(*args, **kwargs):
  1011. """Show the user progress for a long request
  1012. :param percent: Percent progress
  1013. :param title: Title
  1014. :param doctype: Optional, for DocType
  1015. :param name: Optional, for Document name
  1016. """
  1017. import frappe.async
  1018. return frappe.async.publish_progress(*args, **kwargs)
  1019. def publish_realtime(*args, **kwargs):
  1020. """Publish real-time updates
  1021. :param event: Event name, like `task_progress` etc.
  1022. :param message: JSON message object. For async must contain `task_id`
  1023. :param room: Room in which to publish update (default entire site)
  1024. :param user: Transmit to user
  1025. :param doctype: Transmit to doctype, docname
  1026. :param docname: Transmit to doctype, docname
  1027. :param after_commit: (default False) will emit after current transaction is committed
  1028. """
  1029. import frappe.async
  1030. return frappe.async.publish_realtime(*args, **kwargs)
  1031. def local_cache(namespace, key, generator, regenerate_if_none=False):
  1032. """A key value store for caching within a request
  1033. :param namespace: frappe.local.cache[namespace]
  1034. :param key: frappe.local.cache[namespace][key] used to retrieve value
  1035. :param generator: method to generate a value if not found in store
  1036. """
  1037. if namespace not in local.cache:
  1038. local.cache[namespace] = {}
  1039. if key not in local.cache[namespace]:
  1040. local.cache[namespace][key] = generator()
  1041. elif local.cache[namespace][key]==None and regenerate_if_none:
  1042. # if key exists but the previous result was None
  1043. local.cache[namespace][key] = generator()
  1044. return local.cache[namespace][key]
  1045. def enqueue(*args, **kwargs):
  1046. '''
  1047. Enqueue method to be executed using a background worker
  1048. :param method: method string or method object
  1049. :param queue: (optional) should be either long, default or short
  1050. :param timeout: (optional) should be set according to the functions
  1051. :param event: this is passed to enable clearing of jobs from queues
  1052. :param async: (optional) if async=False, the method is executed immediately, else via a worker
  1053. :param job_name: (optional) can be used to name an enqueue call, which can be used to prevent duplicate calls
  1054. :param kwargs: keyword arguments to be passed to the method
  1055. '''
  1056. import frappe.utils.background_jobs
  1057. return frappe.utils.background_jobs.enqueue(*args, **kwargs)
  1058. def enqueue_doc(*args, **kwargs):
  1059. '''
  1060. Enqueue method to be executed using a background worker
  1061. :param doctype: DocType of the document on which you want to run the event
  1062. :param name: Name of the document on which you want to run the event
  1063. :param method: method string or method object
  1064. :param queue: (optional) should be either long, default or short
  1065. :param timeout: (optional) should be set according to the functions
  1066. :param kwargs: keyword arguments to be passed to the method
  1067. '''
  1068. import frappe.utils.background_jobs
  1069. return frappe.utils.background_jobs.enqueue_doc(*args, **kwargs)
  1070. def get_doctype_app(doctype):
  1071. def _get_doctype_app():
  1072. doctype_module = local.db.get_value("DocType", doctype, "module")
  1073. return local.module_app[scrub(doctype_module)]
  1074. return local_cache("doctype_app", doctype, generator=_get_doctype_app)
  1075. loggers = {}
  1076. log_level = None
  1077. def logger(module=None, with_more_info=True):
  1078. '''Returns a python logger that uses StreamHandler'''
  1079. from frappe.utils.logger import get_logger
  1080. return get_logger(module or 'default', with_more_info=with_more_info)
  1081. def log_error(message=None, title=None):
  1082. '''Log error to Error Log'''
  1083. get_doc(dict(doctype='Error Log', error=as_unicode(message or get_traceback()),
  1084. method=title)).insert(ignore_permissions=True)
  1085. def get_desk_link(doctype, name):
  1086. return '<a href="#Form/{0}/{1}" style="font-weight: bold;">{2} {1}</a>'.format(doctype, name, _(doctype))
  1087. def bold(text):
  1088. return '<b>{0}</b>'.format(text)
  1089. def safe_eval(code, eval_globals=None, eval_locals=None):
  1090. '''A safer `eval`'''
  1091. whitelisted_globals = {
  1092. "int": int,
  1093. "float": float,
  1094. "long": int,
  1095. "round": round
  1096. }
  1097. if '__' in code:
  1098. throw('Illegal rule {0}. Cannot use "__"'.format(bold(code)))
  1099. if not eval_globals:
  1100. eval_globals = {}
  1101. eval_globals['__builtins__'] = {}
  1102. eval_globals.update(whitelisted_globals)
  1103. return eval(code, eval_globals, eval_locals)
  1104. def get_system_settings(key):
  1105. if key not in local.system_settings:
  1106. local.system_settings.update({key: db.get_single_value('System Settings', key)})
  1107. return local.system_settings.get(key)
  1108. def get_active_domains():
  1109. from frappe.core.doctype.domain_settings.domain_settings import get_active_domains
  1110. return get_active_domains()