You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1794 lines
53 KiB

  1. # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. """
  4. Frappe - Low Code Open Source Framework in Python and JS
  5. Frappe, pronounced fra-pay, is a full stack, batteries-included, web
  6. framework written in Python and Javascript with MariaDB as the database.
  7. It is the framework which powers ERPNext. It is pretty generic and can
  8. be used to build database driven apps.
  9. Read the documentation: https://frappeframework.com/docs
  10. """
  11. from __future__ import unicode_literals, print_function
  12. from six import iteritems, binary_type, text_type, string_types, PY2
  13. from werkzeug.local import Local, release_local
  14. import os, sys, importlib, inspect, json
  15. from past.builtins import cmp
  16. import click
  17. # Local application imports
  18. from .exceptions import *
  19. from .utils.jinja import (get_jenv, get_template, render_template, get_email_from_template, get_jloader)
  20. from .utils.lazy_loader import lazy_import
  21. # Lazy imports
  22. faker = lazy_import('faker')
  23. # Harmless for Python 3
  24. # For Python 2 set default encoding to utf-8
  25. if PY2:
  26. reload(sys)
  27. sys.setdefaultencoding("utf-8")
  28. __version__ = '13.0.0-dev'
  29. __title__ = "Frappe Framework"
  30. local = Local()
  31. controllers = {}
  32. class _dict(dict):
  33. """dict like object that exposes keys as attributes"""
  34. def __getattr__(self, key):
  35. ret = self.get(key)
  36. if not ret and key.startswith("__"):
  37. raise AttributeError()
  38. return ret
  39. def __setattr__(self, key, value):
  40. self[key] = value
  41. def __getstate__(self):
  42. return self
  43. def __setstate__(self, d):
  44. self.update(d)
  45. def update(self, d):
  46. """update and return self -- the missing dict feature in python"""
  47. super(_dict, self).update(d)
  48. return self
  49. def copy(self):
  50. return _dict(dict(self).copy())
  51. def _(msg, lang=None, context=None):
  52. """Returns translated string in current lang, if exists.
  53. Usage:
  54. _('Change')
  55. _('Change', context='Coins')
  56. """
  57. from frappe.translate import get_full_dict
  58. from frappe.utils import strip_html_tags, is_html
  59. if not hasattr(local, 'lang'):
  60. local.lang = lang or 'en'
  61. if not lang:
  62. lang = local.lang
  63. non_translated_string = msg
  64. if is_html(msg):
  65. msg = strip_html_tags(msg)
  66. # msg should always be unicode
  67. msg = as_unicode(msg).strip()
  68. translated_string = ''
  69. if context:
  70. string_key = '{msg}:{context}'.format(msg=msg, context=context)
  71. translated_string = get_full_dict(lang).get(string_key)
  72. if not translated_string:
  73. translated_string = get_full_dict(lang).get(msg)
  74. # return lang_full_dict according to lang passed parameter
  75. return translated_string or non_translated_string
  76. def as_unicode(text, encoding='utf-8'):
  77. '''Convert to unicode if required'''
  78. if isinstance(text, text_type):
  79. return text
  80. elif text==None:
  81. return ''
  82. elif isinstance(text, binary_type):
  83. return text_type(text, encoding)
  84. else:
  85. return text_type(text)
  86. def get_lang_dict(fortype, name=None):
  87. """Returns the translated language dict for the given type and name.
  88. :param fortype: must be one of `doctype`, `page`, `report`, `include`, `jsfile`, `boot`
  89. :param name: name of the document for which assets are to be returned."""
  90. from frappe.translate import get_dict
  91. return get_dict(fortype, name)
  92. def set_user_lang(user, user_language=None):
  93. """Guess and set user language for the session. `frappe.local.lang`"""
  94. from frappe.translate import get_user_lang
  95. local.lang = get_user_lang(user)
  96. # local-globals
  97. db = local("db")
  98. conf = local("conf")
  99. form = form_dict = local("form_dict")
  100. request = local("request")
  101. response = local("response")
  102. session = local("session")
  103. user = local("user")
  104. flags = local("flags")
  105. error_log = local("error_log")
  106. debug_log = local("debug_log")
  107. message_log = local("message_log")
  108. lang = local("lang")
  109. def init(site, sites_path=None, new_site=False):
  110. """Initialize frappe for the current site. Reset thread locals `frappe.local`"""
  111. if getattr(local, "initialised", None):
  112. return
  113. if not sites_path:
  114. sites_path = '.'
  115. local.error_log = []
  116. local.message_log = []
  117. local.debug_log = []
  118. local.realtime_log = []
  119. local.flags = _dict({
  120. "currently_saving": [],
  121. "redirect_location": "",
  122. "in_install_db": False,
  123. "in_install_app": False,
  124. "in_import": False,
  125. "in_test": False,
  126. "mute_messages": False,
  127. "ignore_links": False,
  128. "mute_emails": False,
  129. "has_dataurl": False,
  130. "new_site": new_site
  131. })
  132. local.rollback_observers = []
  133. local.before_commit = []
  134. local.test_objects = {}
  135. local.site = site
  136. local.sites_path = sites_path
  137. local.site_path = os.path.join(sites_path, site)
  138. local.all_apps = None
  139. local.request_ip = None
  140. local.response = _dict({"docs":[]})
  141. local.task_id = None
  142. local.conf = _dict(get_site_config())
  143. local.lang = local.conf.lang or "en"
  144. local.lang_full_dict = None
  145. local.module_app = None
  146. local.app_modules = None
  147. local.system_settings = _dict()
  148. local.user = None
  149. local.user_perms = None
  150. local.session = None
  151. local.role_permissions = {}
  152. local.valid_columns = {}
  153. local.new_doc_templates = {}
  154. local.link_count = {}
  155. local.jenv = None
  156. local.jloader =None
  157. local.cache = {}
  158. local.document_cache = {}
  159. local.meta_cache = {}
  160. local.form_dict = _dict()
  161. local.session = _dict()
  162. local.dev_server = os.environ.get('DEV_SERVER', False)
  163. setup_module_map()
  164. local.initialised = True
  165. def connect(site=None, db_name=None, set_admin_as_user=True):
  166. """Connect to site database instance.
  167. :param site: If site is given, calls `frappe.init`.
  168. :param db_name: Optional. Will use from `site_config.json`.
  169. :param set_admin_as_user: Set Administrator as current user.
  170. """
  171. from frappe.database import get_db
  172. if site:
  173. init(site)
  174. local.db = get_db(user=db_name or local.conf.db_name)
  175. if set_admin_as_user:
  176. set_user("Administrator")
  177. def connect_replica():
  178. from frappe.database import get_db
  179. user = local.conf.db_name
  180. password = local.conf.db_password
  181. if local.conf.different_credentials_for_replica:
  182. user = local.conf.replica_db_name
  183. password = local.conf.replica_db_password
  184. local.replica_db = get_db(host=local.conf.replica_host, user=user, password=password)
  185. # swap db connections
  186. local.primary_db = local.db
  187. local.db = local.replica_db
  188. def get_site_config(sites_path=None, site_path=None):
  189. """Returns `site_config.json` combined with `sites/common_site_config.json`.
  190. `site_config` is a set of site wide settings like database name, password, email etc."""
  191. config = {}
  192. sites_path = sites_path or getattr(local, "sites_path", None)
  193. site_path = site_path or getattr(local, "site_path", None)
  194. if sites_path:
  195. common_site_config = os.path.join(sites_path, "common_site_config.json")
  196. if os.path.exists(common_site_config):
  197. try:
  198. config.update(get_file_json(common_site_config))
  199. except Exception as error:
  200. click.secho("common_site_config.json is invalid", fg="red")
  201. print(error)
  202. if site_path:
  203. site_config = os.path.join(site_path, "site_config.json")
  204. if os.path.exists(site_config):
  205. try:
  206. config.update(get_file_json(site_config))
  207. except Exception as error:
  208. click.secho("{0}/site_config.json is invalid".format(local.site), fg="red")
  209. print(error)
  210. elif local.site and not local.flags.new_site:
  211. raise IncorrectSitePath("{0} does not exist".format(local.site))
  212. return _dict(config)
  213. def get_conf(site=None):
  214. if hasattr(local, 'conf'):
  215. return local.conf
  216. else:
  217. # if no site, get from common_site_config.json
  218. with init_site(site):
  219. return local.conf
  220. class init_site:
  221. def __init__(self, site=None):
  222. '''If site==None, initialize it for empty site ('') to load common_site_config.json'''
  223. self.site = site or ''
  224. def __enter__(self):
  225. init(self.site)
  226. return local
  227. def __exit__(self, type, value, traceback):
  228. destroy()
  229. def destroy():
  230. """Closes connection and releases werkzeug local."""
  231. if db:
  232. db.close()
  233. release_local(local)
  234. # memcache
  235. redis_server = None
  236. def cache():
  237. """Returns redis connection."""
  238. global redis_server
  239. if not redis_server:
  240. from frappe.utils.redis_wrapper import RedisWrapper
  241. redis_server = RedisWrapper.from_url(conf.get('redis_cache')
  242. or "redis://localhost:11311")
  243. return redis_server
  244. def get_traceback():
  245. """Returns error traceback."""
  246. from frappe.utils import get_traceback
  247. return get_traceback()
  248. def errprint(msg):
  249. """Log error. This is sent back as `exc` in response.
  250. :param msg: Message."""
  251. msg = as_unicode(msg)
  252. if not request or (not "cmd" in local.form_dict) or conf.developer_mode:
  253. print(msg)
  254. error_log.append({"exc": msg})
  255. def print_sql(enable=True):
  256. return cache().set_value('flag_print_sql', enable)
  257. def log(msg):
  258. """Add to `debug_log`.
  259. :param msg: Message."""
  260. if not request:
  261. if conf.get("logging") or False:
  262. print(repr(msg))
  263. debug_log.append(as_unicode(msg))
  264. def msgprint(msg, title=None, raise_exception=0, as_table=False, as_list=False, indicator=None, alert=False, primary_action=None, is_minimizable=None, wide=None):
  265. """Print a message to the user (via HTTP response).
  266. Messages are sent in the `__server_messages` property in the
  267. response JSON and shown in a pop-up / modal.
  268. :param msg: Message.
  269. :param title: [optional] Message title.
  270. :param raise_exception: [optional] Raise given exception and show message.
  271. :param as_table: [optional] If `msg` is a list of lists, render as HTML table.
  272. :param as_list: [optional] If `msg` is a list, render as un-ordered list.
  273. :param primary_action: [optional] Bind a primary server/client side action.
  274. :param is_minimizable: [optional] Allow users to minimize the modal
  275. :param wide: [optional] Show wide modal
  276. """
  277. from frappe.utils import strip_html_tags
  278. msg = safe_decode(msg)
  279. out = _dict(message=msg)
  280. def _raise_exception():
  281. if raise_exception:
  282. if flags.rollback_on_exception:
  283. db.rollback()
  284. import inspect
  285. if inspect.isclass(raise_exception) and issubclass(raise_exception, Exception):
  286. raise raise_exception(msg)
  287. else:
  288. raise ValidationError(msg)
  289. if flags.mute_messages:
  290. _raise_exception()
  291. return
  292. if as_table and type(msg) in (list, tuple):
  293. out.as_table = 1
  294. if as_list and type(msg) in (list, tuple) and len(msg) > 1:
  295. out.as_list = 1
  296. if flags.print_messages and out.message:
  297. print(f"Message: {strip_html_tags(out.message)}")
  298. if title:
  299. out.title = title
  300. if not indicator and raise_exception:
  301. indicator = 'red'
  302. if indicator:
  303. out.indicator = indicator
  304. if is_minimizable:
  305. out.is_minimizable = is_minimizable
  306. if alert:
  307. out.alert = 1
  308. if raise_exception:
  309. out.raise_exception = 1
  310. if primary_action:
  311. out.primary_action = primary_action
  312. if wide:
  313. out.wide = wide
  314. message_log.append(json.dumps(out))
  315. if raise_exception and hasattr(raise_exception, '__name__'):
  316. local.response['exc_type'] = raise_exception.__name__
  317. _raise_exception()
  318. def clear_messages():
  319. local.message_log = []
  320. def get_message_log():
  321. log = []
  322. for msg_out in local.message_log:
  323. log.append(json.loads(msg_out))
  324. return log
  325. def clear_last_message():
  326. if len(local.message_log) > 0:
  327. local.message_log = local.message_log[:-1]
  328. def throw(msg, exc=ValidationError, title=None, is_minimizable=None, wide=None, as_list=False):
  329. """Throw execption and show message (`msgprint`).
  330. :param msg: Message.
  331. :param exc: Exception class. Default `frappe.ValidationError`"""
  332. msgprint(msg, raise_exception=exc, title=title, indicator='red', is_minimizable=is_minimizable, wide=wide, as_list=as_list)
  333. def emit_js(js, user=False, **kwargs):
  334. if user == False:
  335. user = session.user
  336. publish_realtime('eval_js', js, user=user, **kwargs)
  337. def create_folder(path, with_init=False):
  338. """Create a folder in the given path and add an `__init__.py` file (optional).
  339. :param path: Folder path.
  340. :param with_init: Create `__init__.py` in the new folder."""
  341. from frappe.utils import touch_file
  342. if not os.path.exists(path):
  343. os.makedirs(path)
  344. if with_init:
  345. touch_file(os.path.join(path, "__init__.py"))
  346. def set_user(username):
  347. """Set current user.
  348. :param username: **User** name to set as current user."""
  349. local.session.user = username
  350. local.session.sid = username
  351. local.cache = {}
  352. local.form_dict = _dict()
  353. local.jenv = None
  354. local.session.data = _dict()
  355. local.role_permissions = {}
  356. local.new_doc_templates = {}
  357. local.user_perms = None
  358. def get_user():
  359. from frappe.utils.user import UserPermissions
  360. if not local.user_perms:
  361. local.user_perms = UserPermissions(local.session.user)
  362. return local.user_perms
  363. def get_roles(username=None):
  364. """Returns roles of current user."""
  365. if not local.session:
  366. return ["Guest"]
  367. import frappe.permissions
  368. return frappe.permissions.get_roles(username or local.session.user)
  369. def get_request_header(key, default=None):
  370. """Return HTTP request header.
  371. :param key: HTTP header key.
  372. :param default: Default value."""
  373. return request.headers.get(key, default)
  374. def sendmail(recipients=[], sender="", subject="No Subject", message="No Message",
  375. as_markdown=False, delayed=True, reference_doctype=None, reference_name=None,
  376. unsubscribe_method=None, unsubscribe_params=None, unsubscribe_message=None, add_unsubscribe_link=1,
  377. attachments=None, content=None, doctype=None, name=None, reply_to=None, queue_separately=False,
  378. cc=[], bcc=[], message_id=None, in_reply_to=None, send_after=None, expose_recipients=None,
  379. send_priority=1, communication=None, retry=1, now=None, read_receipt=None, is_notification=False,
  380. inline_images=None, template=None, args=None, header=None, print_letterhead=False, with_container=False):
  381. """Send email using user's default **Email Account** or global default **Email Account**.
  382. :param recipients: List of recipients.
  383. :param sender: Email sender. Default is current user or default outgoing account.
  384. :param subject: Email Subject.
  385. :param message: (or `content`) Email Content.
  386. :param as_markdown: Convert content markdown to HTML.
  387. :param delayed: Send via scheduled email sender **Email Queue**. Don't send immediately. Default is true
  388. :param send_priority: Priority for Email Queue, default 1.
  389. :param reference_doctype: (or `doctype`) Append as communication to this DocType.
  390. :param reference_name: (or `name`) Append as communication to this document name.
  391. :param unsubscribe_method: Unsubscribe url with options email, doctype, name. e.g. `/api/method/unsubscribe`
  392. :param unsubscribe_params: Unsubscribe paramaters to be loaded on the unsubscribe_method [optional] (dict).
  393. :param attachments: List of attachments.
  394. :param reply_to: Reply-To Email Address.
  395. :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.
  396. :param in_reply_to: Used to send the Message-Id of a received email back as In-Reply-To.
  397. :param send_after: Send after the given datetime.
  398. :param expose_recipients: Display all recipients in the footer message - "This email was sent to"
  399. :param communication: Communication link to be set in Email Queue record
  400. :param inline_images: List of inline images as {"filename", "filecontent"}. All src properties will be replaced with random Content-Id
  401. :param template: Name of html template from templates/emails folder
  402. :param args: Arguments for rendering the template
  403. :param header: Append header in email
  404. :param with_container: Wraps email inside a styled container
  405. """
  406. text_content = None
  407. if template:
  408. message, text_content = get_email_from_template(template, args)
  409. message = content or message
  410. if as_markdown:
  411. from frappe.utils import md_to_html
  412. message = md_to_html(message)
  413. if not delayed:
  414. now = True
  415. from frappe.email import queue
  416. queue.send(recipients=recipients, sender=sender,
  417. subject=subject, message=message, text_content=text_content,
  418. reference_doctype = doctype or reference_doctype, reference_name = name or reference_name, add_unsubscribe_link=add_unsubscribe_link,
  419. unsubscribe_method=unsubscribe_method, unsubscribe_params=unsubscribe_params, unsubscribe_message=unsubscribe_message,
  420. attachments=attachments, reply_to=reply_to, cc=cc, bcc=bcc, message_id=message_id, in_reply_to=in_reply_to,
  421. send_after=send_after, expose_recipients=expose_recipients, send_priority=send_priority, queue_separately=queue_separately,
  422. communication=communication, now=now, read_receipt=read_receipt, is_notification=is_notification,
  423. inline_images=inline_images, header=header, print_letterhead=print_letterhead, with_container=with_container)
  424. whitelisted = []
  425. guest_methods = []
  426. xss_safe_methods = []
  427. allowed_http_methods_for_whitelisted_func = {}
  428. def whitelist(allow_guest=False, xss_safe=False, methods=None):
  429. """
  430. Decorator for whitelisting a function and making it accessible via HTTP.
  431. Standard request will be `/api/method/[path.to.method]`
  432. :param allow_guest: Allow non logged-in user to access this method.
  433. :param methods: Allowed http method to access the method.
  434. Use as:
  435. @frappe.whitelist()
  436. def myfunc(param1, param2):
  437. pass
  438. """
  439. if not methods:
  440. methods = ['GET', 'POST', 'PUT', 'DELETE']
  441. def innerfn(fn):
  442. global whitelisted, guest_methods, xss_safe_methods, allowed_http_methods_for_whitelisted_func
  443. # get function from the unbound / bound method
  444. # this is needed because functions can be compared, but not methods
  445. method = None
  446. if hasattr(fn, '__func__'):
  447. method = fn
  448. fn = method.__func__
  449. whitelisted.append(fn)
  450. allowed_http_methods_for_whitelisted_func[fn] = methods
  451. if allow_guest:
  452. guest_methods.append(fn)
  453. if xss_safe:
  454. xss_safe_methods.append(fn)
  455. return method or fn
  456. return innerfn
  457. def is_whitelisted(method):
  458. from frappe.utils import sanitize_html
  459. is_guest = session['user'] == 'Guest'
  460. if method not in whitelisted or is_guest and method not in guest_methods:
  461. throw(_("Not permitted"), PermissionError)
  462. if is_guest and method not in xss_safe_methods:
  463. # strictly sanitize form_dict
  464. # escapes html characters like <> except for predefined tags like a, b, ul etc.
  465. for key, value in form_dict.items():
  466. if isinstance(value, string_types):
  467. form_dict[key] = sanitize_html(value)
  468. def read_only():
  469. def innfn(fn):
  470. def wrapper_fn(*args, **kwargs):
  471. if conf.read_from_replica:
  472. connect_replica()
  473. try:
  474. retval = fn(*args, **get_newargs(fn, kwargs))
  475. except:
  476. raise
  477. finally:
  478. if local and hasattr(local, 'primary_db'):
  479. local.db.close()
  480. local.db = local.primary_db
  481. return retval
  482. return wrapper_fn
  483. return innfn
  484. def only_for(roles, message=False):
  485. """Raise `frappe.PermissionError` if the user does not have any of the given **Roles**.
  486. :param roles: List of roles to check."""
  487. if local.flags.in_test:
  488. return
  489. if not isinstance(roles, (tuple, list)):
  490. roles = (roles,)
  491. roles = set(roles)
  492. myroles = set(get_roles())
  493. if not roles.intersection(myroles):
  494. if message:
  495. msgprint(_('This action is only allowed for {}').format(bold(', '.join(roles))), _('Not Permitted'))
  496. raise PermissionError
  497. def get_domain_data(module):
  498. try:
  499. domain_data = get_hooks('domains')
  500. if module in domain_data:
  501. return _dict(get_attr(get_hooks('domains')[module][0] + '.data'))
  502. else:
  503. return _dict()
  504. except ImportError:
  505. if local.flags.in_test:
  506. return _dict()
  507. else:
  508. raise
  509. def clear_cache(user=None, doctype=None):
  510. """Clear **User**, **DocType** or global cache.
  511. :param user: If user is given, only user cache is cleared.
  512. :param doctype: If doctype is given, only DocType cache is cleared."""
  513. import frappe.cache_manager
  514. if doctype:
  515. frappe.cache_manager.clear_doctype_cache(doctype)
  516. reset_metadata_version()
  517. elif user:
  518. frappe.cache_manager.clear_user_cache(user)
  519. else: # everything
  520. from frappe import translate
  521. frappe.cache_manager.clear_user_cache()
  522. frappe.cache_manager.clear_domain_cache()
  523. translate.clear_cache()
  524. reset_metadata_version()
  525. local.cache = {}
  526. local.new_doc_templates = {}
  527. for fn in get_hooks("clear_cache"):
  528. get_attr(fn)()
  529. local.role_permissions = {}
  530. def only_has_select_perm(doctype, user=None, ignore_permissions=False):
  531. if ignore_permissions:
  532. return False
  533. if not user:
  534. user = local.session.user
  535. import frappe.permissions
  536. permissions = frappe.permissions.get_role_permissions(doctype, user=user)
  537. if permissions.get('select') and not permissions.get('read'):
  538. return True
  539. else:
  540. return False
  541. def has_permission(doctype=None, ptype="read", doc=None, user=None, verbose=False, throw=False):
  542. """Raises `frappe.PermissionError` if not permitted.
  543. :param doctype: DocType for which permission is to be check.
  544. :param ptype: Permission type (`read`, `write`, `create`, `submit`, `cancel`, `amend`). Default: `read`.
  545. :param doc: [optional] Checks User permissions for given doc.
  546. :param user: [optional] Check for given user. Default: current user."""
  547. if not doctype and doc:
  548. doctype = doc.doctype
  549. import frappe.permissions
  550. out = frappe.permissions.has_permission(doctype, ptype, doc=doc, verbose=verbose, user=user, raise_exception=throw)
  551. if throw and not out:
  552. if doc:
  553. frappe.throw(_("No permission for {0}").format(doc.doctype + " " + doc.name))
  554. else:
  555. frappe.throw(_("No permission for {0}").format(doctype))
  556. return out
  557. def has_website_permission(doc=None, ptype='read', user=None, verbose=False, doctype=None):
  558. """Raises `frappe.PermissionError` if not permitted.
  559. :param doctype: DocType for which permission is to be check.
  560. :param ptype: Permission type (`read`, `write`, `create`, `submit`, `cancel`, `amend`). Default: `read`.
  561. :param doc: Checks User permissions for given doc.
  562. :param user: [optional] Check for given user. Default: current user."""
  563. if not user:
  564. user = session.user
  565. if doc:
  566. if isinstance(doc, string_types):
  567. doc = get_doc(doctype, doc)
  568. doctype = doc.doctype
  569. if doc.flags.ignore_permissions:
  570. return True
  571. # check permission in controller
  572. if hasattr(doc, 'has_website_permission'):
  573. return doc.has_website_permission(ptype, user, verbose=verbose)
  574. hooks = (get_hooks("has_website_permission") or {}).get(doctype, [])
  575. if hooks:
  576. for method in hooks:
  577. result = call(method, doc=doc, ptype=ptype, user=user, verbose=verbose)
  578. # if even a single permission check is Falsy
  579. if not result:
  580. return False
  581. # else it is Truthy
  582. return True
  583. else:
  584. return False
  585. def is_table(doctype):
  586. """Returns True if `istable` property (indicating child Table) is set for given DocType."""
  587. def get_tables():
  588. return db.sql_list("select name from tabDocType where istable=1")
  589. tables = cache().get_value("is_table", get_tables)
  590. return doctype in tables
  591. def get_precision(doctype, fieldname, currency=None, doc=None):
  592. """Get precision for a given field"""
  593. from frappe.model.meta import get_field_precision
  594. return get_field_precision(get_meta(doctype).get_field(fieldname), doc, currency)
  595. def generate_hash(txt=None, length=None):
  596. """Generates random hash for given text + current timestamp + random string."""
  597. import hashlib, time
  598. from .utils import random_string
  599. digest = hashlib.sha224(((txt or "") + repr(time.time()) + repr(random_string(8))).encode()).hexdigest()
  600. if length:
  601. digest = digest[:length]
  602. return digest
  603. def reset_metadata_version():
  604. """Reset `metadata_version` (Client (Javascript) build ID) hash."""
  605. v = generate_hash()
  606. cache().set_value("metadata_version", v)
  607. return v
  608. def new_doc(doctype, parent_doc=None, parentfield=None, as_dict=False):
  609. """Returns a new document of the given DocType with defaults set.
  610. :param doctype: DocType of the new document.
  611. :param parent_doc: [optional] add to parent document.
  612. :param parentfield: [optional] add against this `parentfield`."""
  613. from frappe.model.create_new import get_new_doc
  614. return get_new_doc(doctype, parent_doc, parentfield, as_dict=as_dict)
  615. def set_value(doctype, docname, fieldname, value=None):
  616. """Set document value. Calls `frappe.client.set_value`"""
  617. import frappe.client
  618. return frappe.client.set_value(doctype, docname, fieldname, value)
  619. def get_cached_doc(*args, **kwargs):
  620. if args and len(args) > 1 and isinstance(args[1], text_type):
  621. key = get_document_cache_key(args[0], args[1])
  622. # local cache
  623. doc = local.document_cache.get(key)
  624. if doc:
  625. return doc
  626. # redis cache
  627. doc = cache().hget('document_cache', key)
  628. if doc:
  629. doc = get_doc(doc)
  630. local.document_cache[key] = doc
  631. return doc
  632. # database
  633. doc = get_doc(*args, **kwargs)
  634. return doc
  635. def get_document_cache_key(doctype, name):
  636. return '{0}::{1}'.format(doctype, name)
  637. def clear_document_cache(doctype, name):
  638. cache().hdel("last_modified", doctype)
  639. key = get_document_cache_key(doctype, name)
  640. if key in local.document_cache:
  641. del local.document_cache[key]
  642. cache().hdel('document_cache', key)
  643. def get_cached_value(doctype, name, fieldname, as_dict=False):
  644. doc = get_cached_doc(doctype, name)
  645. if isinstance(fieldname, string_types):
  646. if as_dict:
  647. throw('Cannot make dict for single fieldname')
  648. return doc.get(fieldname)
  649. values = [doc.get(f) for f in fieldname]
  650. if as_dict:
  651. return _dict(zip(fieldname, values))
  652. return values
  653. def get_doc(*args, **kwargs):
  654. """Return a `frappe.model.document.Document` object of the given type and name.
  655. :param arg1: DocType name as string **or** document JSON.
  656. :param arg2: [optional] Document name as string.
  657. Examples:
  658. # insert a new document
  659. todo = frappe.get_doc({"doctype":"ToDo", "description": "test"})
  660. todo.insert()
  661. # open an existing document
  662. todo = frappe.get_doc("ToDo", "TD0001")
  663. """
  664. import frappe.model.document
  665. doc = frappe.model.document.get_doc(*args, **kwargs)
  666. # set in cache
  667. if args and len(args) > 1:
  668. key = get_document_cache_key(args[0], args[1])
  669. local.document_cache[key] = doc
  670. cache().hset('document_cache', key, doc.as_dict())
  671. return doc
  672. def get_last_doc(doctype, filters=None, order_by="creation desc"):
  673. """Get last created document of this type."""
  674. d = get_all(
  675. doctype,
  676. filters=filters,
  677. limit_page_length=1,
  678. order_by=order_by,
  679. pluck="name"
  680. )
  681. if d:
  682. return get_doc(doctype, d[0])
  683. else:
  684. raise DoesNotExistError
  685. def get_single(doctype):
  686. """Return a `frappe.model.document.Document` object of the given Single doctype."""
  687. return get_doc(doctype, doctype)
  688. def get_meta(doctype, cached=True):
  689. """Get `frappe.model.meta.Meta` instance of given doctype name."""
  690. import frappe.model.meta
  691. return frappe.model.meta.get_meta(doctype, cached=cached)
  692. def get_meta_module(doctype):
  693. import frappe.modules
  694. return frappe.modules.load_doctype_module(doctype)
  695. def delete_doc(doctype=None, name=None, force=0, ignore_doctypes=None, for_reload=False,
  696. ignore_permissions=False, flags=None, ignore_on_trash=False, ignore_missing=True, delete_permanently=False):
  697. """Delete a document. Calls `frappe.model.delete_doc.delete_doc`.
  698. :param doctype: DocType of document to be delete.
  699. :param name: Name of document to be delete.
  700. :param force: Allow even if document is linked. Warning: This may lead to data integrity errors.
  701. :param ignore_doctypes: Ignore if child table is one of these.
  702. :param for_reload: Call `before_reload` trigger before deleting.
  703. :param ignore_permissions: Ignore user permissions.
  704. :param delete_permanently: Do not create a Deleted Document for the document."""
  705. import frappe.model.delete_doc
  706. frappe.model.delete_doc.delete_doc(doctype, name, force, ignore_doctypes, for_reload,
  707. ignore_permissions, flags, ignore_on_trash, ignore_missing, delete_permanently)
  708. def delete_doc_if_exists(doctype, name, force=0):
  709. """Delete document if exists."""
  710. if db.exists(doctype, name):
  711. delete_doc(doctype, name, force=force)
  712. def reload_doctype(doctype, force=False, reset_permissions=False):
  713. """Reload DocType from model (`[module]/[doctype]/[name]/[name].json`) files."""
  714. reload_doc(scrub(db.get_value("DocType", doctype, "module")), "doctype", scrub(doctype),
  715. force=force, reset_permissions=reset_permissions)
  716. def reload_doc(module, dt=None, dn=None, force=False, reset_permissions=False):
  717. """Reload Document from model (`[module]/[doctype]/[name]/[name].json`) files.
  718. :param module: Module name.
  719. :param dt: DocType name.
  720. :param dn: Document name.
  721. :param force: Reload even if `modified` timestamp matches.
  722. """
  723. import frappe.modules
  724. return frappe.modules.reload_doc(module, dt, dn, force=force, reset_permissions=reset_permissions)
  725. @whitelist()
  726. def rename_doc(*args, **kwargs):
  727. """
  728. Renames a doc(dt, old) to doc(dt, new) and updates all linked fields of type "Link"
  729. Calls `frappe.model.rename_doc.rename_doc`
  730. """
  731. kwargs.pop('ignore_permissions', None)
  732. kwargs.pop('cmd', None)
  733. from frappe.model.rename_doc import rename_doc
  734. return rename_doc(*args, **kwargs)
  735. def get_module(modulename):
  736. """Returns a module object for given Python module name using `importlib.import_module`."""
  737. return importlib.import_module(modulename)
  738. def scrub(txt):
  739. """Returns sluggified string. e.g. `Sales Order` becomes `sales_order`."""
  740. return txt.replace(' ', '_').replace('-', '_').lower()
  741. def unscrub(txt):
  742. """Returns titlified string. e.g. `sales_order` becomes `Sales Order`."""
  743. return txt.replace('_', ' ').replace('-', ' ').title()
  744. def get_module_path(module, *joins):
  745. """Get the path of the given module name.
  746. :param module: Module name.
  747. :param *joins: Join additional path elements using `os.path.join`."""
  748. module = scrub(module)
  749. return get_pymodule_path(local.module_app[module] + "." + module, *joins)
  750. def get_app_path(app_name, *joins):
  751. """Return path of given app.
  752. :param app: App name.
  753. :param *joins: Join additional path elements using `os.path.join`."""
  754. return get_pymodule_path(app_name, *joins)
  755. def get_site_path(*joins):
  756. """Return path of current site.
  757. :param *joins: Join additional path elements using `os.path.join`."""
  758. return os.path.join(local.site_path, *joins)
  759. def get_pymodule_path(modulename, *joins):
  760. """Return path of given Python module name.
  761. :param modulename: Python module name.
  762. :param *joins: Join additional path elements using `os.path.join`."""
  763. if not "public" in joins:
  764. joins = [scrub(part) for part in joins]
  765. return os.path.join(os.path.dirname(get_module(scrub(modulename)).__file__), *joins)
  766. def get_module_list(app_name):
  767. """Get list of modules for given all via `app/modules.txt`."""
  768. return get_file_items(os.path.join(os.path.dirname(get_module(app_name).__file__), "modules.txt"))
  769. def get_all_apps(with_internal_apps=True, sites_path=None):
  770. """Get list of all apps via `sites/apps.txt`."""
  771. if not sites_path:
  772. sites_path = local.sites_path
  773. apps = get_file_items(os.path.join(sites_path, "apps.txt"), raise_not_found=True)
  774. if with_internal_apps:
  775. for app in get_file_items(os.path.join(local.site_path, "apps.txt")):
  776. if app not in apps:
  777. apps.append(app)
  778. if "frappe" in apps:
  779. apps.remove("frappe")
  780. apps.insert(0, 'frappe')
  781. return apps
  782. def get_installed_apps(sort=False, frappe_last=False):
  783. """Get list of installed apps in current site."""
  784. if getattr(flags, "in_install_db", True):
  785. return []
  786. if not db:
  787. connect()
  788. if not local.all_apps:
  789. local.all_apps = cache().get_value('all_apps', get_all_apps)
  790. installed = json.loads(db.get_global("installed_apps") or "[]")
  791. if sort:
  792. installed = [app for app in local.all_apps if app in installed]
  793. if frappe_last:
  794. if 'frappe' in installed:
  795. installed.remove('frappe')
  796. installed.append('frappe')
  797. return installed
  798. def get_doc_hooks():
  799. '''Returns hooked methods for given doc. It will expand the dict tuple if required.'''
  800. if not hasattr(local, 'doc_events_hooks'):
  801. hooks = get_hooks('doc_events', {})
  802. out = {}
  803. for key, value in iteritems(hooks):
  804. if isinstance(key, tuple):
  805. for doctype in key:
  806. append_hook(out, doctype, value)
  807. else:
  808. append_hook(out, key, value)
  809. local.doc_events_hooks = out
  810. return local.doc_events_hooks
  811. def get_hooks(hook=None, default=None, app_name=None):
  812. """Get hooks via `app/hooks.py`
  813. :param hook: Name of the hook. Will gather all hooks for this name and return as a list.
  814. :param default: Default if no hook found.
  815. :param app_name: Filter by app."""
  816. def load_app_hooks(app_name=None):
  817. hooks = {}
  818. for app in [app_name] if app_name else get_installed_apps(sort=True):
  819. app = "frappe" if app=="webnotes" else app
  820. try:
  821. app_hooks = get_module(app + ".hooks")
  822. except ImportError:
  823. if local.flags.in_install_app:
  824. # if app is not installed while restoring
  825. # ignore it
  826. pass
  827. print('Could not find app "{0}"'.format(app_name))
  828. if not request:
  829. sys.exit(1)
  830. raise
  831. for key in dir(app_hooks):
  832. if not key.startswith("_"):
  833. append_hook(hooks, key, getattr(app_hooks, key))
  834. return hooks
  835. no_cache = conf.developer_mode or False
  836. if app_name:
  837. hooks = _dict(load_app_hooks(app_name))
  838. else:
  839. if no_cache:
  840. hooks = _dict(load_app_hooks())
  841. else:
  842. hooks = _dict(cache().get_value("app_hooks", load_app_hooks))
  843. if hook:
  844. return hooks.get(hook) or (default if default is not None else [])
  845. else:
  846. return hooks
  847. def append_hook(target, key, value):
  848. '''appends a hook to the the target dict.
  849. If the hook key, exists, it will make it a key.
  850. If the hook value is a dict, like doc_events, it will
  851. listify the values against the key.
  852. '''
  853. if isinstance(value, dict):
  854. # dict? make a list of values against each key
  855. target.setdefault(key, {})
  856. for inkey in value:
  857. append_hook(target[key], inkey, value[inkey])
  858. else:
  859. # make a list
  860. target.setdefault(key, [])
  861. if not isinstance(value, list):
  862. value = [value]
  863. target[key].extend(value)
  864. def setup_module_map():
  865. """Rebuild map of all modules (internal)."""
  866. _cache = cache()
  867. if conf.db_name:
  868. local.app_modules = _cache.get_value("app_modules")
  869. local.module_app = _cache.get_value("module_app")
  870. if not (local.app_modules and local.module_app):
  871. local.module_app, local.app_modules = {}, {}
  872. for app in get_all_apps(True):
  873. if app == "webnotes":
  874. app = "frappe"
  875. local.app_modules.setdefault(app, [])
  876. for module in get_module_list(app):
  877. module = scrub(module)
  878. local.module_app[module] = app
  879. local.app_modules[app].append(module)
  880. if conf.db_name:
  881. _cache.set_value("app_modules", local.app_modules)
  882. _cache.set_value("module_app", local.module_app)
  883. def get_file_items(path, raise_not_found=False, ignore_empty_lines=True):
  884. """Returns items from text file as a list. Ignores empty lines."""
  885. import frappe.utils
  886. content = read_file(path, raise_not_found=raise_not_found)
  887. if content:
  888. content = frappe.utils.strip(content)
  889. return [
  890. p.strip() for p in content.splitlines()
  891. if (not ignore_empty_lines) or (p.strip() and not p.startswith("#"))
  892. ]
  893. else:
  894. return []
  895. def get_file_json(path):
  896. """Read a file and return parsed JSON object."""
  897. with open(path, 'r') as f:
  898. return json.load(f)
  899. def read_file(path, raise_not_found=False):
  900. """Open a file and return its content as Unicode."""
  901. if isinstance(path, text_type):
  902. path = path.encode("utf-8")
  903. if os.path.exists(path):
  904. with open(path, "r") as f:
  905. return as_unicode(f.read())
  906. elif raise_not_found:
  907. raise IOError("{} Not Found".format(path))
  908. else:
  909. return None
  910. def get_attr(method_string):
  911. """Get python method object from its name."""
  912. app_name = method_string.split(".")[0]
  913. if not local.flags.in_install and app_name not in get_installed_apps():
  914. throw(_("App {0} is not installed").format(app_name), AppNotInstalledError)
  915. modulename = '.'.join(method_string.split('.')[:-1])
  916. methodname = method_string.split('.')[-1]
  917. return getattr(get_module(modulename), methodname)
  918. def call(fn, *args, **kwargs):
  919. """Call a function and match arguments."""
  920. if isinstance(fn, string_types):
  921. fn = get_attr(fn)
  922. newargs = get_newargs(fn, kwargs)
  923. return fn(*args, **newargs)
  924. def get_newargs(fn, kwargs):
  925. if hasattr(fn, 'fnargs'):
  926. fnargs = fn.fnargs
  927. else:
  928. try:
  929. fnargs, varargs, varkw, defaults = inspect.getargspec(fn)
  930. except ValueError:
  931. fnargs = inspect.getfullargspec(fn).args
  932. varargs = inspect.getfullargspec(fn).varargs
  933. varkw = inspect.getfullargspec(fn).varkw
  934. defaults = inspect.getfullargspec(fn).defaults
  935. newargs = {}
  936. for a in kwargs:
  937. if (a in fnargs) or varkw:
  938. newargs[a] = kwargs.get(a)
  939. newargs.pop("ignore_permissions", None)
  940. newargs.pop("flags", None)
  941. return newargs
  942. def make_property_setter(args, ignore_validate=False, validate_fields_for_doctype=True):
  943. """Create a new **Property Setter** (for overriding DocType and DocField properties).
  944. If doctype is not specified, it will create a property setter for all fields with the
  945. given fieldname"""
  946. args = _dict(args)
  947. if not args.doctype_or_field:
  948. args.doctype_or_field = 'DocField'
  949. if not args.property_type:
  950. args.property_type = db.get_value('DocField',
  951. {'parent': 'DocField', 'fieldname': args.property}, 'fieldtype') or 'Data'
  952. if not args.doctype:
  953. doctype_list = db.sql_list('select distinct parent from tabDocField where fieldname=%s', args.fieldname)
  954. else:
  955. doctype_list = [args.doctype]
  956. for doctype in doctype_list:
  957. if not args.property_type:
  958. args.property_type = db.get_value('DocField',
  959. {'parent': doctype, 'fieldname': args.fieldname}, 'fieldtype') or 'Data'
  960. ps = get_doc({
  961. 'doctype': "Property Setter",
  962. 'doctype_or_field': args.doctype_or_field,
  963. 'doc_type': doctype,
  964. 'field_name': args.fieldname,
  965. 'row_name': args.row_name,
  966. 'property': args.property,
  967. 'value': args.value,
  968. 'property_type': args.property_type or "Data",
  969. '__islocal': 1
  970. })
  971. ps.flags.ignore_validate = ignore_validate
  972. ps.flags.validate_fields_for_doctype = validate_fields_for_doctype
  973. ps.validate_fieldtype_change()
  974. ps.insert()
  975. def import_doc(path):
  976. """Import a file using Data Import."""
  977. from frappe.core.doctype.data_import.data_import import import_doc
  978. import_doc(path)
  979. def copy_doc(doc, ignore_no_copy=True):
  980. """ No_copy fields also get copied."""
  981. import copy
  982. def remove_no_copy_fields(d):
  983. for df in d.meta.get("fields", {"no_copy": 1}):
  984. if hasattr(d, df.fieldname):
  985. d.set(df.fieldname, None)
  986. fields_to_clear = ['name', 'owner', 'creation', 'modified', 'modified_by']
  987. if not local.flags.in_test:
  988. fields_to_clear.append("docstatus")
  989. if not isinstance(doc, dict):
  990. d = doc.as_dict()
  991. else:
  992. d = doc
  993. newdoc = get_doc(copy.deepcopy(d))
  994. newdoc.set("__islocal", 1)
  995. for fieldname in (fields_to_clear + ['amended_from', 'amendment_date']):
  996. newdoc.set(fieldname, None)
  997. if not ignore_no_copy:
  998. remove_no_copy_fields(newdoc)
  999. for i, d in enumerate(newdoc.get_all_children()):
  1000. d.set("__islocal", 1)
  1001. for fieldname in fields_to_clear:
  1002. d.set(fieldname, None)
  1003. if not ignore_no_copy:
  1004. remove_no_copy_fields(d)
  1005. return newdoc
  1006. def compare(val1, condition, val2):
  1007. """Compare two values using `frappe.utils.compare`
  1008. `condition` could be:
  1009. - "^"
  1010. - "in"
  1011. - "not in"
  1012. - "="
  1013. - "!="
  1014. - ">"
  1015. - "<"
  1016. - ">="
  1017. - "<="
  1018. - "not None"
  1019. - "None"
  1020. """
  1021. import frappe.utils
  1022. return frappe.utils.compare(val1, condition, val2)
  1023. def respond_as_web_page(title, html, success=None, http_status_code=None, context=None,
  1024. indicator_color=None, primary_action='/', primary_label = None, fullpage=False,
  1025. width=None, template='message'):
  1026. """Send response as a web page with a message rather than JSON. Used to show permission errors etc.
  1027. :param title: Page title and heading.
  1028. :param message: Message to be shown.
  1029. :param success: Alert message.
  1030. :param http_status_code: HTTP status code
  1031. :param context: web template context
  1032. :param indicator_color: color of indicator in title
  1033. :param primary_action: route on primary button (default is `/`)
  1034. :param primary_label: label on primary button (default is "Home")
  1035. :param fullpage: hide header / footer
  1036. :param width: Width of message in pixels
  1037. :param template: Optionally pass view template
  1038. """
  1039. local.message_title = title
  1040. local.message = html
  1041. local.response['type'] = 'page'
  1042. local.response['route'] = template
  1043. local.no_cache = 1
  1044. if http_status_code:
  1045. local.response['http_status_code'] = http_status_code
  1046. if not context:
  1047. context = {}
  1048. if not indicator_color:
  1049. if success:
  1050. indicator_color = 'green'
  1051. elif http_status_code and http_status_code > 300:
  1052. indicator_color = 'red'
  1053. else:
  1054. indicator_color = 'blue'
  1055. context['indicator_color'] = indicator_color
  1056. context['primary_label'] = primary_label
  1057. context['primary_action'] = primary_action
  1058. context['error_code'] = http_status_code
  1059. context['fullpage'] = fullpage
  1060. if width:
  1061. context['card_width'] = width
  1062. local.response['context'] = context
  1063. def redirect_to_message(title, html, http_status_code=None, context=None, indicator_color=None):
  1064. """Redirects to /message?id=random
  1065. Similar to respond_as_web_page, but used to 'redirect' and show message pages like success, failure, etc. with a detailed message
  1066. :param title: Page title and heading.
  1067. :param message: Message to be shown.
  1068. :param http_status_code: HTTP status code.
  1069. Example Usage:
  1070. frappe.redirect_to_message(_('Thank you'), "<div><p>You will receive an email at test@example.com</p></div>")
  1071. """
  1072. message_id = generate_hash(length=8)
  1073. message = {
  1074. 'context': context or {},
  1075. 'http_status_code': http_status_code or 200
  1076. }
  1077. message['context'].update({
  1078. 'header': title,
  1079. 'title': title,
  1080. 'message': html
  1081. })
  1082. if indicator_color:
  1083. message['context'].update({
  1084. "indicator_color": indicator_color
  1085. })
  1086. cache().set_value("message_id:{0}".format(message_id), message, expires_in_sec=60)
  1087. location = '/message?id={0}'.format(message_id)
  1088. if not getattr(local, 'is_ajax', False):
  1089. local.response["type"] = "redirect"
  1090. local.response["location"] = location
  1091. else:
  1092. return location
  1093. def build_match_conditions(doctype, as_condition=True):
  1094. """Return match (User permissions) for given doctype as list or SQL."""
  1095. import frappe.desk.reportview
  1096. return frappe.desk.reportview.build_match_conditions(doctype, as_condition=as_condition)
  1097. def get_list(doctype, *args, **kwargs):
  1098. """List database query via `frappe.model.db_query`. Will also check for permissions.
  1099. :param doctype: DocType on which query is to be made.
  1100. :param fields: List of fields or `*`.
  1101. :param filters: List of filters (see example).
  1102. :param order_by: Order By e.g. `modified desc`.
  1103. :param limit_page_start: Start results at record #. Default 0.
  1104. :param limit_page_length: No of records in the page. Default 20.
  1105. Example usage:
  1106. # simple dict filter
  1107. frappe.get_list("ToDo", fields=["name", "description"], filters = {"owner":"test@example.com"})
  1108. # filter as a list of lists
  1109. frappe.get_list("ToDo", fields="*", filters = [["modified", ">", "2014-01-01"]])
  1110. # filter as a list of dicts
  1111. frappe.get_list("ToDo", fields="*", filters = {"description": ("like", "test%")})
  1112. """
  1113. import frappe.model.db_query
  1114. return frappe.model.db_query.DatabaseQuery(doctype).execute(*args, **kwargs)
  1115. def get_all(doctype, *args, **kwargs):
  1116. """List database query via `frappe.model.db_query`. Will **not** check for permissions.
  1117. Parameters are same as `frappe.get_list`
  1118. :param doctype: DocType on which query is to be made.
  1119. :param fields: List of fields or `*`. Default is: `["name"]`.
  1120. :param filters: List of filters (see example).
  1121. :param order_by: Order By e.g. `modified desc`.
  1122. :param limit_start: Start results at record #. Default 0.
  1123. :param limit_page_length: No of records in the page. Default 20.
  1124. Example usage:
  1125. # simple dict filter
  1126. frappe.get_all("ToDo", fields=["name", "description"], filters = {"owner":"test@example.com"})
  1127. # filter as a list of lists
  1128. frappe.get_all("ToDo", fields=["*"], filters = [["modified", ">", "2014-01-01"]])
  1129. # filter as a list of dicts
  1130. frappe.get_all("ToDo", fields=["*"], filters = {"description": ("like", "test%")})
  1131. """
  1132. kwargs["ignore_permissions"] = True
  1133. if not "limit_page_length" in kwargs:
  1134. kwargs["limit_page_length"] = 0
  1135. return get_list(doctype, *args, **kwargs)
  1136. def get_value(*args, **kwargs):
  1137. """Returns a document property or list of properties.
  1138. Alias for `frappe.db.get_value`
  1139. :param doctype: DocType name.
  1140. :param filters: Filters like `{"x":"y"}` or name of the document. `None` if Single DocType.
  1141. :param fieldname: Column name.
  1142. :param ignore: Don't raise exception if table, column is missing.
  1143. :param as_dict: Return values as dict.
  1144. :param debug: Print query in error log.
  1145. """
  1146. return db.get_value(*args, **kwargs)
  1147. def as_json(obj, indent=1):
  1148. from frappe.utils.response import json_handler
  1149. return json.dumps(obj, indent=indent, sort_keys=True, default=json_handler, separators=(',', ': '))
  1150. def are_emails_muted():
  1151. from frappe.utils import cint
  1152. return flags.mute_emails or cint(conf.get("mute_emails") or 0) or False
  1153. def get_test_records(doctype):
  1154. """Returns list of objects from `test_records.json` in the given doctype's folder."""
  1155. from frappe.modules import get_doctype_module, get_module_path
  1156. path = os.path.join(get_module_path(get_doctype_module(doctype)), "doctype", scrub(doctype), "test_records.json")
  1157. if os.path.exists(path):
  1158. with open(path, "r") as f:
  1159. return json.loads(f.read())
  1160. else:
  1161. return []
  1162. def format_value(*args, **kwargs):
  1163. """Format value with given field properties.
  1164. :param value: Value to be formatted.
  1165. :param df: (Optional) DocField object with properties `fieldtype`, `options` etc."""
  1166. import frappe.utils.formatters
  1167. return frappe.utils.formatters.format_value(*args, **kwargs)
  1168. def format(*args, **kwargs):
  1169. """Format value with given field properties.
  1170. :param value: Value to be formatted.
  1171. :param df: (Optional) DocField object with properties `fieldtype`, `options` etc."""
  1172. import frappe.utils.formatters
  1173. return frappe.utils.formatters.format_value(*args, **kwargs)
  1174. def get_print(doctype=None, name=None, print_format=None, style=None,
  1175. html=None, as_pdf=False, doc=None, output=None, no_letterhead=0, password=None):
  1176. """Get Print Format for given document.
  1177. :param doctype: DocType of document.
  1178. :param name: Name of document.
  1179. :param print_format: Print Format name. Default 'Standard',
  1180. :param style: Print Format style.
  1181. :param as_pdf: Return as PDF. Default False.
  1182. :param password: Password to encrypt the pdf with. Default None"""
  1183. from frappe.website.render import build_page
  1184. from frappe.utils.pdf import get_pdf
  1185. local.form_dict.doctype = doctype
  1186. local.form_dict.name = name
  1187. local.form_dict.format = print_format
  1188. local.form_dict.style = style
  1189. local.form_dict.doc = doc
  1190. local.form_dict.no_letterhead = no_letterhead
  1191. options = None
  1192. if password:
  1193. options = {'password': password}
  1194. if not html:
  1195. html = build_page("printview")
  1196. if as_pdf:
  1197. return get_pdf(html, output = output, options = options)
  1198. else:
  1199. return html
  1200. def attach_print(doctype, name, file_name=None, print_format=None,
  1201. style=None, html=None, doc=None, lang=None, print_letterhead=True, password=None):
  1202. from frappe.utils import scrub_urls
  1203. if not file_name: file_name = name
  1204. file_name = file_name.replace(' ','').replace('/','-')
  1205. print_settings = db.get_singles_dict("Print Settings")
  1206. _lang = local.lang
  1207. #set lang as specified in print format attachment
  1208. if lang: local.lang = lang
  1209. local.flags.ignore_print_permissions = True
  1210. no_letterhead = not print_letterhead
  1211. kwargs = dict(
  1212. print_format=print_format,
  1213. style=style,
  1214. html=html,
  1215. doc=doc,
  1216. no_letterhead=no_letterhead,
  1217. password=password
  1218. )
  1219. content = ''
  1220. if int(print_settings.send_print_as_pdf or 0):
  1221. ext = ".pdf"
  1222. kwargs["as_pdf"] = True
  1223. content = get_print(doctype, name, **kwargs)
  1224. else:
  1225. ext = ".html"
  1226. content = scrub_urls(get_print(doctype, name, **kwargs)).encode('utf-8')
  1227. out = {
  1228. "fname": file_name + ext,
  1229. "fcontent": content
  1230. }
  1231. local.flags.ignore_print_permissions = False
  1232. #reset lang to original local lang
  1233. local.lang = _lang
  1234. return out
  1235. def publish_progress(*args, **kwargs):
  1236. """Show the user progress for a long request
  1237. :param percent: Percent progress
  1238. :param title: Title
  1239. :param doctype: Optional, for document type
  1240. :param docname: Optional, for document name
  1241. :param description: Optional description
  1242. """
  1243. import frappe.realtime
  1244. return frappe.realtime.publish_progress(*args, **kwargs)
  1245. def publish_realtime(*args, **kwargs):
  1246. """Publish real-time updates
  1247. :param event: Event name, like `task_progress` etc.
  1248. :param message: JSON message object. For async must contain `task_id`
  1249. :param room: Room in which to publish update (default entire site)
  1250. :param user: Transmit to user
  1251. :param doctype: Transmit to doctype, docname
  1252. :param docname: Transmit to doctype, docname
  1253. :param after_commit: (default False) will emit after current transaction is committed
  1254. """
  1255. import frappe.realtime
  1256. return frappe.realtime.publish_realtime(*args, **kwargs)
  1257. def local_cache(namespace, key, generator, regenerate_if_none=False):
  1258. """A key value store for caching within a request
  1259. :param namespace: frappe.local.cache[namespace]
  1260. :param key: frappe.local.cache[namespace][key] used to retrieve value
  1261. :param generator: method to generate a value if not found in store
  1262. """
  1263. if namespace not in local.cache:
  1264. local.cache[namespace] = {}
  1265. if key not in local.cache[namespace]:
  1266. local.cache[namespace][key] = generator()
  1267. elif local.cache[namespace][key]==None and regenerate_if_none:
  1268. # if key exists but the previous result was None
  1269. local.cache[namespace][key] = generator()
  1270. return local.cache[namespace][key]
  1271. def enqueue(*args, **kwargs):
  1272. '''
  1273. Enqueue method to be executed using a background worker
  1274. :param method: method string or method object
  1275. :param queue: (optional) should be either long, default or short
  1276. :param timeout: (optional) should be set according to the functions
  1277. :param event: this is passed to enable clearing of jobs from queues
  1278. :param is_async: (optional) if is_async=False, the method is executed immediately, else via a worker
  1279. :param job_name: (optional) can be used to name an enqueue call, which can be used to prevent duplicate calls
  1280. :param kwargs: keyword arguments to be passed to the method
  1281. '''
  1282. import frappe.utils.background_jobs
  1283. return frappe.utils.background_jobs.enqueue(*args, **kwargs)
  1284. def enqueue_doc(*args, **kwargs):
  1285. '''
  1286. Enqueue method to be executed using a background worker
  1287. :param doctype: DocType of the document on which you want to run the event
  1288. :param name: Name of the document on which you want to run the event
  1289. :param method: method string or method object
  1290. :param queue: (optional) should be either long, default or short
  1291. :param timeout: (optional) should be set according to the functions
  1292. :param kwargs: keyword arguments to be passed to the method
  1293. '''
  1294. import frappe.utils.background_jobs
  1295. return frappe.utils.background_jobs.enqueue_doc(*args, **kwargs)
  1296. def get_doctype_app(doctype):
  1297. def _get_doctype_app():
  1298. doctype_module = local.db.get_value("DocType", doctype, "module")
  1299. return local.module_app[scrub(doctype_module)]
  1300. return local_cache("doctype_app", doctype, generator=_get_doctype_app)
  1301. loggers = {}
  1302. log_level = None
  1303. def logger(module=None, with_more_info=False, allow_site=True, filter=None, max_size=100_000, file_count=20):
  1304. '''Returns a python logger that uses StreamHandler'''
  1305. from frappe.utils.logger import get_logger
  1306. return get_logger(module=module, with_more_info=with_more_info, allow_site=allow_site, filter=filter, max_size=max_size, file_count=file_count)
  1307. def log_error(message=None, title=_("Error")):
  1308. '''Log error to Error Log'''
  1309. # AI ALERT:
  1310. # the title and message may be swapped
  1311. # the better API for this is log_error(title, message), and used in many cases this way
  1312. # this hack tries to be smart about whats a title (single line ;-)) and fixes it
  1313. if message:
  1314. if '\n' in title:
  1315. error, title = title, message
  1316. else:
  1317. error = message
  1318. else:
  1319. error = get_traceback()
  1320. return get_doc(dict(doctype='Error Log', error=as_unicode(error),
  1321. method=title)).insert(ignore_permissions=True)
  1322. def get_desk_link(doctype, name):
  1323. html = '<a href="/app/Form/{doctype}/{name}" style="font-weight: bold;">{doctype_local} {name}</a>'
  1324. return html.format(
  1325. doctype=doctype,
  1326. name=name,
  1327. doctype_local=_(doctype)
  1328. )
  1329. def bold(text):
  1330. return '<b>{0}</b>'.format(text)
  1331. def safe_eval(code, eval_globals=None, eval_locals=None):
  1332. '''A safer `eval`'''
  1333. whitelisted_globals = {
  1334. "int": int,
  1335. "float": float,
  1336. "long": int,
  1337. "round": round
  1338. }
  1339. if '__' in code:
  1340. throw('Illegal rule {0}. Cannot use "__"'.format(bold(code)))
  1341. if not eval_globals:
  1342. eval_globals = {}
  1343. eval_globals['__builtins__'] = {}
  1344. eval_globals.update(whitelisted_globals)
  1345. return eval(code, eval_globals, eval_locals)
  1346. def get_system_settings(key):
  1347. if key not in local.system_settings:
  1348. local.system_settings.update({key: db.get_single_value('System Settings', key)})
  1349. return local.system_settings.get(key)
  1350. def get_active_domains():
  1351. from frappe.core.doctype.domain_settings.domain_settings import get_active_domains
  1352. return get_active_domains()
  1353. def get_version(doctype, name, limit=None, head=False, raise_err=True):
  1354. '''
  1355. Returns a list of version information of a given DocType.
  1356. Note: Applicable only if DocType has changes tracked.
  1357. Example
  1358. >>> frappe.get_version('User', 'foobar@gmail.com')
  1359. >>>
  1360. [
  1361. {
  1362. "version": [version.data], # Refer Version DocType get_diff method and data attribute
  1363. "user": "admin@gmail.com", # User that created this version
  1364. "creation": <datetime.datetime> # Creation timestamp of that object.
  1365. }
  1366. ]
  1367. '''
  1368. meta = get_meta(doctype)
  1369. if meta.track_changes:
  1370. names = db.get_all('Version', filters={
  1371. 'ref_doctype': doctype,
  1372. 'docname': name,
  1373. 'order_by': 'creation' if head else None,
  1374. 'limit': limit
  1375. }, as_list=1)
  1376. from frappe.chat.util import squashify, dictify, safe_json_loads
  1377. versions = []
  1378. for name in names:
  1379. name = squashify(name)
  1380. doc = get_doc('Version', name)
  1381. data = doc.data
  1382. data = safe_json_loads(data)
  1383. data = dictify(dict(
  1384. version=data,
  1385. user=doc.owner,
  1386. creation=doc.creation
  1387. ))
  1388. versions.append(data)
  1389. return versions
  1390. else:
  1391. if raise_err:
  1392. raise ValueError(_('{0} has no versions tracked.').format(doctype))
  1393. @whitelist(allow_guest=True)
  1394. def ping():
  1395. return "pong"
  1396. def safe_encode(param, encoding='utf-8'):
  1397. try:
  1398. param = param.encode(encoding)
  1399. except Exception:
  1400. pass
  1401. return param
  1402. def safe_decode(param, encoding='utf-8'):
  1403. try:
  1404. param = param.decode(encoding)
  1405. except Exception:
  1406. pass
  1407. return param
  1408. def parse_json(val):
  1409. from frappe.utils import parse_json
  1410. return parse_json(val)
  1411. def mock(type, size=1, locale='en'):
  1412. results = []
  1413. fake = faker.Faker(locale)
  1414. if type not in dir(fake):
  1415. raise ValueError('Not a valid mock type.')
  1416. else:
  1417. for i in range(size):
  1418. data = getattr(fake, type)()
  1419. results.append(data)
  1420. from frappe.chat.util import squashify
  1421. return squashify(results)
  1422. def validate_and_sanitize_search_inputs(fn):
  1423. from frappe.desk.search import validate_and_sanitize_search_inputs as func
  1424. return func(fn)