選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

1772 行
52 KiB

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