Skip to content

Script Python API

Global

Name Type docs
as_json

Signature:

as_json(obj: dict | list, indent=1, separators=None, ensure_ascii=True) -> str
function Return the JSON string representation of the given `obj`.
dict type dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)
log

Signature:

log(msg: str) -> None
function Add to `debug_log` :param msg: Message.
_dict type dict like object that exposes keys as attributes
args.cmd str
frappe.date_format str
frappe.time_format str
frappe.number_format NumberFormat
frappe.form_dict.cmd str
frappe.qb LocalProxy
frappe.utils.DATE_FORMAT str
frappe.utils.TIME_FORMAT str
frappe.utils.DATETIME_FORMAT str
frappe.user str
frappe.full_name NoneType
frappe.request Request
frappe.session.user str
frappe.session.csrf_token NoneType
frappe.socketio_port int
frappe.lang str
frappe.response.docs list
FrappeClient

Signature:

FrappeClient(url, username=None, password=None, verify=True, api_key=None, api_secret=None, frappe_authorization_source=None)
type
style.border_color str
get_toc

Signature:

get_toc(route, url_prefix=None, app=None)
function Insert full index (table of contents) for {index} tag
get_next_link

Signature:

get_next_link(route, url_prefix=None, app=None)
function
_

Signature:

_(msg: str, lang: str | None = None, context: str | None = None) -> str
function Return translated string in current lang, if exists. Usage: _('Change') _('Change', context='Coins')
scrub

Signature:

scrub(txt: str) -> str
function Return sluggified string. e.g. `Sales Order` becomes `sales_order`.
guess_mimetype

Signature:

guess_mimetype(url, strict=True)
function Guess the type of a file based on its URL. Return value is a tuple (type, encoding) where type is None if the type can't be guessed (no or unknown suffix) or a string of the form type/subtype, usable for a MIME Content-type header; and encoding is None for no encoding or the name of the program used to encode (e.g. compress or gzip). The mappings are table driven. Encoding suffixes are case sensitive; type suffixes are first tried case sensitive, then case insensitive. The suffixes .tgz, .taz and .tz (case sensitive!) are all mapped to ".tar.gz". (This is table-driven too, using the dictionary suffix_map). Optional `strict' argument when false adds a bunch of commonly found, but non-standard types.
html2text

Signature:

html2text(html: str, strip_links=False, wrap=True) -> str
function Return the given `html` as markdown text.
dev_server int
run_script

Signature:

run_script(script, **kwargs)
function run another server script
is_job_queued

Signature:

is_job_queued(job_name, queue='default')
function :param job_name: used to identify a queued job, usually dotted path to function :param queue: should be either long, default or short
get_visible_columns

Signature:

get_visible_columns(data: list, table_meta: 'Meta', df: 'DocField') -> list['DocField']
function Return list of visible columns based on print_hide and if all columns have value.
__build_class__ builtin_function_or_method __build_class__(func, name, /, *bases, [metaclass], **kwds) -> class Internal helper function used by the class statement.
None NoneType
False bool
True bool
bool type bool(x) -> bool Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.
bytes type bytes(iterable_of_ints) -> bytes bytes(string, encoding[, errors]) -> bytes bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer bytes(int) -> bytes object of size given by the parameter initialized with null bytes bytes() -> empty bytes object Construct an immutable array of bytes from: - an iterable yielding integers in range(256) - a text string encoded using the specified encoding - any object implementing the buffer API. - an integer
int type int([x]) -> integer int(x, base=10) -> integer Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero. If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int('0b100', base=0) 4
range type range(stop) -> range object range(start, stop[, step]) -> range object Return an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1. start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3. These are exactly the valid indices for a list of 4 elements. When step is given, it specifies the increment (or decrement).
slice type slice(stop) slice(start, stop[, step]) Create a slice object. This is used for extended slicing (e.g. a[0:10:2]).
str type str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.
zip type zip(*iterables, strict=False) --> Yield tuples until an input is exhausted. >>> list(zip('abcdefg', range(3), range(4))) [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)] The zip object yields n-length tuples, where n is the number of iterables passed as positional arguments to zip(). The i-th element in every tuple comes from the i-th iterable argument to zip(). This continues until the shortest argument is exhausted. If strict is true and one of the arguments is exhausted before the others, raise a ValueError.
BaseException type Common base class for all exceptions
GeneratorExit type Request that a generator exit.
KeyboardInterrupt type Program interrupted by user.
SystemExit type Request to exit from the interpreter.
_write_

Signature:

_write_(obj)
function
_getitem_

Signature:

_getitem_(obj, key)
function
_getattr_

Signature:

_getattr_(object, name, default=None)
function
_print_

Signature:

_print_(_getattr_=None)
type Collect written text, and return it when called.
_getiter_ builtin_function_or_method iter(iterable) -> iterator iter(callable, sentinel) -> iterator Get an iterator from an object. In the first form, the argument must supply its own iterator, or be a sequence. In the second form, the callable is called until it returns the sentinel.
_iter_unpack_sequence_

Signature:

_iter_unpack_sequence_(it, spec, _getiter_)
function Protect sequence unpacking of targets in a 'for loop'. The target of a for loop could be a sequence. For example "for a, b in it" => Each object from the iterator needs guarded sequence unpacking.
abs

Signature:

abs(x, /)
builtin_function_or_method Return the absolute value of the argument.
all

Signature:

all(iterable, /)
builtin_function_or_method Return True if bool(x) is True for all values x in the iterable. If the iterable is empty, return True.
any

Signature:

any(iterable, /)
builtin_function_or_method Return True if bool(x) is True for any x in the iterable. If the iterable is empty, return False.
bool type bool(x) -> bool Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.
enumerate

Signature:

enumerate(iterable, start=0)
type Return an enumerate object. iterable an object supporting iteration The enumerate object yields pairs containing a count (from start, which defaults to zero) and a value yielded by the iterable argument. enumerate is useful for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
isinstance

Signature:

isinstance(obj, class_or_tuple, /)
builtin_function_or_method Return whether an object is an instance of a class or of a subclass thereof. A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B) or ...`` etc.
issubclass

Signature:

issubclass(cls, class_or_tuple, /)
builtin_function_or_method Return whether 'cls' is derived from another class or is the same class. A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B) or ...``.
list

Signature:

list(iterable=(), /)
type Built-in mutable sequence. If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.
max builtin_function_or_method max(iterable, *[, default=obj, key=func]) -> value max(arg1, arg2, *args, *[, key=func]) -> value With a single iterable argument, return its biggest item. The default keyword-only argument specifies an object to return if the provided iterable is empty. With two or more arguments, return the largest argument.
min builtin_function_or_method min(iterable, *[, default=obj, key=func]) -> value min(arg1, arg2, *args, *[, key=func]) -> value With a single iterable argument, return its smallest item. The default keyword-only argument specifies an object to return if the provided iterable is empty. With two or more arguments, return the smallest argument.
range type range(stop) -> range object range(start, stop[, step]) -> range object Return an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1. start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3. These are exactly the valid indices for a list of 4 elements. When step is given, it specifies the increment (or decrement).
set type set() -> new empty set object set(iterable) -> new set object Build an unordered collection of unique elements.
sorted

Signature:

sorted(iterable, /, *, key=None, reverse=False)
builtin_function_or_method Return a new list containing all items from the iterable in ascending order. A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order.
sum

Signature:

sum(iterable, /, start=0)
builtin_function_or_method Return the sum of a 'start' value (default: 0) plus an iterable of numbers When the iterable is empty, return the start value. This function is intended specifically for use with numeric values and may reject non-numeric types.
tuple

Signature:

tuple(iterable=(), /)
type Built-in immutable sequence. If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items. If the argument is a tuple, the return value is the same object.
exceptions

__builtins__

Name Type docs
abs

Signature:

abs(x, /)
builtin_function_or_method Return the absolute value of the argument.
callable

Signature:

callable(obj, /)
builtin_function_or_method Return whether the object is callable (i.e., some kind of function). Note that classes are callable, as are instances of classes with a __call__() method.
chr

Signature:

chr(i, /)
builtin_function_or_method Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
complex

Signature:

complex(real=0, imag=0)
type Create a complex number from a real part and an optional imaginary part. This is equivalent to (real + imag*1j) where imag defaults to 0.
divmod

Signature:

divmod(x, y, /)
builtin_function_or_method Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
float

Signature:

float(x=0, /)
type Convert a string or number to a floating point number, if possible.
hash

Signature:

hash(obj, /)
builtin_function_or_method Return the hash value for the given object. Two objects that compare equal must also have the same hash value, but the reverse is not necessarily true.
hex

Signature:

hex(number, /)
builtin_function_or_method Return the hexadecimal representation of an integer. >>> hex(12648430) '0xc0ffee'
id

Signature:

id(obj, /)
builtin_function_or_method Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (CPython uses the object's memory address.)
isinstance

Signature:

isinstance(obj, class_or_tuple, /)
builtin_function_or_method Return whether an object is an instance of a class or of a subclass thereof. A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B) or ...`` etc.
issubclass

Signature:

issubclass(cls, class_or_tuple, /)
builtin_function_or_method Return whether 'cls' is derived from another class or is the same class. A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B) or ...``.
len

Signature:

len(obj, /)
builtin_function_or_method Return the number of items in a container.
oct

Signature:

oct(number, /)
builtin_function_or_method Return the octal representation of an integer. >>> oct(342391) '0o1234567'
ord

Signature:

ord(c, /)
builtin_function_or_method Return the Unicode code point for a one-character string.
pow

Signature:

pow(base, exp, mod=None)
builtin_function_or_method Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments Some types, such as ints, are able to use a more efficient algorithm when invoked using the three argument form.
repr

Signature:

repr(obj, /)
builtin_function_or_method Return the canonical string representation of the object. For many object types, including most builtins, eval(repr(obj)) == obj.
round

Signature:

round(number, ndigits=None)
builtin_function_or_method Round a number to a given precision in decimal digits. The return value is an integer if ndigits is omitted or None. Otherwise the return value has the same type as the number. ndigits may be negative.
sorted

Signature:

sorted(iterable, /, *, key=None, reverse=False)
builtin_function_or_method Return a new list containing all items from the iterable in ascending order. A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order.
tuple

Signature:

tuple(iterable=(), /)
type Built-in immutable sequence. If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items. If the argument is a tuple, the return value is the same object.
setattr

Signature:

setattr(object, name, value)
function
delattr

Signature:

delattr(object, name)
function
_getattr_

Signature:

_getattr_(object, name, default=None, getattr=<built-in function getattr>)
function Getattr implementation which prevents using format on string objects. format() is considered harmful: http://lucumr.pocoo.org/2016/12/29/careful-with-str-format/

frappe

Name Type docs
frappe.call

Signature:

frappe.call(function, **kwargs)
function Executes a whitelisted function or Server Script of type API
frappe.format

Signature:

frappe.format(*args, **kwargs)
function Format value with given field properties. :param value: Value to be formatted. :param df: (Optional) DocField object with properties `fieldtype`, `options` etc.
frappe.format_value

Signature:

frappe.format_value(*args, **kwargs)
function Format value with given field properties. :param value: Value to be formatted. :param df: (Optional) DocField object with properties `fieldtype`, `options` etc.
frappe.format_date

Signature:

frappe.format_date(date: str | datetime.date | datetime.datetime, format='long') -> str
function Return localized date in the form of 'January 1, 2012'.
frappe.bold

Signature:

frappe.bold(text: str | int | float) -> str
function Return `text` wrapped in `<strong>` tags.
frappe.copy_doc

Signature:

frappe.copy_doc(doc: 'Document', ignore_no_copy: bool = True) -> 'Document'
function No_copy fields also get copied.
frappe.errprint

Signature:

frappe.errprint(msg: str) -> None
function Log error. This is sent back as `exc` in response. :param msg: Message.
frappe.get_meta

Signature:

frappe.get_meta(doctype, cached=True)
function Get `frappe.model.meta.Meta` instance of given doctype name.
frappe.new_doc

Signature:

frappe.new_doc(doctype: str, *, parent_doc: Optional[ForwardRef('Document')] = None, parentfield: str | None = None, as_dict: bool = False, **kwargs) -> 'Document'
function Return a new document of the given DocType with defaults set. :param doctype: DocType of the new document. :param parent_doc: [optional] add to parent document. :param parentfield: [optional] add against this `parentfield`. :param as_dict: [optional] return as dictionary instead of Document. :param kwargs: [optional] You can specify fields as field=value pairs in function call.
frappe.get_doc

Signature:

frappe.get_doc(*args: Any, **kwargs: Any) -> 'Document'
function Return a `frappe.model.document.Document` object of the given type and name. :param arg1: DocType name as string **or** document JSON. :param arg2: [optional] Document name as string. Examples: # insert a new document todo = frappe.get_doc({"doctype":"ToDo", "description": "test"}) todo.insert() # open an existing document todo = frappe.get_doc("ToDo", "TD0001")
frappe.get_mapped_doc

Signature:

frappe.get_mapped_doc(from_doctype, from_docname, table_maps, target_doc=None, postprocess=None, ignore_permissions=False, ignore_child_tables=False, cached=False)
function
frappe.get_last_doc

Signature:

frappe.get_last_doc(doctype, filters: frappe.types.filter.Filters | frappe.types.filter.FilterTuple | collections.abc.Mapping[str, str | int | float | None | datetime.datetime | datetime.date | pypika.queries.Column | frappe.types.docref.DocRef | bool | tuple[str, str | int | float | None | datetime.datetime | datetime.date | pypika.queries.Column | frappe.types.docref.DocRef | bool | collections.abc.Sequence[str | int | float | None | datetime.datetime | datetime.date | pypika.queries.Column | frappe.types.docref.DocRef | bool]]] | tuple[str, str | int | float | None | datetime.datetime | datetime.date | pypika.queries.Column | frappe.types.docref.DocRef | bool | collections.abc.Sequence[str | int | float | None | datetime.datetime | datetime.date | pypika.queries.Column | frappe.types.docref.DocRef | bool]] | tuple[str, str, str | int | float | None | datetime.datetime | datetime.date | pypika.queries.Column | frappe.types.docref.DocRef | bool | collections.abc.Sequence[str | int | float | None | datetime.datetime | datetime.date | pypika.queries.Column | frappe.types.docref.DocRef | bool]] | tuple[str, str, str, str | int | float | None | datetime.datetime | datetime.date | pypika.queries.Column | frappe.types.docref.DocRef | bool | collections.abc.Sequence[str | int | float | None | datetime.datetime | datetime.date | pypika.queries.Column | frappe.types.docref.DocRef | bool]] | None = None, order_by='creation desc', *, for_update=False)
function Get last created document of this type.
frappe.get_cached_doc

Signature:

frappe.get_cached_doc(*args: Any, **kwargs: Any) -> 'Document'
function Identical to `frappe.get_doc`, but return from cache if available.
frappe.get_list

Signature:

frappe.get_list(doctype, *args, **kwargs)
function List database query via `frappe.model.db_query`. Will also check for permissions. :param doctype: DocType on which query is to be made. :param fields: List of fields or `*`. :param filters: List of filters (see example). :param order_by: Order By e.g. `creation desc`. :param limit_start: Start results at record #. Default 0. :param limit_page_length: No of records in the page. Default 20. Example usage: # simple dict filter frappe.get_list("ToDo", fields=["name", "description"], filters = {"owner":"test@example.com"}) # filter as a list of lists frappe.get_list("ToDo", fields="*", filters = [["modified", ">", "2014-01-01"]])
frappe.get_all

Signature:

frappe.get_all(doctype, *args, **kwargs)
function List database query via `frappe.model.db_query`. Will **not** check for permissions. Parameters are same as `frappe.get_list` :param doctype: DocType on which query is to be made. :param fields: List of fields or `*`. Default is: `["name"]`. :param filters: List of filters (see example). :param order_by: Order By e.g. `creation desc`. :param limit_start: Start results at record #. Default 0. :param limit_page_length: No of records in the page. Default 20. Example usage: # simple dict filter frappe.get_all("ToDo", fields=["name", "description"], filters = {"owner":"test@example.com"}) # filter as a list of lists frappe.get_all("ToDo", fields=["*"], filters = [["modified", ">", "2014-01-01"]])
frappe.get_system_settings

Signature:

frappe.get_system_settings(key: str)
function Return the value associated with the given `key` from System Settings DocType.
frappe.rename_doc

Signature:

frappe.rename_doc(doctype: str | None = None, old: str | int | None = None, new: str | int | None = None, force: bool = False, merge: bool = False, ignore_permissions: bool = False, ignore_if_exists: bool = False, show_alert: bool = True, rebuild_search: bool = True, doc: frappe.model.document.Document | None = None, validate: bool = True) -> str
function Rename a doc(dt, old) to doc(dt, new) and update all linked fields of type "Link". doc: Document object to be renamed. new: New name for the record. If None, and doctype is specified, new name may be automatically generated via before_rename hooks. doctype: DocType of the document. Not required if doc is passed. old: Current name of the document. Not required if doc is passed. force: Allow even if document is not allowed to be renamed. merge: Merge with existing document of new name. ignore_permissions: Ignore user permissions while renaming. ignore_if_exists: Don't raise exception if document with new name already exists. This will quietely overwrite the existing document. show_alert: Display alert if document is renamed successfully. rebuild_search: Rebuild linked doctype search after renaming. validate: Validate before renaming. If False, it is assumed that the caller has already validated.
frappe.delete_doc

Signature:

frappe.delete_doc(doctype=None, name=None, force=0, ignore_doctypes=None, for_reload=False, ignore_permissions=False, flags=None, ignore_on_trash=False, ignore_missing=True, delete_permanently=False)
function Deletes a doc(dt, dn) and validates if it is not submitted and not linked in a live record
frappe.get_url

Signature:

frappe.get_url(uri: str | None = None, full_address: bool = False) -> str
function Get app url from request.
frappe.render_template

Signature:

frappe.render_template(template, context=None, is_path=None, safe_render=True)
function Render a template using Jinja :param template: path or HTML containing the jinja template :param context: dict of properties to pass to the template :param is_path: (optional) assert that the `template` parameter is a path :param safe_render: (optional) prevent server side scripting via jinja templating
frappe.msgprint

Signature:

frappe.msgprint(msg: str, title: str | None = None, raise_exception: bool | type[Exception] = False, as_table: bool = False, as_list: bool = False, indicator: Optional[Literal['blue', 'green', 'orange', 'red', 'yellow']] = None, alert: bool = False, primary_action: dict | None = None, is_minimizable: bool = False, wide: bool = False, *, realtime=False) -> None
function Print a message to the user (via HTTP response). Messages are sent in the `__server_messages` property in the response JSON and shown in a pop-up / modal. :param msg: Message. :param title: [optional] Message title. Default: "Message". :param raise_exception: [optional] Raise given exception and show message. :param as_table: [optional] If `msg` is a list of lists, render as HTML table. :param as_list: [optional] If `msg` is a list, render as un-ordered list. :param primary_action: [optional] Bind a primary server/client side action. :param is_minimizable: [optional] Allow users to minimize the modal :param wide: [optional] Show wide modal :param realtime: Publish message immediately using websocket.
frappe.throw

Signature:

frappe.throw(msg: str, exc: type[Exception] = <class 'frappe.exceptions.ValidationError'>, title: str | None = None, is_minimizable: bool = False, wide: bool = False, as_list: bool = False, primary_action=None) -> None
function Throw execption and show message (`msgprint`). :param msg: Message. :param exc: Exception class. Default `frappe.ValidationError` :param title: [optional] Message title. Default: "Message". :param is_minimizable: [optional] Allow users to minimize the modal :param wide: [optional] Show wide modal :param as_list: [optional] If `msg` is a list, render as un-ordered list. :param primary_action: [optional] Bind a primary server/client side action.
frappe.sendmail

Signature:

frappe.sendmail(recipients=None, sender='', subject='No Subject', message='No Message', as_markdown=False, delayed=True, reference_doctype=None, reference_name=None, unsubscribe_method=None, unsubscribe_params=None, unsubscribe_message=None, add_unsubscribe_link=1, attachments=None, content=None, doctype=None, name=None, reply_to=None, queue_separately=False, cc=None, bcc=None, message_id=None, in_reply_to=None, send_after=None, expose_recipients=None, send_priority=1, communication=None, retry=1, now=None, read_receipt=None, is_notification=False, inline_images=None, template=None, args=None, header=None, print_letterhead=False, with_container=False, email_read_tracker_url=None) -> Optional[ForwardRef('EmailQueue')]
function Send email using user's default **Email Account** or global default **Email Account**. :param recipients: List of recipients. :param sender: Email sender. Default is current user or default outgoing account. :param subject: Email Subject. :param message: (or `content`) Email Content. :param as_markdown: Convert content markdown to HTML. :param delayed: Send via scheduled email sender **Email Queue**. Don't send immediately. Default is true :param send_priority: Priority for Email Queue, default 1. :param reference_doctype: (or `doctype`) Append as communication to this DocType. :param reference_name: (or `name`) Append as communication to this document name. :param unsubscribe_method: Unsubscribe url with options email, doctype, name. e.g. `/api/method/unsubscribe` :param unsubscribe_params: Unsubscribe paramaters to be loaded on the unsubscribe_method [optional] (dict). :param attachments: List of attachments. :param reply_to: Reply-To Email Address. :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. :param in_reply_to: Used to send the Message-Id of a received email back as In-Reply-To. :param send_after: Send after the given datetime. :param expose_recipients: Display all recipients in the footer message - "This email was sent to" :param communication: Communication link to be set in Email Queue record :param inline_images: List of inline images as {"filename", "filecontent"}. All src properties will be replaced with random Content-Id :param template: Name of html template from templates/emails folder :param args: Arguments for rendering the template :param header: Append header in email :param with_container: Wraps email inside a styled container
frappe.get_print

Signature:

frappe.get_print(doctype=None, name=None, print_format=None, style=None, as_pdf=False, doc=None, output=None, no_letterhead=0, password=None, pdf_options=None, letterhead=None)
function Get Print Format for given document. :param doctype: DocType of document. :param name: Name of document. :param print_format: Print Format name. Default 'Standard', :param style: Print Format style. :param as_pdf: Return as PDF. Default False. :param password: Password to encrypt the pdf with. Default None
frappe.attach_print

Signature:

frappe.attach_print(doctype, name, file_name=None, print_format=None, style=None, html=None, doc=None, lang=None, print_letterhead=True, password=None, letterhead=None)
function
frappe.get_fullname

Signature:

frappe.get_fullname(user=None)
function get the full name (first name + last name) of the user from User
frappe.get_gravatar

Signature:

frappe.get_gravatar(email: str, default: Literal['mm', '404'] = 'mm') -> str
function Return gravatar URL for the given email. If `default` is set to "404", gravatar URL will return 404 if no avatar is found. If `default` is set to "mm", a placeholder image will be returned.
frappe.make_get_request

Signature:

frappe.make_get_request(url: str, **kwargs)
function Make a 'GET' HTTP request to the given `url` and return processed response. You can optionally pass the below parameters: * `headers`: Headers to be set in the request. * `params`: Query parameters to be passed in the request. * `auth`: Auth credentials.
frappe.make_post_request

Signature:

frappe.make_post_request(url: str, **kwargs)
function Make a 'POST' HTTP request to the given `url` and return processed response. You can optionally pass the below parameters: * `headers`: Headers to be set in the request. * `data`: Data to be passed in body of the request. * `json`: JSON to be passed in the request. * `params`: Query parameters to be passed in the request. * `auth`: Auth credentials.
frappe.make_put_request

Signature:

frappe.make_put_request(url: str, **kwargs)
function Make a 'PUT' HTTP request to the given `url` and return processed response. You can optionally pass the below parameters: * `headers`: Headers to be set in the request. * `data`: Data to be passed in body of the request. * `json`: JSON to be passed in the request. * `params`: Query parameters to be passed in the request. * `auth`: Auth credentials.
frappe.make_patch_request

Signature:

frappe.make_patch_request(url: str, **kwargs)
function Make a 'PATCH' HTTP request to the given `url` and return processed response. You can optionally pass the below parameters: * `headers`: Headers to be set in the request. * `data`: Data to be passed in body of the request. * `json`: JSON to be passed in the request. * `params`: Query parameters to be passed in the request. * `auth`: Auth credentials.
frappe.make_delete_request

Signature:

frappe.make_delete_request(url: str, **kwargs)
function Make a 'DELETE' HTTP request to the given `url` and return processed response. You can optionally pass the below parameters: * `headers`: Headers to be set in the request. * `data`: Data to be passed in body of the request. * `json`: JSON to be passed in the request. * `params`: Query parameters to be passed in the request. * `auth`: Auth credentials.
frappe.get_hooks

Signature:

frappe.get_hooks(hook: str | None = None, default=None, app_name: str | None = None) -> frappe.types.frappedict._dict
function Get hooks via `app/hooks.py` :param hook: Name of the hook. Will gather all hooks for this name and return as a list. :param default: Default if no hook found. :param app_name: Filter by app.
frappe.enqueue

Signature:

frappe.enqueue(function, **kwargs)
function Enqueue function to be executed using a background worker Accepts frappe.enqueue params like job_name, queue, timeout, etc. in addition to params to be passed to function :param function: whitelisted function or API Method set in Server Script
frappe.sanitize_html

Signature:

frappe.sanitize_html(html, linkify=False, always_sanitize=False)
function Sanitize HTML tags, attributes and style to prevent XSS attacks Based on bleach clean, bleach whitelist and html5lib's Sanitizer defaults Does not sanitize JSON unless explicitly specified, as it could lead to future problems
frappe.log_error

Signature:

frappe.log_error(title=None, message=None, reference_doctype=None, reference_name=None, *, defer_insert=False)
function Log error to Error Log
frappe.log

Signature:

frappe.log(msg: str) -> None
function Add to `debug_log` :param msg: Message.

frappe.db

Name Type docs
frappe.db.get_list

Signature:

frappe.db.get_list(doctype, *args, **kwargs)
function List database query via `frappe.model.db_query`. Will also check for permissions. :param doctype: DocType on which query is to be made. :param fields: List of fields or `*`. :param filters: List of filters (see example). :param order_by: Order By e.g. `creation desc`. :param limit_start: Start results at record #. Default 0. :param limit_page_length: No of records in the page. Default 20. Example usage: # simple dict filter frappe.get_list("ToDo", fields=["name", "description"], filters = {"owner":"test@example.com"}) # filter as a list of lists frappe.get_list("ToDo", fields="*", filters = [["modified", ">", "2014-01-01"]])
frappe.db.get_all

Signature:

frappe.db.get_all(doctype, *args, **kwargs)
function List database query via `frappe.model.db_query`. Will **not** check for permissions. Parameters are same as `frappe.get_list` :param doctype: DocType on which query is to be made. :param fields: List of fields or `*`. Default is: `["name"]`. :param filters: List of filters (see example). :param order_by: Order By e.g. `creation desc`. :param limit_start: Start results at record #. Default 0. :param limit_page_length: No of records in the page. Default 20. Example usage: # simple dict filter frappe.get_all("ToDo", fields=["name", "description"], filters = {"owner":"test@example.com"}) # filter as a list of lists frappe.get_all("ToDo", fields=["*"], filters = [["modified", ">", "2014-01-01"]])
frappe.db.get_value

Signature:

frappe.db.get_value(doctype: str, filters: frappe.types.docref.DocRef | str | int | bool | dict | list | None = None, fieldname: str | list[str] = 'name', ignore: bool = False, as_dict: bool = False, debug: bool = False, order_by: str = 'KEEP_DEFAULT_ORDERING', cache: bool = False, for_update: bool = False, *, run: bool = True, pluck: bool = False, distinct: bool = False, skip_locked: bool = False, wait: bool = True)
method Return a document property or list of properties. :param doctype: DocType name. :param filters: Filters like `{"x":"y"}` or name of the document. `None` if Single DocType. :param fieldname: Column name. :param ignore: Don't raise exception if table, column is missing. :param as_dict: Return values as dict. :param debug: Print query in error log. :param order_by: Column to order by :param cache: Use cached results fetched during current job/request :param pluck: pluck first column instead of returning as nested list or dict. :param for_update: All the affected/read rows will be locked. :param skip_locked: Skip selecting currently locked rows. :param wait: Wait for aquiring lock Example: # return first customer starting with a frappe.db.get_value("Customer", {"name": ("like a%")}) # return last login of **User** `test@example.com` frappe.db.get_value("User", "test@example.com", "last_login") last_login, last_ip = frappe.db.get_value("User", "test@example.com", ["last_login", "last_ip"]) # returns default date_format frappe.db.get_value("System Settings", None, "date_format")
frappe.db.set_value

Signature:

frappe.db.set_value(dt: str, dn: frappe.types.docref.DocRef | str | int | bool | dict, field: str, val=None, modified=None, modified_by=None, update_modified=True, debug=False)
method Set a single value in the database, do not call the ORM triggers but update the modified timestamp (unless specified not to). **Warning:** this function will not call Document events and should be avoided in normal cases. :param dt: DocType name. :param dn: Document name for updating single record or filters for updating many records. :param field: Property / field name or dictionary of values to be updated :param value: Value to be updated. :param modified: Use this as the `modified` timestamp. :param modified_by: Set this user as `modified_by`. :param update_modified: default True. Set as false, if you don't want to update the timestamp. :param debug: Print the query in the developer / js console.
frappe.db.get_single_value

Signature:

frappe.db.get_single_value(doctype: str, fieldname: str, cache: bool = True)
method Get property of Single DocType. Cache locally by default :param doctype: DocType of the single object whose value is requested :param fieldname: `fieldname` of the property whose value is requested Example: # Get the default value of the company from the Global Defaults doctype. company = frappe.db.get_single_value('Global Defaults', 'default_company')
frappe.db.get_default

Signature:

frappe.db.get_default(key, parent='__default')
method Return default value as a list if multiple or single.
frappe.db.exists

Signature:

frappe.db.exists(dt, dn=None, cache=False, *, debug=False)
method Return the document name of a matching document, or None. Note: `cache` only works if `dt` and `dn` are of type `str`. ## Examples Pass doctype and docname (only in this case we can cache the result) ``` exists("User", "jane@example.org", cache=True) ``` Pass a dict of filters including the `"doctype"` key: ``` exists({"doctype": "User", "full_name": "Jane Doe"}) ``` Pass the doctype and a dict of filters: ``` exists("User", {"full_name": "Jane Doe"}) ```
frappe.db.count

Signature:

frappe.db.count(dt, filters=None, debug=False, cache=False, distinct: bool = True)
method Return `COUNT(*)` for given DocType and filters.
frappe.db.escape

Signature:

frappe.db.escape(s, percent=True)
function Escape quotes and percent in given string.
frappe.db.sql

Signature:

frappe.db.sql(query, *args, **kwargs)
function a wrapper for frappe.db.sql to allow reads
frappe.db.commit

Signature:

frappe.db.commit()
method Commit current transaction. Calls SQL `COMMIT`.
frappe.db.rollback

Signature:

frappe.db.rollback(*, save_point=None)
method `ROLLBACK` current transaction. Optionally rollback to a known save_point.
frappe.db.after_commit

Signature:

frappe.db.after_commit(func: collections.abc.Callable) -> None
CallbackManager Manage callbacks. ``` # Capture callacks callbacks = CallbackManager() # Put a function call in queue callbacks.add(func) # Run all pending functions in queue callbacks.run() # Reset queue callbacks.reset() ``` Example usage: frappe.db.after_commit
frappe.db.before_commit

Signature:

frappe.db.before_commit(func: collections.abc.Callable) -> None
CallbackManager Manage callbacks. ``` # Capture callacks callbacks = CallbackManager() # Put a function call in queue callbacks.add(func) # Run all pending functions in queue callbacks.run() # Reset queue callbacks.reset() ``` Example usage: frappe.db.after_commit
frappe.db.after_rollback

Signature:

frappe.db.after_rollback(func: collections.abc.Callable) -> None
CallbackManager Manage callbacks. ``` # Capture callacks callbacks = CallbackManager() # Put a function call in queue callbacks.add(func) # Run all pending functions in queue callbacks.run() # Reset queue callbacks.reset() ``` Example usage: frappe.db.after_commit
frappe.db.before_rollback

Signature:

frappe.db.before_rollback(func: collections.abc.Callable) -> None
CallbackManager Manage callbacks. ``` # Capture callacks callbacks = CallbackManager() # Put a function call in queue callbacks.add(func) # Run all pending functions in queue callbacks.run() # Reset queue callbacks.reset() ``` Example usage: frappe.db.after_commit
frappe.db.add_index

Signature:

frappe.db.add_index(doctype: str, fields: list, index_name: str | None = None)
method Creates an index with given fields if not already created. Index name will be `fieldname1_fieldname2_index`

frappe.utils

Name Type docs
frappe.utils.is_invalid_date_string

Signature:

frappe.utils.is_invalid_date_string(date_string: str) -> bool
function Return True if the date string is invalid or None or empty.
frappe.utils.getdate

Signature:

frappe.utils.getdate(string_date: Optional[ForwardRef('DateTimeLikeObject')] = None, parse_day_first: bool = False) -> datetime.date | None
function Convert string date (yyyy-mm-dd) to datetime.date object. If no input is provided, current date is returned.
frappe.utils.get_datetime

Signature:

frappe.utils.get_datetime(datetime_str: Union[ForwardRef('DateTimeLikeObject'), NoneType, tuple, list] = None) -> datetime.datetime | None
function Return the below mentioned values based on the given `datetime_str`: * If `datetime_str` is None, returns datetime object of current datetime * If `datetime_str` is already a datetime object, returns the same * If `datetime_str` is a timedelta object, returns the same * If `datetime_str` is a list or tuple, returns a datetime object * If `datetime_str` is a date object, returns a datetime object * If `datetime_str` is a valid date string, returns a datetime object for the same * If `datetime_str` is an invalid date string, returns None
frappe.utils.get_timedelta

Signature:

frappe.utils.get_timedelta(time: str | datetime.timedelta | None = None) -> datetime.timedelta | None
function Return `datetime.timedelta` object from string value of a valid time format. Return None if `time` is not a valid format. Args: time (str | datetime.timedelta): A valid time representation. This string is parsed using `dateutil.parser.parse`. Examples of valid inputs are: '0:0:0', '17:21:00', '2012-01-19 17:21:00'. Checkout https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.parse Return: datetime.timedelta: Timedelta object equivalent of the passed `time` string
frappe.utils.to_timedelta

Signature:

frappe.utils.to_timedelta(time_str: str | datetime.time) -> datetime.timedelta
function Return a `datetime.timedelta` object from the given string or `datetime.time` object. If the given argument is not a string or a `datetime.time` object, it is returned as is.
frappe.utils.add_to_date

Signature:

frappe.utils.add_to_date(date: str | datetime.date | datetime.datetime, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, as_string=False, as_datetime=False) -> str | datetime.date | datetime.datetime
function Adds `days` to the given date
frappe.utils.add_days

Signature:

frappe.utils.add_days(date: str | datetime.date | datetime.datetime, days: int | float) -> str | datetime.date | datetime.datetime
function Return a new date after adding the given number of `days` to the given `date`.
frappe.utils.add_months

Signature:

frappe.utils.add_months(date: str | datetime.date | datetime.datetime, months: int | float) -> str | datetime.date | datetime.datetime
function Return a new date after adding the given number of `months` to the given `date`.
frappe.utils.add_years

Signature:

frappe.utils.add_years(date: str | datetime.date | datetime.datetime, years: int | float) -> str | datetime.date | datetime.datetime
function Return a new date after adding the given number of `years` to the given `date`.
frappe.utils.date_diff

Signature:

frappe.utils.date_diff(string_ed_date: str | datetime.date | datetime.datetime, string_st_date: str | datetime.date | datetime.datetime) -> int
function Return the difference between given two dates in days.
frappe.utils.month_diff

Signature:

frappe.utils.month_diff(string_ed_date: str | datetime.date | datetime.datetime, string_st_date: str | datetime.date | datetime.datetime) -> int
function Return the difference between given two dates in months.
frappe.utils.time_diff

Signature:

frappe.utils.time_diff(string_ed_date: str | datetime.date | datetime.datetime, string_st_date: str | datetime.date | datetime.datetime) -> datetime.timedelta
function Return the difference between given two dates as `datetime.timedelta` object.
frappe.utils.time_diff_in_seconds

Signature:

frappe.utils.time_diff_in_seconds(string_ed_date: str | datetime.date | datetime.datetime, string_st_date: str | datetime.date | datetime.datetime) -> float
function Return the difference between given two dates in seconds.
frappe.utils.time_diff_in_hours

Signature:

frappe.utils.time_diff_in_hours(string_ed_date: str | datetime.date | datetime.datetime, string_st_date: str | datetime.date | datetime.datetime) -> float
function Return the difference between given two dates in hours.
frappe.utils.now_datetime

Signature:

frappe.utils.now_datetime() -> datetime.datetime
function Return the current datetime in system timezone.
frappe.utils.get_timestamp

Signature:

frappe.utils.get_timestamp(date: Optional[ForwardRef('DateTimeLikeObject')] = None) -> float
function Return the Unix timestamp (seconds since Epoch) for the given `date`. If `date` is None, the current timestamp is returned.
frappe.utils.get_eta

Signature:

frappe.utils.get_eta(from_time: str | datetime.date | datetime.datetime, percent_complete) -> str
function
frappe.utils.get_system_timezone

Signature:

frappe.utils.get_system_timezone() -> str
function Return the system timezone.
frappe.utils.get_datetime_in_timezone

Signature:

frappe.utils.get_datetime_in_timezone(time_zone: str) -> datetime.datetime
function Return the current datetime in the given timezone (e.g. 'Asia/Kolkata').
frappe.utils.convert_utc_to_system_timezone

Signature:

frappe.utils.convert_utc_to_system_timezone(utc_timestamp: datetime.datetime) -> datetime.datetime
function Return the given UTC `datetime` timestamp in system timezone.
frappe.utils.now

Signature:

frappe.utils.now() -> str
function Return current datetime as `yyyy-mm-dd hh:mm:ss`.
frappe.utils.nowdate

Signature:

frappe.utils.nowdate() -> str
function Return current date as `yyyy-mm-dd`.
frappe.utils.today

Signature:

frappe.utils.today() -> str
function Return today's date in `yyyy-mm-dd` format.
frappe.utils.get_abbr

Signature:

frappe.utils.get_abbr(string: str, max_len: int = 2) -> str
function Return the abbreviation of the given string. Examples: * "John Doe" => "JD" * "Jenny Jane Doe" => "JJ" (default, `max_len` = 2) * "Jenny Jane Doe" => "JJD" (`max_len` = 3) Return "?" if the given string is empty.
frappe.utils.nowtime

Signature:

frappe.utils.nowtime() -> str
function Return current time (system timezone) in `hh:mm:ss` format.
frappe.utils.get_first_day

Signature:

frappe.utils.get_first_day(dt, d_years: int = 0, d_months: int = 0, as_str: bool = False) -> str | datetime.date
function Return the first day of the month for the date specified by date object. Also, add `d_years` and `d_months` if specified.
frappe.utils.get_quarter_start

Signature:

frappe.utils.get_quarter_start(dt: str | datetime.date | datetime.datetime | None = None, as_str: bool = False) -> str | datetime.date
function Return the start date of the quarter for the given datetime like object (`dt`). If `dt` is None, the current quarter start date is returned.
frappe.utils.get_first_day_of_week

Signature:

frappe.utils.get_first_day_of_week(dt: str | datetime.date | datetime.datetime, as_str=False) -> datetime.date | str
function Return the first day of the week (as per System Settings or Sunday by default) for the given datetime like object (`dt`). If `as_str` is True, the first day of the week is returned as a string in `yyyy-mm-dd` format.
frappe.utils.get_year_start

Signature:

frappe.utils.get_year_start(dt: str | datetime.date | datetime.datetime, as_str=False) -> str | datetime.date
function Return the start date of the year for the given date (`dt`).
frappe.utils.get_last_day_of_week

Signature:

frappe.utils.get_last_day_of_week(dt: str | datetime.date | datetime.datetime, as_str=False) -> datetime.date | str
function Return the last day of the week (first day is taken from System Settings or Sunday by default) for the given datetime like object (`dt`). If `as_str` is True, the last day of the week is returned as a string in `yyyy-mm-dd` format.
frappe.utils.get_last_day

Signature:

frappe.utils.get_last_day(dt)
function Return last day of the month using: `get_first_day(dt, 0, 1) + datetime.timedelta(-1)`
frappe.utils.get_quarter_ending

Signature:

frappe.utils.get_quarter_ending(date: str | datetime.date | datetime.datetime | None = None, as_str=False) -> str | datetime.date
function Return the end date of the quarter for the given datetime like object (`date`). If `date` is None, the current quarter end date is returned. If `as_str` is True, the end date of the quarter is returned as a string in `yyyy-mm-dd` format.
frappe.utils.get_year_ending

Signature:

frappe.utils.get_year_ending(date: str | datetime.date | datetime.datetime | None = None, as_str=False) -> datetime.date | str
function Return the end date of the year for the given datetime like object (`date`). If `date` is None, the current year end date is returned. If `as_str` is True, the end date of the year is returned as a string in `yyyy-mm-dd` format.
frappe.utils.get_time

Signature:

frappe.utils.get_time(time_str: str | datetime.datetime | datetime.time | datetime.timedelta) -> datetime.time
function Return a `datetime.time` object for the given `time_str`. If the given argument is already a `datetime.time` object, it is returned as is.
frappe.utils.get_datetime_str

Signature:

frappe.utils.get_datetime_str(datetime_obj: str | datetime.date | datetime.datetime) -> str
function Return the given datetime like object (datetime.date, datetime.datetime, string) as a string in `yyyy-mm-dd hh:mm:ss` format.
frappe.utils.get_date_str

Signature:

frappe.utils.get_date_str(date_obj: str | datetime.date | datetime.datetime) -> str
function Return the given datetime like object (datetime.date, datetime.datetime, string) as a string in `yyyy-mm-dd` format.
frappe.utils.get_time_str

Signature:

frappe.utils.get_time_str(timedelta_obj: datetime.timedelta | str) -> str
function Return the given timedelta object as a string in `hh:mm:ss` format.
frappe.utils.get_user_date_format

Signature:

frappe.utils.get_user_date_format() -> str
function Get the current user date format. The result will be cached.
frappe.utils.get_user_time_format

Signature:

frappe.utils.get_user_time_format() -> str
function Get the current user time format. The result will be cached.
frappe.utils.format_date

Signature:

frappe.utils.format_date(string_date=None, format_string: str | None = None, parse_day_first: bool = False) -> str
function Convert the given string date to :data:`user_date_format`. User format specified in defaults Examples: * dd-mm-yyyy * mm-dd-yyyy * dd/mm/yyyy
frappe.utils.formatdate

Signature:

frappe.utils.formatdate(string_date=None, format_string: str | None = None, parse_day_first: bool = False) -> str
function Convert the given string date to :data:`user_date_format`. User format specified in defaults Examples: * dd-mm-yyyy * mm-dd-yyyy * dd/mm/yyyy
frappe.utils.format_time

Signature:

frappe.utils.format_time(time_string=None, format_string: str | None = None) -> str
function Convert the given string time to :data:`user_time_format`. User format specified in defaults Examples: * HH:mm:ss * HH:mm
frappe.utils.format_datetime

Signature:

frappe.utils.format_datetime(datetime_string: str | datetime.date | datetime.datetime, format_string: str | None = None) -> str
function Convert the given string time to :data:`user_datetime_format` User format specified in defaults Examples: * dd-mm-yyyy HH:mm:ss * mm-dd-yyyy HH:mm
frappe.utils.format_duration

Signature:

frappe.utils.format_duration(seconds, hide_days=False)
function Convert the given duration value in float(seconds) to duration format. example: convert 12885 to '3h 34m 45s' where 12885 = seconds in float
frappe.utils.get_weekdays

Signature:

frappe.utils.get_weekdays() -> list[str]
function Return a list of weekday names. Return value: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
frappe.utils.get_weekday

Signature:

frappe.utils.get_weekday(datetime: str | datetime.date | datetime.datetime | None = None) -> str
function Return the weekday name (e.g. 'Sunday') for the given datetime like object (datetime.date, datetime.datetime, string). If `datetime` argument is not provided, the current weekday name is returned.
frappe.utils.get_month

Signature:

frappe.utils.get_month(datetime: str | datetime.date | datetime.datetime | None = None) -> str
function Return the month name (e.g. 'January') for the given datetime like object (datetime.date, datetime.datetime, string). If `datetime` argument is not provided, the current month name is returned.
frappe.utils.get_timespan_date_range

Signature:

frappe.utils.get_timespan_date_range(timespan: Literal['last week', 'last month', 'last quarter', 'last 6 months', 'last year', 'yesterday', 'today', 'tomorrow', 'this week', 'this month', 'this quarter', 'this year', 'next week', 'next month', 'next quarter', 'next 6 months', 'next year']) -> tuple[datetime.datetime, datetime.datetime] | None
function Return the date range (start_date, end_date) tuple for the given timespan.
frappe.utils.global_date_format

Signature:

frappe.utils.global_date_format(date: str | datetime.date | datetime.datetime, format='long') -> str
function Return localized date in the form of 'January 1, 2012'.
frappe.utils.has_common

Signature:

frappe.utils.has_common(l1: Hashable, l2: Hashable) -> bool
function Return truthy value if there are common elements in lists l1 and l2.
frappe.utils.flt

Signature:

frappe.utils.flt(s: int | float | str | None, precision: int | None = None, rounding_method: str | None = None) -> float
function Convert to float (ignoring commas in string). :param s: Number in string or other numeric format. :param precision: optional argument to specify precision for rounding. :returns: Converted number in python float type. Return 0 if input can not be converted to float. Examples: >>> flt("43.5", precision=0) 44 >>> flt("42.5", precision=0) 42 >>> flt("10,500.5666", precision=2) 10500.57 >>> flt("a") 0.0 >>> flt(None) 0.0
frappe.utils.cint

Signature:

frappe.utils.cint(s: int | float | str | None, default: int = 0) -> int
function Convert to integer. :param s: Number in string or other numeric format. :returns: Converted number in python integer type. Return default if input cannot be converted to integer. Examples: >>> cint("100") 100 >>> cint("a") 0 >>> cint(None) 0
frappe.utils.floor

Signature:

frappe.utils.floor(s: int | float | str) -> int
function Return a number representing the largest integer less than or equal to the specified number.
frappe.utils.ceil

Signature:

frappe.utils.ceil(s: int | float | str) -> int
function Return the smallest integer greater than or equal to the given number.
frappe.utils.cstr

Signature:

frappe.utils.cstr(s, encoding='utf-8') -> str
function Convert the given argument to string.
frappe.utils.rounded

Signature:

frappe.utils.rounded(num, precision=0, rounding_method=None)
function Round according to method set in system setting, defaults to banker's rounding
frappe.utils.remainder

Signature:

frappe.utils.remainder(numerator: int | float, denominator: int | float, precision: int = 2) -> int | float
function Return the remainder of the division of `numerator` by `denominator`.
frappe.utils.safe_div

Signature:

frappe.utils.safe_div(numerator: int | float, denominator: int | float, precision: int = 2) -> float
function SafeMath division that returns zero when divided by zero.
frappe.utils.round_based_on_smallest_currency_fraction

Signature:

frappe.utils.round_based_on_smallest_currency_fraction(value, currency, precision=2)
function
frappe.utils.encode

Signature:

frappe.utils.encode(obj, encoding='utf-8')
function
frappe.utils.parse_val

Signature:

frappe.utils.parse_val(v)
function Convert to simple datatypes from SQL query results.
frappe.utils.fmt_money

Signature:

frappe.utils.fmt_money(amount: str | float | int | None, precision: int | None = None, currency: str | None = None, format: str | None = None) -> str
function Convert to string with commas for thousands, millions etc.
frappe.utils.get_number_format_info

Signature:

frappe.utils.get_number_format_info(format: str) -> tuple[str, str, int]
function DEPRECATED: use `NumberFormat.from_string()` from `frappe.utils.number_format` instead. Return the decimal separator, thousands separator and precision for the given number `format` string. e.g. get_number_format_info('#,##,###.##') -> ('.', ',', 2) Will return ('.', ',', 2) for format strings which can't be guessed.
frappe.utils.money_in_words

Signature:

frappe.utils.money_in_words(number: str | float | int, main_currency: str | None = None, fraction_currency: str | None = None)
function Return string in words with currency and fraction currency.
frappe.utils.in_words

Signature:

frappe.utils.in_words(integer: int, in_million=True) -> str
function Return string in words for the given integer.
frappe.utils.is_html

Signature:

frappe.utils.is_html(text: str) -> bool
function Return True if the given `text` contains any HTML tags.
frappe.utils.is_image

Signature:

frappe.utils.is_image(filepath: str) -> bool
function Return True if the given `filepath` points to an image file.
frappe.utils.get_thumbnail_base64_for_image

Signature:

frappe.utils.get_thumbnail_base64_for_image(src: str) -> dict[str, str] | None
function Return the base64 encoded string for the thumbnail of the given image source path. Example return value: { "base64": "data:image/ext;base64,...", "width": 50, "height": 50 }
frappe.utils.image_to_base64

Signature:

frappe.utils.image_to_base64(image: 'PILImageFile', extn: str) -> bytes
function Return the base64 encoded string for the given PIL `ImageFile`.
frappe.utils.pdf_to_base64

Signature:

frappe.utils.pdf_to_base64(filename: str) -> bytes | None
function Return the base64 encoded string for the given PDF file. Return None if the file is not found or is not a PDF file.
frappe.utils.strip_html

Signature:

frappe.utils.strip_html(text: str) -> str
function Remove anything enclosed in and including <>.
frappe.utils.escape_html

Signature:

frappe.utils.escape_html(text: str) -> str
function Return the given text with HTML special characters escaped. e.g. '<h1>Hello</h1>' -> '&lt;h1&gt;Hello&lt;/h1&gt;'
frappe.utils.pretty_date

Signature:

frappe.utils.pretty_date(iso_datetime: datetime.datetime | str) -> str
function Return a localized string representation of the delta to the current system time. For example, "1 hour ago", "2 days ago", "in 5 seconds", etc.
frappe.utils.comma_or

Signature:

frappe.utils.comma_or(some_list: list | tuple, add_quotes=True) -> str
function Return the given list or tuple as a comma separated string with the last item joined by 'or'. e.g. ['a', 'b', 'c'] -> 'a, b or c' If `add_quotes` is True, each item in the list will be wrapped in single quotes. e.g. ['a', 'b', 'c'] -> "'a', 'b' or 'c'"
frappe.utils.comma_and

Signature:

frappe.utils.comma_and(some_list: list | tuple, add_quotes=True) -> str
function Return the given list or tuple as a comma separated string with the last item joined by 'and'. e.g. ['a', 'b', 'c'] -> 'a, b and c' If `add_quotes` is True, each item in the list will be wrapped in single quotes. e.g. ['a', 'b', 'c'] -> "'a', 'b' and 'c'"
frappe.utils.comma_sep

Signature:

frappe.utils.comma_sep(some_list: list | tuple, pattern: str, add_quotes=True) -> str
function Return the given list or tuple as a comma separated string, with the last item joined by the given string format pattern. If `add_quotes` is True, each item in the list will be wrapped in single quotes. e.g. if `some_list` is ['a', 'b', 'c'] and `pattern` is '{0} or {1}', the output will be 'a, b or c'
frappe.utils.new_line_sep

Signature:

frappe.utils.new_line_sep(some_list: list | tuple) -> str
function Return the given list or tuple as a new line separated string. e.g. ['', 'Paid', 'Unpaid'] -> ' Paid Unpaid'
frappe.utils.filter_strip_join

Signature:

frappe.utils.filter_strip_join(some_list: list[str], sep: str) -> list[str]
function given a list, filter None values, strip spaces and join
frappe.utils.get_url

Signature:

frappe.utils.get_url(uri: str | None = None, full_address: bool = False) -> str
function Get app url from request.
frappe.utils.get_host_name_from_request

Signature:

frappe.utils.get_host_name_from_request() -> str
function Return the hostname (`request.host`) from the request headers.
frappe.utils.url_contains_port

Signature:

frappe.utils.url_contains_port(url: str) -> bool
function Return True if the given url contains a port number. e.g. 'http://localhost:8000' -> True, 'http://localhost' -> False.
frappe.utils.get_host_name

Signature:

frappe.utils.get_host_name() -> str
function Return the hostname of the current site. e.g. If site is 'https://cloud.frappe.io', returns 'cloud.frappe.io'.
frappe.utils.get_link_to_form

Signature:

frappe.utils.get_link_to_form(doctype: str, name: str | None = None, label: str | None = None) -> str
function Return the HTML link to the given document's form view. e.g. get_link_to_form("Sales Invoice", "INV-0001", "Link Label") returns: '<a href="https://frappe.io/app/sales-invoice/INV-0001">Link Label</a>'.
frappe.utils.get_link_to_report

Signature:

frappe.utils.get_link_to_report(name: str, label: str | None = None, report_type: str | None = None, doctype: str | None = None, filters: dict | None = None) -> str
function Return the HTML link to the given report. e.g. get_link_to_report("Revenue Report", "Link Label") returns: '<a href="https://frappe.io/app/query-report/Revenue%20Report">Link Label</a>'.
frappe.utils.get_absolute_url

Signature:

frappe.utils.get_absolute_url(doctype: str, name: str) -> str
function Return the absolute route for the form view of the given document in the desk. e.g. when doctype="Sales Invoice" and name="INV-00001", returns '/app/sales-invoice/INV-00001'
frappe.utils.get_url_to_form

Signature:

frappe.utils.get_url_to_form(doctype: str, name: str | None = None) -> str
function Return the absolute URL for the form view of the given document in the desk. e.g. when doctype="Sales Invoice" and your site URL is "https://frappe.io", returns 'https://frappe.io/app/sales-invoice/INV-00001'
frappe.utils.get_url_to_list

Signature:

frappe.utils.get_url_to_list(doctype: str) -> str
function Return the absolute URL for the list view of the given document in the desk. e.g. when doctype="Sales Invoice" and your site URL is "https://frappe.io", returns 'https://frappe.io/app/sales-invoice'
frappe.utils.get_url_to_report

Signature:

frappe.utils.get_url_to_report(name, report_type: str | None = None, doctype: str | None = None) -> str
function Return the absolute URL for the report in the desk. e.g. when name="Sales Register" and your site URL is "https://frappe.io", returns 'https://frappe.io/app/query-report/Sales%20Register' You can optionally pass `report_type` and `doctype` to get the URL for a Report Builder report. get_url_to_report("Revenue", "Report Builder", "Sales Invoice") -> 'https://frappe.io/app/sales-invoice/view/report/Revenue'
frappe.utils.get_url_to_report_with_filters

Signature:

frappe.utils.get_url_to_report_with_filters(name, filters, report_type=None, doctype=None)
function Return the absolute URL for the report in the desk with filters.
frappe.utils.evaluate_filters

Signature:

frappe.utils.evaluate_filters(doc: 'Mapping', filters: frappe.types.filter.Filters | frappe.types.filter.FilterTuple | collections.abc.Mapping[str, str | int | float | None | datetime.datetime | datetime.date | pypika.queries.Column | frappe.types.docref.DocRef | bool | tuple[str, str | int | float | None | datetime.datetime | datetime.date | pypika.queries.Column | frappe.types.docref.DocRef | bool | collections.abc.Sequence[str | int | float | None | datetime.datetime | datetime.date | pypika.queries.Column | frappe.types.docref.DocRef | bool]]] | tuple[str, str | int | float | None | datetime.datetime | datetime.date | pypika.queries.Column | frappe.types.docref.DocRef | bool | collections.abc.Sequence[str | int | float | None | datetime.datetime | datetime.date | pypika.queries.Column | frappe.types.docref.DocRef | bool]] | tuple[str, str, str | int | float | None | datetime.datetime | datetime.date | pypika.queries.Column | frappe.types.docref.DocRef | bool | collections.abc.Sequence[str | int | float | None | datetime.datetime | datetime.date | pypika.queries.Column | frappe.types.docref.DocRef | bool]] | tuple[str, str, str, str | int | float | None | datetime.datetime | datetime.date | pypika.queries.Column | frappe.types.docref.DocRef | bool | collections.abc.Sequence[str | int | float | None | datetime.datetime | datetime.date | pypika.queries.Column | frappe.types.docref.DocRef | bool]])
function Return True if doc matches filters.
frappe.utils.compare

Signature:

frappe.utils.compare(val1: Any, condition: str, val2: Any, fieldtype: str | None = None)
function
frappe.utils.get_filter

Signature:

frappe.utils.get_filter(doctype: str, filters: frappe.types.filter.Filters | frappe.types.filter.FilterTuple | collections.abc.Mapping[str, str | int | float | None | datetime.datetime | datetime.date | pypika.queries.Column | frappe.types.docref.DocRef | bool | tuple[str, str | int | float | None | datetime.datetime | datetime.date | pypika.queries.Column | frappe.types.docref.DocRef | bool | collections.abc.Sequence[str | int | float | None | datetime.datetime | datetime.date | pypika.queries.Column | frappe.types.docref.DocRef | bool]]] | tuple[str, str | int | float | None | datetime.datetime | datetime.date | pypika.queries.Column | frappe.types.docref.DocRef | bool | collections.abc.Sequence[str | int | float | None | datetime.datetime | datetime.date | pypika.queries.Column | frappe.types.docref.DocRef | bool]] | tuple[str, str, str | int | float | None | datetime.datetime | datetime.date | pypika.queries.Column | frappe.types.docref.DocRef | bool | collections.abc.Sequence[str | int | float | None | datetime.datetime | datetime.date | pypika.queries.Column | frappe.types.docref.DocRef | bool]] | tuple[str, str, str, str | int | float | None | datetime.datetime | datetime.date | pypika.queries.Column | frappe.types.docref.DocRef | bool | collections.abc.Sequence[str | int | float | None | datetime.datetime | datetime.date | pypika.queries.Column | frappe.types.docref.DocRef | bool]], filters_config=None) -> 'frappe._dict'
function Return a `_dict` like: { "doctype": ... "fieldname": ... "operator": ... "value": ... "fieldtype": ... }
frappe.utils.make_filter_tuple

Signature:

frappe.utils.make_filter_tuple(doctype, key, value)
function return a filter tuple like [doctype, key, operator, value]
frappe.utils.make_filter_dict

Signature:

frappe.utils.make_filter_dict(filters)
function convert this [[doctype, key, operator, value], ..] to this { key: (operator, value), .. }
frappe.utils.sanitize_column

Signature:

frappe.utils.sanitize_column(column_name: str) -> None
function
frappe.utils.scrub_urls

Signature:

frappe.utils.scrub_urls(html: str) -> str
function Expand relative urls in the given `html`. e.g. If HTML is '<a href="/files/abc.jpeg">View Image</a>' and site URL is 'https://frappe.io', returns '<a href="https://frappe.io/files/abc.jpeg">View Image</a>'.
frappe.utils.expand_relative_urls

Signature:

frappe.utils.expand_relative_urls(html: str) -> str
function Expand relative urls in the given `html`. e.g. If HTML is '<a href="/files/abc.jpeg">View Image</a>' and site URL is 'https://frappe.io', returns '<a href="https://frappe.io/files/abc.jpeg">View Image</a>'.
frappe.utils.quoted

Signature:

frappe.utils.quoted(url: str) -> str
function Return the given `url` quoted. e.g. 'https://frappe.io/files/my Image file.jpeg' -> 'https://frappe.io/files/my%20Image%20file.jpeg'
frappe.utils.quote_urls

Signature:

frappe.utils.quote_urls(html: str) -> str
function
frappe.utils.unique

Signature:

frappe.utils.unique(seq: Sequence[ForwardRef('T')]) -> list['T']
function use this instead of list(set()) to preserve order of the original list. Thanks to Stackoverflow: http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order
frappe.utils.strip

Signature:

frappe.utils.strip(val: str, chars: str | None = None) -> str
function Strip the given characters from the given string. e.g. strip(',hello,bye,', ',') -> 'hello,bye'
frappe.utils.to_markdown

Signature:

frappe.utils.to_markdown(html: str) -> str
function Convert the given HTML to markdown and returns it.
frappe.utils.md_to_html

Signature:

frappe.utils.md_to_html(markdown_text: str) -> Optional[ForwardRef('UnicodeWithAttrs')]
function Convert the given markdown text to HTML and returns it.
frappe.utils.markdown

Signature:

frappe.utils.markdown(markdown_text: str) -> Optional[ForwardRef('UnicodeWithAttrs')]
function Convert the given markdown text to HTML and returns it.
frappe.utils.is_subset

Signature:

frappe.utils.is_subset(list_a: list, list_b: list) -> bool
function Return whether list_a is a subset of list_b.
frappe.utils.generate_hash

Signature:

frappe.utils.generate_hash(*args, **kwargs) -> str
function Generates a random hash using best available randomness source and returns it. You can optionally provide the `length` of the hash to be generated. Default is 56.
frappe.utils.get_user_info_for_avatar

Signature:

frappe.utils.get_user_info_for_avatar(user_id: str) -> frappe.utils.data._UserInfo
function Return user info for the given `user_id` suitable for use in an avatar. e.g. { "email": "faris@frappe.io", "image": "/assets/frappe/images/ui/avatar.png", "name": "Faris Ansari" }
frappe.utils.add_trackers_to_url

Signature:

frappe.utils.add_trackers_to_url(url: str, source: str, campaign: str | None = None, medium: str | None = None, content: str | None = None) -> str
function
frappe.utils.parse_and_map_trackers_from_url

Signature:

frappe.utils.parse_and_map_trackers_from_url(url: str, create: bool = False) -> dict
function
frappe.utils.map_trackers

Signature:

frappe.utils.map_trackers(url_trackers: dict, create: bool = False)
function

frappe.website

Name Type docs
frappe.website.abs_url

Signature:

frappe.website.abs_url(path)
function Deconstructs and Reconstructs a URL into an absolute URL or a URL relative from root '/'
frappe.website.extract_title

Signature:

frappe.website.extract_title(source, path)
function Return title from `&lt;!-- title --&gt;` or &lt;h1&gt; or path.
frappe.website.get_boot_data

Signature:

frappe.website.get_boot_data()
function
frappe.website.get_home_page

Signature:

frappe.website.get_home_page()
function
frappe.website.get_html_content_based_on_type

Signature:

frappe.website.get_html_content_based_on_type(doc, fieldname, content_type)
function Set content based on content_type

json

Name Type docs
json.loads

Signature:

json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
function Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance containing a JSON document) to a Python object. ``object_hook`` is an optional function that will be called with the result of any object literal decode (a ``dict``). The return value of ``object_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). ``object_pairs_hook`` is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of ``object_pairs_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders. If ``object_hook`` is also defined, the ``object_pairs_hook`` takes priority. ``parse_float``, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). ``parse_int``, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float). ``parse_constant``, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN. This can be used to raise an exception if invalid JSON numbers are encountered. To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg; otherwise ``JSONDecoder`` is used.
json.dumps

Signature:

json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
function Serialize ``obj`` to a JSON formatted ``str``. If ``skipkeys`` is true then ``dict`` keys that are not basic types (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped instead of raising a ``TypeError``. If ``ensure_ascii`` is false, then the return value can contain non-ASCII characters if they appear in strings contained in ``obj``. Otherwise, all such characters are escaped in JSON strings. If ``check_circular`` is false, then the circular reference check for container types will be skipped and a circular reference will result in an ``RecursionError`` (or worse). If ``allow_nan`` is false, then it will be a ``ValueError`` to serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). If ``indent`` is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. ``None`` is the most compact representation. If specified, ``separators`` should be an ``(item_separator, key_separator)`` tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and ``(',', ': ')`` otherwise. To get the most compact JSON representation, you should specify ``(',', ':')`` to eliminate whitespace. ``default(obj)`` is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. If *sort_keys* is true (default: ``False``), then the output of dictionaries will be sorted by key. To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg; otherwise ``JSONEncoder`` is used.

Exceptions

Name
frappe.NotFound
frappe.SiteNotSpecifiedError
frappe.DatabaseModificationError
frappe.UrlSchemeNotSupported
frappe.ValidationError
frappe.FrappeTypeError
frappe.AuthenticationError
frappe.SessionExpired
frappe.PermissionError
frappe.DoesNotExistError
frappe.PageDoesNotExistError
frappe.NameError
frappe.OutgoingEmailError
frappe.SessionStopped
frappe.UnsupportedMediaType
frappe.RequestToken
frappe.Redirect
frappe.CSRFTokenError
frappe.TooManyRequestsError
frappe.ImproperDBConfigurationError
frappe.DuplicateEntryError
frappe.DataError
frappe.UnknownDomainError
frappe.MappingMismatchError
frappe.InvalidStatusError
frappe.MandatoryError
frappe.NonNegativeError
frappe.InvalidSignatureError
frappe.RateLimitExceededError
frappe.CannotChangeConstantError
frappe.CharacterLengthExceededError
frappe.UpdateAfterSubmitError
frappe.LinkValidationError
frappe.CancelledLinkError
frappe.DocstatusTransitionError
frappe.TimestampMismatchError
frappe.EmptyTableError
frappe.LinkExistsError
frappe.InvalidEmailAddressError
frappe.InvalidNameError
frappe.InvalidPhoneNumberError
frappe.TemplateNotFoundError
frappe.UniqueValidationError
frappe.AppNotInstalledError
frappe.IncorrectSitePath
frappe.ImplicitCommitError
frappe.RetryBackgroundJobError
frappe.DocumentLockedError
frappe.CircularLinkingError
frappe.SecurityException
frappe.InvalidColumnName
frappe.IncompatibleApp
frappe.InvalidDates
frappe.DataTooLongException
frappe.FileAlreadyAttachedException
frappe.DocumentAlreadyRestored
frappe.AttachmentLimitReached
frappe.QueryTimeoutError
frappe.QueryDeadlockError
frappe.InReadOnlyMode
frappe.SessionBootFailed
frappe.PrintFormatError
frappe.TooManyWritesError
frappe.InvalidAuthorizationHeader
frappe.InvalidAuthorizationPrefix
frappe.InvalidAuthorizationToken
frappe.InvalidDatabaseFile
frappe.ExecutableNotFound
frappe.InvalidRoundingMethod
frappe.InvalidRemoteException
frappe.LinkExpired
frappe.InvalidKeyError
frappe.CommandFailedError
ArithmeticError
AssertionError
AttributeError
BufferError
BytesWarning
DeprecationWarning
EOFError
EnvironmentError
Exception
FloatingPointError
FutureWarning
IOError
ImportError
ImportWarning
IndentationError
IndexError
KeyError
LookupError
MemoryError
NameError
NotImplementedError
OSError
OverflowError
PendingDeprecationWarning
ReferenceError
RuntimeError
RuntimeWarning
StopIteration
SyntaxError
SyntaxWarning
SystemError
TabError
TypeError
UnboundLocalError
UnicodeDecodeError
UnicodeEncodeError
UnicodeError
UnicodeTranslateError
UnicodeWarning
UserWarning
ValueError
Warning
ZeroDivisionError