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.
 
 
 
 
 
 

977 lines
30 KiB

  1. # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. """
  4. globals attached to frappe module
  5. + some utility functions that should probably be moved
  6. """
  7. from __future__ import unicode_literals
  8. from werkzeug.local import Local, release_local
  9. import os, importlib, inspect, logging, json
  10. # public
  11. from frappe.__version__ import __version__
  12. from .exceptions import *
  13. from .utils.jinja import get_jenv, get_template, render_template
  14. local = Local()
  15. class _dict(dict):
  16. """dict like object that exposes keys as attributes"""
  17. def __getattr__(self, key):
  18. ret = self.get(key)
  19. if not ret and key.startswith("__"):
  20. raise AttributeError()
  21. return ret
  22. def __setattr__(self, key, value):
  23. self[key] = value
  24. def __getstate__(self):
  25. return self
  26. def __setstate__(self, d):
  27. self.update(d)
  28. def update(self, d):
  29. """update and return self -- the missing dict feature in python"""
  30. super(_dict, self).update(d)
  31. return self
  32. def copy(self):
  33. return _dict(dict(self).copy())
  34. def _(msg):
  35. """Returns translated string in current lang, if exists."""
  36. if local.lang == "en":
  37. return msg
  38. from frappe.translate import get_full_dict
  39. return get_full_dict(local.lang).get(msg, msg)
  40. def get_lang_dict(fortype, name=None):
  41. """Returns the translated language dict for the given type and name.
  42. :param fortype: must be one of `doctype`, `page`, `report`, `include`, `jsfile`, `boot`
  43. :param name: name of the document for which assets are to be returned."""
  44. if local.lang=="en":
  45. return {}
  46. from frappe.translate import get_dict
  47. return get_dict(fortype, name)
  48. def set_user_lang(user, user_language=None):
  49. """Guess and set user language for the session. `frappe.local.lang`"""
  50. from frappe.translate import get_user_lang
  51. local.lang = get_user_lang(user)
  52. # local-globals
  53. db = local("db")
  54. conf = local("conf")
  55. form = form_dict = local("form_dict")
  56. request = local("request")
  57. request_method = local("request_method")
  58. response = local("response")
  59. session = local("session")
  60. user = local("user")
  61. flags = local("flags")
  62. error_log = local("error_log")
  63. debug_log = local("debug_log")
  64. message_log = local("message_log")
  65. lang = local("lang")
  66. def init(site, sites_path=None):
  67. """Initialize frappe for the current site. Reset thread locals `frappe.local`"""
  68. if getattr(local, "initialised", None):
  69. return
  70. if not sites_path:
  71. sites_path = '.'
  72. local.error_log = []
  73. local.message_log = []
  74. local.debug_log = []
  75. local.flags = _dict({
  76. "ran_schedulers": [],
  77. "redirect_location": "",
  78. "in_install_db": False,
  79. "in_install_app": False,
  80. "in_import": False,
  81. "in_test": False,
  82. "mute_messages": False,
  83. "ignore_links": False,
  84. "mute_emails": False,
  85. "has_dataurl": False,
  86. })
  87. local.rollback_observers = []
  88. local.test_objects = {}
  89. local.site = site
  90. local.sites_path = sites_path
  91. local.site_path = os.path.join(sites_path, site)
  92. local.request_method = request.method if request else None
  93. local.request_ip = None
  94. local.response = _dict({"docs":[]})
  95. local.conf = _dict(get_site_config())
  96. local.lang = local.conf.lang or "en"
  97. local.module_app = None
  98. local.app_modules = None
  99. local.user = None
  100. local.user_obj = None
  101. local.role_permissions = {}
  102. local.valid_columns = {}
  103. local.new_doc_templates = {}
  104. local.jenv = None
  105. local.jloader =None
  106. local.cache = {}
  107. setup_module_map()
  108. local.initialised = True
  109. def connect(site=None, db_name=None):
  110. """Connect to site database instance.
  111. :param site: If site is given, calls `frappe.init`.
  112. :param db_name: Optional. Will use from `site_config.json`."""
  113. from database import Database
  114. if site:
  115. init(site)
  116. local.db = Database(user=db_name or local.conf.db_name)
  117. local.form_dict = _dict()
  118. local.session = _dict()
  119. set_user("Administrator")
  120. def get_site_config(sites_path=None, site_path=None):
  121. """Returns `site_config.json` combined with `sites/common_site_config.json`.
  122. `site_config` is a set of site wide settings like database name, password, email etc."""
  123. config = {}
  124. sites_path = sites_path or getattr(local, "sites_path", None)
  125. site_path = site_path or getattr(local, "site_path", None)
  126. if sites_path:
  127. common_site_config = os.path.join(sites_path, "common_site_config.json")
  128. if os.path.exists(common_site_config):
  129. config.update(get_file_json(common_site_config))
  130. if site_path:
  131. site_config = os.path.join(site_path, "site_config.json")
  132. if os.path.exists(site_config):
  133. config.update(get_file_json(site_config))
  134. return _dict(config)
  135. def destroy():
  136. """Closes connection and releases werkzeug local."""
  137. if db:
  138. db.close()
  139. release_local(local)
  140. # memcache
  141. redis_server = None
  142. def cache():
  143. """Returns memcache connection."""
  144. global redis_server
  145. if not redis_server:
  146. from frappe.utils.redis_wrapper import RedisWrapper
  147. redis_server = RedisWrapper.from_url(conf.get("cache_redis_server") or "redis://localhost:11311")
  148. return redis_server
  149. def get_traceback():
  150. """Returns error traceback."""
  151. import utils
  152. return utils.get_traceback()
  153. def errprint(msg):
  154. """Log error. This is sent back as `exc` in response.
  155. :param msg: Message."""
  156. from utils import cstr
  157. if not request or (not "cmd" in local.form_dict):
  158. print cstr(msg)
  159. error_log.append(cstr(msg))
  160. def log(msg):
  161. """Add to `debug_log`.
  162. :param msg: Message."""
  163. if not request:
  164. if conf.get("logging") or False:
  165. print repr(msg)
  166. from utils import cstr
  167. debug_log.append(cstr(msg))
  168. def msgprint(msg, small=0, raise_exception=0, as_table=False):
  169. """Print a message to the user (via HTTP response).
  170. Messages are sent in the `__server_messages` property in the
  171. response JSON and shown in a pop-up / modal.
  172. :param msg: Message.
  173. :param small: [optional] Show as a floating message in the footer.
  174. :param raise_exception: [optional] Raise given exception and show message.
  175. :param as_table: [optional] If `msg` is a list of lists, render as HTML table.
  176. """
  177. from utils import cstr, encode
  178. def _raise_exception():
  179. if raise_exception:
  180. if flags.rollback_on_exception:
  181. db.rollback()
  182. import inspect
  183. if inspect.isclass(raise_exception) and issubclass(raise_exception, Exception):
  184. raise raise_exception, encode(msg)
  185. else:
  186. raise ValidationError, encode(msg)
  187. if flags.mute_messages:
  188. _raise_exception()
  189. return
  190. if as_table and type(msg) in (list, tuple):
  191. msg = '<table border="1px" style="border-collapse: collapse" cellpadding="2px">' + ''.join(['<tr>'+''.join(['<td>%s</td>' % c for c in r])+'</tr>' for r in msg]) + '</table>'
  192. if flags.print_messages:
  193. print "Message: " + repr(msg)
  194. message_log.append((small and '__small:' or '')+cstr(msg or ''))
  195. _raise_exception()
  196. def throw(msg, exc=ValidationError):
  197. """Throw execption and show message (`msgprint`).
  198. :param msg: Message.
  199. :param exc: Exception class. Default `frappe.ValidationError`"""
  200. msgprint(msg, raise_exception=exc)
  201. def create_folder(path, with_init=False):
  202. """Create a folder in the given path and add an `__init__.py` file (optional).
  203. :param path: Folder path.
  204. :param with_init: Create `__init__.py` in the new folder."""
  205. from frappe.utils import touch_file
  206. if not os.path.exists(path):
  207. os.makedirs(path)
  208. if with_init:
  209. touch_file(os.path.join(path, "__init__.py"))
  210. def set_user(username):
  211. """Set current user.
  212. :param username: **User** name to set as current user."""
  213. local.session.user = username
  214. local.session.sid = username
  215. local.cache = {}
  216. local.form_dict = _dict()
  217. local.jenv = None
  218. local.session.data = _dict()
  219. local.role_permissions = {}
  220. local.new_doc_templates = {}
  221. local.user_obj = None
  222. def get_user():
  223. from frappe.utils.user import User
  224. if not local.user_obj:
  225. local.user_obj = User(local.session.user)
  226. return local.user_obj
  227. def get_roles(username=None):
  228. """Returns roles of current user."""
  229. if not local.session:
  230. return ["Guest"]
  231. if username:
  232. import frappe.utils.user
  233. return frappe.utils.user.get_roles(username)
  234. else:
  235. return get_user().get_roles()
  236. def get_request_header(key, default=None):
  237. """Return HTTP request header.
  238. :param key: HTTP header key.
  239. :param default: Default value."""
  240. return request.headers.get(key, default)
  241. def sendmail(recipients=(), sender="", subject="No Subject", message="No Message",
  242. as_markdown=False, bulk=False, reference_doctype=None, reference_name=None,
  243. unsubscribe_method=None, unsubscribe_params=None, unsubscribe_message=None,
  244. attachments=None, content=None, doctype=None, name=None, reply_to=None,
  245. cc=(), message_id=None, as_bulk=False, send_after=None):
  246. """Send email using user's default **Email Account** or global default **Email Account**.
  247. :param recipients: List of recipients.
  248. :param sender: Email sender. Default is current user.
  249. :param subject: Email Subject.
  250. :param message: (or `content`) Email Content.
  251. :param as_markdown: Convert content markdown to HTML.
  252. :param bulk: Send via scheduled email sender **Bulk Email**. Don't send immediately.
  253. :param reference_doctype: (or `doctype`) Append as communication to this DocType.
  254. :param reference_name: (or `name`) Append as communication to this document name.
  255. :param unsubscribe_method: Unsubscribe url with options email, doctype, name. e.g. `/api/method/unsubscribe`
  256. :param unsubscribe_params: Unsubscribe paramaters to be loaded on the unsubscribe_method [optional] (dict).
  257. :param attachments: List of attachments.
  258. :param reply_to: Reply-To email id.
  259. :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.
  260. :param send_after: Send after the given datetime.
  261. """
  262. if bulk or as_bulk:
  263. import frappe.email.bulk
  264. frappe.email.bulk.send(recipients=recipients, sender=sender,
  265. subject=subject, message=content or message,
  266. reference_doctype = doctype or reference_doctype, reference_name = name or reference_name,
  267. unsubscribe_method=unsubscribe_method, unsubscribe_params=unsubscribe_params, unsubscribe_message=unsubscribe_message,
  268. attachments=attachments, reply_to=reply_to, cc=cc, message_id=message_id, send_after=send_after)
  269. else:
  270. import frappe.email
  271. if as_markdown:
  272. frappe.email.sendmail_md(recipients, sender=sender,
  273. subject=subject, msg=content or message, attachments=attachments, reply_to=reply_to,
  274. cc=cc, message_id=message_id)
  275. else:
  276. frappe.email.sendmail(recipients, sender=sender,
  277. subject=subject, msg=content or message, attachments=attachments, reply_to=reply_to,
  278. cc=cc, message_id=message_id)
  279. logger = None
  280. whitelisted = []
  281. guest_methods = []
  282. def whitelist(allow_guest=False):
  283. """
  284. Decorator for whitelisting a function and making it accessible via HTTP.
  285. Standard request will be `/api/method/[path.to.method]`
  286. :param allow_guest: Allow non logged-in user to access this method.
  287. Use as:
  288. @frappe.whitelist()
  289. def myfunc(param1, param2):
  290. pass
  291. """
  292. def innerfn(fn):
  293. global whitelisted, guest_methods
  294. whitelisted.append(fn)
  295. if allow_guest:
  296. guest_methods.append(fn)
  297. return fn
  298. return innerfn
  299. def only_for(roles):
  300. """Raise `frappe.PermissionError` if the user does not have any of the given **Roles**.
  301. :param roles: List of roles to check."""
  302. if not isinstance(roles, (tuple, list)):
  303. roles = (roles,)
  304. roles = set(roles)
  305. myroles = set(get_roles())
  306. if not roles.intersection(myroles):
  307. raise PermissionError
  308. def clear_cache(user=None, doctype=None):
  309. """Clear **User**, **DocType** or global cache.
  310. :param user: If user is given, only user cache is cleared.
  311. :param doctype: If doctype is given, only DocType cache is cleared."""
  312. import frappe.sessions
  313. if doctype:
  314. import frappe.model.meta
  315. frappe.model.meta.clear_cache(doctype)
  316. reset_metadata_version()
  317. elif user:
  318. frappe.sessions.clear_cache(user)
  319. else: # everything
  320. import translate
  321. frappe.sessions.clear_cache()
  322. translate.clear_cache()
  323. reset_metadata_version()
  324. frappe.local.cache = {}
  325. for fn in frappe.get_hooks("clear_cache"):
  326. get_attr(fn)()
  327. frappe.local.role_permissions = {}
  328. def has_permission(doctype, ptype="read", doc=None, user=None, verbose=False):
  329. """Raises `frappe.PermissionError` if not permitted.
  330. :param doctype: DocType for which permission is to be check.
  331. :param ptype: Permission type (`read`, `write`, `create`, `submit`, `cancel`, `amend`). Default: `read`.
  332. :param doc: [optional] Checks User permissions for given doc.
  333. :param user: [optional] Check for given user. Default: current user."""
  334. import frappe.permissions
  335. return frappe.permissions.has_permission(doctype, ptype, doc=doc, verbose=verbose, user=user)
  336. def has_website_permission(doctype, ptype="read", doc=None, user=None, verbose=False):
  337. """Raises `frappe.PermissionError` if not permitted.
  338. :param doctype: DocType for which permission is to be check.
  339. :param ptype: Permission type (`read`, `write`, `create`, `submit`, `cancel`, `amend`). Default: `read`.
  340. :param doc: Checks User permissions for given doc.
  341. :param user: [optional] Check for given user. Default: current user."""
  342. if not user:
  343. user = session.user
  344. for method in (get_hooks("has_website_permission") or {}).get(doctype, []):
  345. if not call(get_attr(method), doc=doc, ptype=ptype, user=user, verbose=verbose):
  346. return False
  347. return True
  348. def is_table(doctype):
  349. """Returns True if `istable` property (indicating child Table) is set for given DocType."""
  350. tables = cache().get_value("is_table")
  351. if tables==None:
  352. tables = db.sql_list("select name from tabDocType where ifnull(istable,0)=1")
  353. cache().set_value("is_table", tables)
  354. return doctype in tables
  355. def get_precision(doctype, fieldname, currency=None, doc=None):
  356. """Get precision for a given field"""
  357. from frappe.model.meta import get_field_precision
  358. return get_field_precision(get_meta(doctype).get_field(fieldname), doc, currency)
  359. def generate_hash(txt=None):
  360. """Generates random hash for given text + current timestamp + random string."""
  361. import hashlib, time
  362. from .utils import random_string
  363. return hashlib.sha224((txt or "") + repr(time.time()) + repr(random_string(8))).hexdigest()
  364. def reset_metadata_version():
  365. """Reset `metadata_version` (Client (Javascript) build ID) hash."""
  366. v = generate_hash()
  367. cache().set_value("metadata_version", v)
  368. return v
  369. def new_doc(doctype, parent_doc=None, parentfield=None, as_dict=False):
  370. """Returns a new document of the given DocType with defaults set.
  371. :param doctype: DocType of the new document.
  372. :param parent_doc: [optional] add to parent document.
  373. :param parentfield: [optional] add against this `parentfield`."""
  374. from frappe.model.create_new import get_new_doc
  375. return get_new_doc(doctype, parent_doc, parentfield, as_dict=as_dict)
  376. def set_value(doctype, docname, fieldname, value):
  377. """Set document value. Calls `frappe.client.set_value`"""
  378. import frappe.client
  379. return frappe.client.set_value(doctype, docname, fieldname, value)
  380. def get_doc(arg1, arg2=None):
  381. """Return a `frappe.model.document.Document` object of the given type and name.
  382. :param arg1: DocType name as string **or** document JSON.
  383. :param arg2: [optional] Document name as string.
  384. Examples:
  385. # insert a new document
  386. todo = frappe.get_doc({"doctype":"ToDo", "description": "test"})
  387. tood.insert()
  388. # open an existing document
  389. todo = frappe.get_doc("ToDo", "TD0001")
  390. """
  391. import frappe.model.document
  392. return frappe.model.document.get_doc(arg1, arg2)
  393. def get_last_doc(doctype):
  394. """Get last created document of this type."""
  395. d = get_all(doctype, ["name"], order_by="creation desc", limit_page_length=1)
  396. if d:
  397. return get_doc(doctype, d[0].name)
  398. else:
  399. raise DoesNotExistError
  400. def get_single(doctype):
  401. """Return a `frappe.model.document.Document` object of the given Single doctype."""
  402. return get_doc(doctype, doctype)
  403. def get_meta(doctype, cached=True):
  404. """Get `frappe.model.meta.Meta` instance of given doctype name."""
  405. import frappe.model.meta
  406. return frappe.model.meta.get_meta(doctype, cached=cached)
  407. def delete_doc(doctype=None, name=None, force=0, ignore_doctypes=None, for_reload=False,
  408. ignore_permissions=False, flags=None):
  409. """Delete a document. Calls `frappe.model.delete_doc.delete_doc`.
  410. :param doctype: DocType of document to be delete.
  411. :param name: Name of document to be delete.
  412. :param force: Allow even if document is linked. Warning: This may lead to data integrity errors.
  413. :param ignore_doctypes: Ignore if child table is one of these.
  414. :param for_reload: Call `before_reload` trigger before deleting.
  415. :param ignore_permissions: Ignore user permissions."""
  416. import frappe.model.delete_doc
  417. frappe.model.delete_doc.delete_doc(doctype, name, force, ignore_doctypes, for_reload,
  418. ignore_permissions, flags)
  419. def delete_doc_if_exists(doctype, name):
  420. """Delete document if exists."""
  421. if db.exists(doctype, name):
  422. delete_doc(doctype, name)
  423. def reload_doctype(doctype):
  424. """Reload DocType from model (`[module]/[doctype]/[name]/[name].json`) files."""
  425. reload_doc(scrub(db.get_value("DocType", doctype, "module")), "doctype", scrub(doctype))
  426. def reload_doc(module, dt=None, dn=None, force=False):
  427. """Reload Document from model (`[module]/[doctype]/[name]/[name].json`) files.
  428. :param module: Module name.
  429. :param dt: DocType name.
  430. :param dn: Document name.
  431. :param force: Reload even if `modified` timestamp matches.
  432. """
  433. import frappe.modules
  434. return frappe.modules.reload_doc(module, dt, dn, force=force)
  435. def rename_doc(doctype, old, new, debug=0, force=False, merge=False, ignore_permissions=False):
  436. """Rename a document. Calls `frappe.model.rename_doc.rename_doc`"""
  437. from frappe.model.rename_doc import rename_doc
  438. return rename_doc(doctype, old, new, force=force, merge=merge, ignore_permissions=ignore_permissions)
  439. def get_module(modulename):
  440. """Returns a module object for given Python module name using `importlib.import_module`."""
  441. return importlib.import_module(modulename)
  442. def scrub(txt):
  443. """Returns sluggified string. e.g. `Sales Order` becomes `sales_order`."""
  444. return txt.replace(' ','_').replace('-', '_').lower()
  445. def unscrub(txt):
  446. """Returns titlified string. e.g. `sales_order` becomes `Sales Order`."""
  447. return txt.replace('_',' ').replace('-', ' ').title()
  448. def get_module_path(module, *joins):
  449. """Get the path of the given module name.
  450. :param module: Module name.
  451. :param *joins: Join additional path elements using `os.path.join`."""
  452. module = scrub(module)
  453. return get_pymodule_path(local.module_app[module] + "." + module, *joins)
  454. def get_app_path(app_name, *joins):
  455. """Return path of given app.
  456. :param app: App name.
  457. :param *joins: Join additional path elements using `os.path.join`."""
  458. return get_pymodule_path(app_name, *joins)
  459. def get_site_path(*joins):
  460. """Return path of current site.
  461. :param *joins: Join additional path elements using `os.path.join`."""
  462. return os.path.join(local.site_path, *joins)
  463. def get_pymodule_path(modulename, *joins):
  464. """Return path of given Python module name.
  465. :param modulename: Python module name.
  466. :param *joins: Join additional path elements using `os.path.join`."""
  467. joins = [scrub(part) for part in joins]
  468. return os.path.join(os.path.dirname(get_module(scrub(modulename)).__file__), *joins)
  469. def get_module_list(app_name):
  470. """Get list of modules for given all via `app/modules.txt`."""
  471. return get_file_items(os.path.join(os.path.dirname(get_module(app_name).__file__), "modules.txt"))
  472. def get_all_apps(with_frappe=False, with_internal_apps=True, sites_path=None):
  473. """Get list of all apps via `sites/apps.txt`."""
  474. if not sites_path:
  475. sites_path = local.sites_path
  476. apps = get_file_items(os.path.join(sites_path, "apps.txt"), raise_not_found=True)
  477. if with_internal_apps:
  478. apps.extend(get_file_items(os.path.join(local.site_path, "apps.txt")))
  479. if with_frappe:
  480. if "frappe" in apps:
  481. apps.remove("frappe")
  482. apps.insert(0, 'frappe')
  483. return apps
  484. def get_installed_apps(sort=False):
  485. """Get list of installed apps in current site."""
  486. if getattr(flags, "in_install_db", True):
  487. return []
  488. installed = json.loads(db.get_global("installed_apps") or "[]")
  489. if sort:
  490. installed = [app for app in get_all_apps(True) if app in installed]
  491. return installed
  492. def get_hooks(hook=None, default=None, app_name=None):
  493. """Get hooks via `app/hooks.py`
  494. :param hook: Name of the hook. Will gather all hooks for this name and return as a list.
  495. :param default: Default if no hook found.
  496. :param app_name: Filter by app."""
  497. def load_app_hooks(app_name=None):
  498. hooks = {}
  499. for app in [app_name] if app_name else get_installed_apps(sort=True):
  500. app = "frappe" if app=="webnotes" else app
  501. try:
  502. app_hooks = get_module(app + ".hooks")
  503. except ImportError:
  504. if local.flags.in_install_app:
  505. # if app is not installed while restoring
  506. # ignore it
  507. pass
  508. raise
  509. for key in dir(app_hooks):
  510. if not key.startswith("_"):
  511. append_hook(hooks, key, getattr(app_hooks, key))
  512. return hooks
  513. def append_hook(target, key, value):
  514. if isinstance(value, dict):
  515. target.setdefault(key, {})
  516. for inkey in value:
  517. append_hook(target[key], inkey, value[inkey])
  518. else:
  519. append_to_list(target, key, value)
  520. def append_to_list(target, key, value):
  521. target.setdefault(key, [])
  522. if not isinstance(value, list):
  523. value = [value]
  524. target[key].extend(value)
  525. if app_name:
  526. hooks = _dict(load_app_hooks(app_name))
  527. else:
  528. hooks = _dict(cache().get_value("app_hooks", load_app_hooks))
  529. if hook:
  530. return hooks.get(hook) or (default if default is not None else [])
  531. else:
  532. return hooks
  533. def setup_module_map():
  534. """Rebuild map of all modules (internal)."""
  535. _cache = cache()
  536. if conf.db_name:
  537. local.app_modules = _cache.get_value("app_modules")
  538. local.module_app = _cache.get_value("module_app")
  539. if not (local.app_modules and local.module_app):
  540. local.module_app, local.app_modules = {}, {}
  541. for app in get_all_apps(True):
  542. if app=="webnotes": app="frappe"
  543. local.app_modules.setdefault(app, [])
  544. for module in get_module_list(app):
  545. module = scrub(module)
  546. local.module_app[module] = app
  547. local.app_modules[app].append(module)
  548. if conf.db_name:
  549. _cache.set_value("app_modules", local.app_modules)
  550. _cache.set_value("module_app", local.module_app)
  551. def get_file_items(path, raise_not_found=False, ignore_empty_lines=True):
  552. """Returns items from text file as a list. Ignores empty lines."""
  553. import frappe.utils
  554. content = read_file(path, raise_not_found=raise_not_found)
  555. if content:
  556. content = frappe.utils.strip(content)
  557. return [p.strip() for p in content.splitlines() if (not ignore_empty_lines) or (p.strip() and not p.startswith("#"))]
  558. else:
  559. return []
  560. def get_file_json(path):
  561. """Read a file and return parsed JSON object."""
  562. with open(path, 'r') as f:
  563. return json.load(f)
  564. def read_file(path, raise_not_found=False):
  565. """Open a file and return its content as Unicode."""
  566. from frappe.utils import cstr
  567. if os.path.exists(path):
  568. with open(path, "r") as f:
  569. return cstr(f.read())
  570. elif raise_not_found:
  571. raise IOError("{} Not Found".format(path))
  572. else:
  573. return None
  574. def get_attr(method_string):
  575. """Get python method object from its name."""
  576. modulename = '.'.join(method_string.split('.')[:-1])
  577. methodname = method_string.split('.')[-1]
  578. return getattr(get_module(modulename), methodname)
  579. def call(fn, *args, **kwargs):
  580. """Call a function and match arguments."""
  581. if hasattr(fn, 'fnargs'):
  582. fnargs = fn.fnargs
  583. else:
  584. fnargs, varargs, varkw, defaults = inspect.getargspec(fn)
  585. newargs = {}
  586. for a in kwargs:
  587. if (a in fnargs) or varkw:
  588. newargs[a] = kwargs.get(a)
  589. if "flags" in newargs:
  590. del newargs["flags"]
  591. return fn(*args, **newargs)
  592. def make_property_setter(args, ignore_validate=False, validate_fields_for_doctype=True):
  593. """Create a new **Property Setter** (for overriding DocType and DocField properties)."""
  594. args = _dict(args)
  595. ps = get_doc({
  596. 'doctype': "Property Setter",
  597. 'doctype_or_field': args.doctype_or_field or "DocField",
  598. 'doc_type': args.doctype,
  599. 'field_name': args.fieldname,
  600. 'property': args.property,
  601. 'value': args.value,
  602. 'property_type': args.property_type or "Data",
  603. '__islocal': 1
  604. })
  605. ps.flags.ignore_validate = ignore_validate
  606. ps.flags.validate_fields_for_doctype = validate_fields_for_doctype
  607. ps.insert()
  608. def import_doc(path, ignore_links=False, ignore_insert=False, insert=False):
  609. """Import a file using Data Import Tool."""
  610. from frappe.core.page.data_import_tool import data_import_tool
  611. data_import_tool.import_doc(path, ignore_links=ignore_links, ignore_insert=ignore_insert, insert=insert)
  612. def copy_doc(doc, ignore_no_copy=True):
  613. """ No_copy fields also get copied."""
  614. import copy
  615. def remove_no_copy_fields(d):
  616. for df in d.meta.get("fields", {"no_copy": 1}):
  617. if hasattr(d, df.fieldname):
  618. d.set(df.fieldname, None)
  619. if not isinstance(doc, dict):
  620. d = doc.as_dict()
  621. else:
  622. d = doc
  623. newdoc = get_doc(copy.deepcopy(d))
  624. newdoc.name = None
  625. newdoc.set("__islocal", 1)
  626. newdoc.owner = None
  627. newdoc.creation = None
  628. newdoc.amended_from = None
  629. newdoc.amendment_date = None
  630. if not ignore_no_copy:
  631. remove_no_copy_fields(newdoc)
  632. for d in newdoc.get_all_children():
  633. d.name = None
  634. d.parent = None
  635. d.set("__islocal", 1)
  636. d.owner = None
  637. d.creation = None
  638. if not ignore_no_copy:
  639. remove_no_copy_fields(d)
  640. return newdoc
  641. def compare(val1, condition, val2):
  642. """Compare two values using `frappe.utils.compare`
  643. `condition` could be:
  644. - "^"
  645. - "in"
  646. - "not in"
  647. - "="
  648. - "!="
  649. - ">"
  650. - "<"
  651. - ">="
  652. - "<="
  653. - "not None"
  654. - "None"
  655. """
  656. import frappe.utils
  657. return frappe.utils.compare(val1, condition, val2)
  658. def respond_as_web_page(title, html, success=None, http_status_code=None):
  659. """Send response as a web page with a message rather than JSON. Used to show permission errors etc.
  660. :param title: Page title and heading.
  661. :param message: Message to be shown.
  662. :param success: Alert message.
  663. :param http_status_code: HTTP status code."""
  664. local.message_title = title
  665. local.message = html
  666. local.message_success = success
  667. local.response['type'] = 'page'
  668. local.response['page_name'] = 'message'
  669. if http_status_code:
  670. local.response['http_status_code'] = http_status_code
  671. def build_match_conditions(doctype, as_condition=True):
  672. """Return match (User permissions) for given doctype as list or SQL."""
  673. import frappe.desk.reportview
  674. return frappe.desk.reportview.build_match_conditions(doctype, as_condition)
  675. def get_list(doctype, *args, **kwargs):
  676. """List database query via `frappe.model.db_query`. Will also check for permissions.
  677. :param doctype: DocType on which query is to be made.
  678. :param fields: List of fields or `*`.
  679. :param filters: List of filters (see example).
  680. :param order_by: Order By e.g. `modified desc`.
  681. :param limit_page_start: Start results at record #. Default 0.
  682. :param limit_poge_length: No of records in the page. Default 20.
  683. Example usage:
  684. # simple dict filter
  685. frappe.get_list("ToDo", fields=["name", "description"], filters = {"owner":"test@example.com"})
  686. # filter as a list of lists
  687. frappe.get_list("ToDo", fields="*", filters = [["modified", ">", "2014-01-01"]])
  688. # filter as a list of dicts
  689. frappe.get_list("ToDo", fields="*", filters = {"description": ("like", "test%")})
  690. """
  691. import frappe.model.db_query
  692. return frappe.model.db_query.DatabaseQuery(doctype).execute(None, *args, **kwargs)
  693. def get_all(doctype, *args, **kwargs):
  694. """List database query via `frappe.model.db_query`. Will **not** check for conditions.
  695. Parameters are same as `frappe.get_list`
  696. :param doctype: DocType on which query is to be made.
  697. :param fields: List of fields or `*`. Default is: `["name"]`.
  698. :param filters: List of filters (see example).
  699. :param order_by: Order By e.g. `modified desc`.
  700. :param limit_page_start: Start results at record #. Default 0.
  701. :param limit_poge_length: No of records in the page. Default 20.
  702. Example usage:
  703. # simple dict filter
  704. frappe.get_all("ToDo", fields=["name", "description"], filters = {"owner":"test@example.com"})
  705. # filter as a list of lists
  706. frappe.get_all("ToDo", fields=["*"], filters = [["modified", ">", "2014-01-01"]])
  707. # filter as a list of dicts
  708. frappe.get_all("ToDo", fields=["*"], filters = {"description": ("like", "test%")})
  709. """
  710. kwargs["ignore_permissions"] = True
  711. if not "limit_page_length" in kwargs:
  712. kwargs["limit_page_length"] = 0
  713. return get_list(doctype, *args, **kwargs)
  714. def add_version(doc):
  715. """Insert a new **Version** of the given document.
  716. A **Version** is a JSON dump of the current document state."""
  717. get_doc({
  718. "doctype": "Version",
  719. "ref_doctype": doc.doctype,
  720. "docname": doc.name,
  721. "doclist_json": as_json(doc.as_dict())
  722. }).insert(ignore_permissions=True)
  723. def as_json(obj, indent=1):
  724. from frappe.utils.response import json_handler
  725. return json.dumps(obj, indent=indent, sort_keys=True, default=json_handler)
  726. def get_test_records(doctype):
  727. """Returns list of objects from `test_records.json` in the given doctype's folder."""
  728. from frappe.modules import get_doctype_module, get_module_path
  729. path = os.path.join(get_module_path(get_doctype_module(doctype)), "doctype", scrub(doctype), "test_records.json")
  730. if os.path.exists(path):
  731. with open(path, "r") as f:
  732. return json.loads(f.read())
  733. else:
  734. return []
  735. def format_value(value, df, doc=None, currency=None):
  736. """Format value with given field properties.
  737. :param value: Value to be formatted.
  738. :param df: DocField object with properties `fieldtype`, `options` etc."""
  739. import frappe.utils.formatters
  740. return frappe.utils.formatters.format_value(value, df, doc, currency=currency)
  741. def get_print(doctype, name, print_format=None, style=None, html=None, as_pdf=False):
  742. """Get Print Format for given document.
  743. :param doctype: DocType of document.
  744. :param name: Name of document.
  745. :param print_format: Print Format name. Default 'Standard',
  746. :param style: Print Format style.
  747. :param as_pdf: Return as PDF. Default False."""
  748. from frappe.website.render import build_page
  749. from frappe.utils.pdf import get_pdf
  750. local.form_dict.doctype = doctype
  751. local.form_dict.name = name
  752. local.form_dict.format = print_format
  753. local.form_dict.style = style
  754. if not html:
  755. html = build_page("print")
  756. if as_pdf:
  757. return get_pdf(html)
  758. else:
  759. return html
  760. def attach_print(doctype, name, file_name=None, print_format=None, style=None, html=None):
  761. from frappe.utils import scrub_urls
  762. if not file_name: file_name = name
  763. file_name = file_name.replace(' ','').replace('/','-')
  764. print_settings = db.get_singles_dict("Print Settings")
  765. local.flags.ignore_print_permissions = True
  766. if int(print_settings.send_print_as_pdf or 0):
  767. out = {
  768. "fname": file_name + ".pdf",
  769. "fcontent": get_print(doctype, name, print_format=print_format, style=style, html=html, as_pdf=True)
  770. }
  771. else:
  772. out = {
  773. "fname": file_name + ".html",
  774. "fcontent": scrub_urls(get_print(doctype, name, print_format=print_format, style=style, html=html)).encode("utf-8")
  775. }
  776. local.flags.ignore_print_permissions = False
  777. return out
  778. logging_setup_complete = False
  779. def get_logger(module=None):
  780. from frappe.setup_logging import setup_logging
  781. global logging_setup_complete
  782. if not logging_setup_complete:
  783. setup_logging()
  784. logging_setup_complete = True
  785. return logging.getLogger(module or "frappe")