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.
 
 
 
 
 
 

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