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.
 
 
 
 
 
 

1831 line
54 KiB

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