i have created some custom field in customer master like… ECC_NO,GST NO, & more…
How to call mensioned field like ECC_NO & Other which have with customer records.
Question is how to pull ECC_NO in Customise print formate i.e Sales invoice printing HTML formate ???
Write this code in your custom print format.
{% set c = frappe.get_doc("Customer", doc.customer) %}
{{ c.territory or '' }}
{{ c.customer_group or '' }}
{{ c.credit_days or '' }}
{{ c.ECC_NO }}
{{ c.GST NO }}
I have found below error message with this change…see below
Traceback (innermost last):
File “/home/erpadmin/frappe-bench/apps/frappe/frappe/app.py”, line 49, in application
response = frappe.handler.handle()
File “/home/erpadmin/frappe-bench/apps/frappe/frappe/handler.py”, line 66, in handle
execute_cmd(cmd)
File “/home/erpadmin/frappe-bench/apps/frappe/frappe/handler.py”, line 89, in execute_cmd
ret = frappe.call(method, **frappe.form_dict)
File “/home/erpadmin/frappe-bench/apps/frappe/frappe/init.py”, line 532, in call
return fn(*args, **newargs)
File “/home/erpadmin/frappe-bench/apps/frappe/frappe/templates/pages/print.py”, line 86, in get_html
html = template.render(args, filters={“len”: len})
File “/home/erpadmin/frappe-bench/env/local/lib/python2.7/site-packages/jinja2/environment.py”, line 969, in render
return self.environment.handle_exception(exc_info, True)
File “/home/erpadmin/frappe-bench/env/local/lib/python2.7/site-packages/jinja2/environment.py”, line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "
Can you share your code?
app.py
import os
from .utils import exec_cmd, get_frappe, check_git_for_shallow_clone, get_config, build_assets, restart_supervisor_processes, get_cmd_output
import logging
import requests
import json
logger = logging.getLogger(name)
def get_apps(bench=‘.’):
try:
with open(os.path.join(bench, ‘sites’, ‘apps.txt’)) as f:
return f.read().strip().split(‘\n’)
except IOError:
return []
def add_to_appstxt(app, bench=‘.’):
apps = get_apps(bench=bench)
if app not in apps:
apps.append(app)
return write_appstxt(apps, bench=bench)
def remove_from_appstxt(app, bench=‘.’):
apps = get_apps(bench=bench)
if app in apps:
apps.remove(app)
return write_appstxt(apps, bench=bench)
def write_appstxt(apps, bench=‘.’):
with open(os.path.join(bench, ‘sites’, ‘apps.txt’), ‘w’) as f:
return f.write(‘\n’.join(apps))
def get_app(app, git_url, branch=None, bench=‘.’, build_asset_files=True):
logger.info(‘getting app {}’.format(app))
shallow_clone = ‘–depth 1’ if check_git_for_shallow_clone() and get_config().get(‘shallow_clone’) else ‘’
branch = ‘–branch {branch}’.format(branch=branch) if branch else ‘’
exec_cmd(“git clone {git_url} {branch} {shallow_clone} --origin upstream {app}”.format(
git_url=git_url,
app=app,
shallow_clone=shallow_clone,
branch=branch),
cwd=os.path.join(bench, ‘apps’))
print ‘installing’, app
install_app(app, bench=bench)
if build_asset_files:
build_assets(bench=bench)
conf = get_config()
if conf.get(‘restart_supervisor_on_update’):
restart_supervisor_processes(bench=bench)
def new_app(app, bench=‘.’):
logger.info(‘creating new app {}’.format(app))
exec_cmd(“{frappe} --make_app {apps} {app}”.format(frappe=get_frappe(bench=bench),
apps=os.path.join(bench, ‘apps’), app=app))
install_app(app, bench=bench)
def install_app(app, bench=‘.’):
logger.info(‘installing {}’.format(app))
conf = get_config()
find_links = ‘–find-links={}’.format(conf.get(‘wheel_cache_dir’)) if conf.get(‘wheel_cache_dir’) else ‘’
exec_cmd(“{pip} install -q {find_links} -e {app}”.format(
pip=os.path.join(bench, ‘env’, ‘bin’, ‘pip’),
app=os.path.join(bench, ‘apps’, app),
find_links=find_links))
add_to_appstxt(app, bench=bench)
def pull_all_apps(bench=‘.’):
apps_dir = os.path.join(bench, ‘apps’)
apps = [app for app in os.listdir(apps_dir) if os.path.isdir(os.path.join(apps_dir, app))]
rebase = ‘–rebase’ if get_config().get(‘rebase_on_pull’) else ‘’
for app in apps:
app_dir = os.path.join(apps_dir, app)
if os.path.exists(os.path.join(app_dir, ‘.git’)):
logger.info(‘pulling {0}’.format(app))
exec_cmd(“git pull {rebase} upstream {branch}”.format(rebase=rebase, branch=get_current_branch(app_dir)), cwd=app_dir)
def get_current_branch(repo_dir):
return get_cmd_output(“basename $(git symbolic-ref -q HEAD)”, cwd=repo_dir)
def install_apps_from_path(path, bench=‘.’):
apps = get_apps_json(path)
for app in apps:
get_app(app[‘name’], app[‘url’], branch=app.get(‘branch’), bench=bench, build_asset_files=False)
build_assets(bench=bench)
def get_apps_json(path):
if path.startswith(‘http’):
r = requests.get(path)
return r.json()
else:
with open(path) as f:
return json.load(f)
environment.py
-- coding: utf-8 --
“”"
jinja2.environment
~~~~~~~~~~~~~~~~~~
Provides a class that holds runtime and parsing time options.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
“”"
import os
import sys
from jinja2 import nodes
from jinja2.defaults import BLOCK_START_STRING,
BLOCK_END_STRING, VARIABLE_START_STRING, VARIABLE_END_STRING,
COMMENT_START_STRING, COMMENT_END_STRING, LINE_STATEMENT_PREFIX,
LINE_COMMENT_PREFIX, TRIM_BLOCKS, NEWLINE_SEQUENCE,
DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE,
KEEP_TRAILING_NEWLINE, LSTRIP_BLOCKS
from jinja2.lexer import get_lexer, TokenStream
from jinja2.parser import Parser
from jinja2.nodes import EvalContext
from jinja2.optimizer import optimize
from jinja2.compiler import generate
from jinja2.runtime import Undefined, new_context
from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound,
TemplatesNotFound, TemplateRuntimeError
from jinja2.utils import import_string, LRUCache, Markup, missing,
concat, consume, internalcode
from jinja2._compat import imap, ifilter, string_types, iteritems,
text_type, reraise, implements_iterator, implements_to_string,
get_next, encode_filename, PY2, PYPY
from functools import reduce
for direct template usage we have up to ten living environments
_spontaneous_environments = LRUCache(10)
the function to create jinja traceback objects. This is dynamically
imported on the first exception in the exception handler.
_make_traceback = None
def get_spontaneous_environment(*args):
“”“Return a new spontaneous environment. A spontaneous environment is an
unnamed and unaccessible (in theory) environment that is used for
templates generated from a string and not from the file system.
“””
try:
env = _spontaneous_environments.get(args)
except TypeError:
return Environment(*args)
if env is not None:
return env
_spontaneous_environments[args] = env = Environment(*args)
env.shared = True
return env
def create_cache(size):
“”“Return the cache class for the given size.”“”
if size == 0:
return None
if size < 0:
return {}
return LRUCache(size)
def copy_cache(cache):
“”“Create an empty copy of the given cache.”“”
if cache is None:
return None
elif type(cache) is dict:
return {}
return LRUCache(cache.capacity)
def load_extensions(environment, extensions):
“”“Load the extensions from the list and bind it to the environment.
Returns a dict of instantiated environments.
“””
result = {}
for extension in extensions:
if isinstance(extension, string_types):
extension = import_string(extension)
result[extension.identifier] = extension(environment)
return result
def _environment_sanity_check(environment):
“”“Perform a sanity check on the environment.”“”
assert issubclass(environment.undefined, Undefined), ‘undefined must ’
‘be a subclass of undefined because filters depend on it.’
assert environment.block_start_string !=
environment.variable_start_string !=
environment.comment_start_string, ‘block, variable and comment ’
‘start strings must be different’
assert environment.newline_sequence in (’\r’, ‘\r\n’, ‘\n’),
‘newline_sequence set to unknown line ending string.’
return environment
class Environment(object):
r"""The core component of Jinja is the Environment
. It contains
important shared variables like configuration, filters, tests,
globals and others. Instances of this class may be modified if
they are not shared and if no template was loaded so far.
Modifications on environments after the first template was loaded
will lead to surprising effects and undefined behavior.
Here the possible initialization parameters:
`block_start_string`
The string marking the begin of a block. Defaults to ``'{%'``.
`block_end_string`
The string marking the end of a block. Defaults to ``'%}'``.
`variable_start_string`
The string marking the begin of a print statement.
Defaults to ``'{{'``.
`variable_end_string`
The string marking the end of a print statement. Defaults to
``'}}'``.
`comment_start_string`
The string marking the begin of a comment. Defaults to ``'{#'``.
`comment_end_string`
The string marking the end of a comment. Defaults to ``'#}'``.
`line_statement_prefix`
If given and a string, this will be used as prefix for line based
statements. See also :ref:`line-statements`.
`line_comment_prefix`
If given and a string, this will be used as prefix for line based
based comments. See also :ref:`line-statements`.
.. versionadded:: 2.2
`trim_blocks`
If this is set to ``True`` the first newline after a block is
removed (block, not variable tag!). Defaults to `False`.
`lstrip_blocks`
If this is set to ``True`` leading spaces and tabs are stripped
from the start of a line to a block. Defaults to `False`.
`newline_sequence`
The sequence that starts a newline. Must be one of ``'\r'``,
``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a
useful default for Linux and OS X systems as well as web
applications.
`keep_trailing_newline`
Preserve the trailing newline when rendering templates.
The default is ``False``, which causes a single newline,
if present, to be stripped from the end of the template.
.. versionadded:: 2.7
`extensions`
List of Jinja extensions to use. This can either be import paths
as strings or extension classes. For more information have a
look at :ref:`the extensions documentation <jinja-extensions>`.
`optimized`
should the optimizer be enabled? Default is `True`.
`undefined`
:class:`Undefined` or a subclass of it that is used to represent
undefined values in the template.
`finalize`
A callable that can be used to process the result of a variable
expression before it is output. For example one can convert
`None` implicitly into an empty string here.
`autoescape`
If set to true the XML/HTML autoescaping feature is enabled by
default. For more details about auto escaping see
:class:`~jinja2.utils.Markup`. As of Jinja 2.4 this can also
be a callable that is passed the template name and has to
return `True` or `False` depending on autoescape should be
enabled by default.
.. versionchanged:: 2.4
`autoescape` can now be a function
`loader`
The template loader for this environment.
`cache_size`
The size of the cache. Per default this is ``50`` which means
that if more than 50 templates are loaded the loader will clean
out the least recently used template. If the cache size is set to
``0`` templates are recompiled all the time, if the cache size is
``-1`` the cache will not be cleaned.
`auto_reload`
Some loaders load templates from locations where the template
sources may change (ie: file system or database). If
`auto_reload` is set to `True` (default) every time a template is
requested the loader checks if the source changed and if yes, it
will reload the template. For higher performance it's possible to
disable that.
`bytecode_cache`
If set to a bytecode cache object, this object will provide a
cache for the internal Jinja bytecode so that templates don't
have to be parsed if they were not changed.
See :ref:`bytecode-cache` for more information.
"""
#: if this environment is sandboxed. Modifying this variable won't make
#: the environment sandboxed though. For a real sandboxed environment
#: have a look at jinja2.sandbox. This flag alone controls the code
#: generation by the compiler.
sandboxed = False
#: True if the environment is just an overlay
overlayed = False
#: the environment this environment is linked to if it is an overlay
linked_to = None
#: shared environments have this set to `True`. A shared environment
#: must not be modified
shared = False
#: these are currently EXPERIMENTAL undocumented features.
exception_handler = None
exception_formatter = None
def __init__(self,
block_start_string=BLOCK_START_STRING,
block_end_string=BLOCK_END_STRING,
variable_start_string=VARIABLE_START_STRING,
variable_end_string=VARIABLE_END_STRING,
comment_start_string=COMMENT_START_STRING,
comment_end_string=COMMENT_END_STRING,
line_statement_prefix=LINE_STATEMENT_PREFIX,
line_comment_prefix=LINE_COMMENT_PREFIX,
trim_blocks=TRIM_BLOCKS,
lstrip_blocks=LSTRIP_BLOCKS,
newline_sequence=NEWLINE_SEQUENCE,
keep_trailing_newline=KEEP_TRAILING_NEWLINE,
extensions=(),
optimized=True,
undefined=Undefined,
finalize=None,
autoescape=False,
loader=None,
cache_size=50,
auto_reload=True,
bytecode_cache=None):
# !!Important notice!!
# The constructor accepts quite a few arguments that should be
# passed by keyword rather than position. However it's important to
# not change the order of arguments because it's used at least
# internally in those cases:
# - spontaneous environments (i18n extension and Template)
# - unittests
# If parameter changes are required only add parameters at the end
# and don't change the arguments (or the defaults!) of the arguments
# existing already.
# lexer / parser information
self.block_start_string = block_start_string
self.block_end_string = block_end_string
self.variable_start_string = variable_start_string
self.variable_end_string = variable_end_string
self.comment_start_string = comment_start_string
self.comment_end_string = comment_end_string
self.line_statement_prefix = line_statement_prefix
self.line_comment_prefix = line_comment_prefix
self.trim_blocks = trim_blocks
self.lstrip_blocks = lstrip_blocks
self.newline_sequence = newline_sequence
self.keep_trailing_newline = keep_trailing_newline
# runtime information
self.undefined = undefined
self.optimized = optimized
self.finalize = finalize
self.autoescape = autoescape
# defaults
self.filters = DEFAULT_FILTERS.copy()
self.tests = DEFAULT_TESTS.copy()
self.globals = DEFAULT_NAMESPACE.copy()
# set the loader provided
self.loader = loader
self.cache = create_cache(cache_size)
self.bytecode_cache = bytecode_cache
self.auto_reload = auto_reload
# load extensions
self.extensions = load_extensions(self, extensions)
_environment_sanity_check(self)
def add_extension(self, extension):
"""Adds an extension after the environment was created.
.. versionadded:: 2.5
"""
self.extensions.update(load_extensions(self, [extension]))
def extend(self, **attributes):
"""Add the items to the instance of the environment if they do not exist
yet. This is used by :ref:`extensions <writing-extensions>` to register
callbacks and configuration values without breaking inheritance.
"""
for key, value in iteritems(attributes):
if not hasattr(self, key):
setattr(self, key, value)
def overlay(self, block_start_string=missing, block_end_string=missing,
variable_start_string=missing, variable_end_string=missing,
comment_start_string=missing, comment_end_string=missing,
line_statement_prefix=missing, line_comment_prefix=missing,
trim_blocks=missing, lstrip_blocks=missing,
extensions=missing, optimized=missing,
undefined=missing, finalize=missing, autoescape=missing,
loader=missing, cache_size=missing, auto_reload=missing,
bytecode_cache=missing):
"""Create a new overlay environment that shares all the data with the
current environment except of cache and the overridden attributes.
Extensions cannot be removed for an overlayed environment. An overlayed
environment automatically gets all the extensions of the environment it
is linked to plus optional extra extensions.
Creating overlays should happen after the initial environment was set
up completely. Not all attributes are truly linked, some are just
copied over so modifications on the original environment may not shine
through.
"""
args = dict(locals())
del args['self'], args['cache_size'], args['extensions']
rv = object.__new__(self.__class__)
rv.__dict__.update(self.__dict__)
rv.overlayed = True
rv.linked_to = self
for key, value in iteritems(args):
if value is not missing:
setattr(rv, key, value)
if cache_size is not missing:
rv.cache = create_cache(cache_size)
else:
rv.cache = copy_cache(self.cache)
rv.extensions = {}
for key, value in iteritems(self.extensions):
rv.extensions[key] = value.bind(rv)
if extensions is not missing:
rv.extensions.update(load_extensions(rv, extensions))
return _environment_sanity_check(rv)
lexer = property(get_lexer, doc="The lexer for this environment.")
def iter_extensions(self):
"""Iterates over the extensions by priority."""
return iter(sorted(self.extensions.values(),
key=lambda x: x.priority))
def getitem(self, obj, argument):
"""Get an item or attribute of an object but prefer the item."""
try:
return obj[argument]
except (TypeError, LookupError):
if isinstance(argument, string_types):
try:
attr = str(argument)
except Exception:
pass
else:
try:
return getattr(obj, attr)
except AttributeError:
pass
return self.undefined(obj=obj, name=argument)
def getattr(self, obj, attribute):
"""Get an item or attribute of an object but prefer the attribute.
Unlike :meth:`getitem` the attribute *must* be a bytestring.
"""
try:
return getattr(obj, attribute)
except AttributeError:
pass
try:
return obj[attribute]
except (TypeError, LookupError, AttributeError):
return self.undefined(obj=obj, name=attribute)
def call_filter(self, name, value, args=None, kwargs=None,
context=None, eval_ctx=None):
"""Invokes a filter on a value the same way the compiler does it.
.. versionadded:: 2.7
"""
func = self.filters.get(name)
if func is None:
raise TemplateRuntimeError('no filter named %r' % name)
args = [value] + list(args or ())
if getattr(func, 'contextfilter', False):
if context is None:
raise TemplateRuntimeError('Attempted to invoke context '
'filter without context')
args.insert(0, context)
elif getattr(func, 'evalcontextfilter', False):
if eval_ctx is None:
if context is not None:
eval_ctx = context.eval_ctx
else:
eval_ctx = EvalContext(self)
args.insert(0, eval_ctx)
elif getattr(func, 'environmentfilter', False):
args.insert(0, self)
return func(*args, **(kwargs or {}))
def call_test(self, name, value, args=None, kwargs=None):
"""Invokes a test on a value the same way the compiler does it.
.. versionadded:: 2.7
"""
func = self.tests.get(name)
if func is None:
raise TemplateRuntimeError('no test named %r' % name)
return func(value, *(args or ()), **(kwargs or {}))
@internalcode
def parse(self, source, name=None, filename=None):
"""Parse the sourcecode and return the abstract syntax tree. This
tree of nodes is used by the compiler to convert the template into
executable source- or bytecode. This is useful for debugging or to
extract information from templates.
If you are :ref:`developing Jinja2 extensions <writing-extensions>`
this gives you a good overview of the node tree generated.
"""
try:
return self._parse(source, name, filename)
except TemplateSyntaxError:
exc_info = sys.exc_info()
self.handle_exception(exc_info, source_hint=source)
def _parse(self, source, name, filename):
"""Internal parsing function used by `parse` and `compile`."""
return Parser(self, source, name, encode_filename(filename)).parse()
def lex(self, source, name=None, filename=None):
"""Lex the given sourcecode and return a generator that yields
tokens as tuples in the form ``(lineno, token_type, value)``.
This can be useful for :ref:`extension development <writing-extensions>`
and debugging templates.
This does not perform preprocessing. If you want the preprocessing
of the extensions to be applied you have to filter source through
the :meth:`preprocess` method.
"""
source = text_type(source)
try:
return self.lexer.tokeniter(source, name, filename)
except TemplateSyntaxError:
exc_info = sys.exc_info()
self.handle_exception(exc_info, source_hint=source)
def preprocess(self, source, name=None, filename=None):
"""Preprocesses the source with all extensions. This is automatically
called for all parsing and compiling methods but *not* for :meth:`lex`
because there you usually only want the actual source tokenized.
"""
return reduce(lambda s, e: e.preprocess(s, name, filename),
self.iter_extensions(), text_type(source))
def _tokenize(self, source, name, filename=None, state=None):
"""Called by the parser to do the preprocessing and filtering
for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.
"""
source = self.preprocess(source, name, filename)
stream = self.lexer.tokenize(source, name, filename, state)
for ext in self.iter_extensions():
stream = ext.filter_stream(stream)
if not isinstance(stream, TokenStream):
stream = TokenStream(stream, name, filename)
return stream
def _generate(self, source, name, filename, defer_init=False):
"""Internal hook that can be overridden to hook a different generate
method in.
continue environment…
.. versionadded:: 2.5
"""
return generate(source, self, name, filename, defer_init=defer_init)
def _compile(self, source, filename):
"""Internal hook that can be overridden to hook a different compile
method in.
.. versionadded:: 2.5
"""
return compile(source, filename, 'exec')
@internalcode
def compile(self, source, name=None, filename=None, raw=False,
defer_init=False):
"""Compile a node or template source code. The `name` parameter is
the load name of the template after it was joined using
:meth:`join_path` if necessary, not the filename on the file system.
the `filename` parameter is the estimated filename of the template on
the file system. If the template came from a database or memory this
can be omitted.
The return value of this method is a python code object. If the `raw`
parameter is `True` the return value will be a string with python
code equivalent to the bytecode returned otherwise. This method is
mainly used internally.
`defer_init` is use internally to aid the module code generator. This
causes the generated code to be able to import without the global
environment variable to be set.
.. versionadded:: 2.4
`defer_init` parameter added.
"""
source_hint = None
try:
if isinstance(source, string_types):
source_hint = source
source = self._parse(source, name, filename)
if self.optimized:
source = optimize(source, self)
source = self._generate(source, name, filename,
defer_init=defer_init)
if raw:
return source
if filename is None:
filename = '<template>'
else:
filename = encode_filename(filename)
return self._compile(source, filename)
except TemplateSyntaxError:
exc_info = sys.exc_info()
self.handle_exception(exc_info, source_hint=source)
def compile_expression(self, source, undefined_to_none=True):
"""A handy helper method that returns a callable that accepts keyword
arguments that appear as variables in the expression. If called it
returns the result of the expression.
This is useful if applications want to use the same rules as Jinja
in template "configuration files" or similar situations.
Example usage:
>>> env = Environment()
>>> expr = env.compile_expression('foo == 42')
>>> expr(foo=23)
False
>>> expr(foo=42)
True
Per default the return value is converted to `None` if the
expression returns an undefined value. This can be changed
by setting `undefined_to_none` to `False`.
>>> env.compile_expression('var')() is None
True
>>> env.compile_expression('var', undefined_to_none=False)()
Undefined
.. versionadded:: 2.1
"""
parser = Parser(self, source, state='variable')
exc_info = None
try:
expr = parser.parse_expression()
if not parser.stream.eos:
raise TemplateSyntaxError('chunk after expression',
parser.stream.current.lineno,
None, None)
expr.set_environment(self)
except TemplateSyntaxError:
exc_info = sys.exc_info()
if exc_info is not None:
self.handle_exception(exc_info, source_hint=source)
body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)]
template = self.from_string(nodes.Template(body, lineno=1))
return TemplateExpression(template, undefined_to_none)
def compile_templates(self, target, extensions=None, filter_func=None,
zip='deflated', log_function=None,
ignore_errors=True, py_compile=False):
"""Finds all the templates the loader can find, compiles them
and stores them in `target`. If `zip` is `None`, instead of in a
zipfile, the templates will be will be stored in a directory.
By default a deflate zip algorithm is used, to switch to
the stored algorithm, `zip` can be set to ``'stored'``.
`extensions` and `filter_func` are passed to :meth:`list_templates`.
Each template returned will be compiled to the target folder or
zipfile.
By default template compilation errors are ignored. In case a
log function is provided, errors are logged. If you want template
syntax errors to abort the compilation you can set `ignore_errors`
to `False` and you will get an exception on syntax errors.
If `py_compile` is set to `True` .pyc files will be written to the
target instead of standard .py files. This flag does not do anything
on pypy and Python 3 where pyc files are not picked up by itself and
don't give much benefit.
.. versionadded:: 2.4
"""
from jinja2.loaders import ModuleLoader
if log_function is None:
log_function = lambda x: None
if py_compile:
if not PY2 or PYPY:
from warnings import warn
warn(Warning('py_compile has no effect on pypy or Python 3'))
py_compile = False
else:
import imp, marshal
py_header = imp.get_magic() + \
u'\xff\xff\xff\xff'.encode('iso-8859-15')
# Python 3.3 added a source filesize to the header
if sys.version_info >= (3, 3):
py_header += u'\x00\x00\x00\x00'.encode('iso-8859-15')
def write_file(filename, data, mode):
if zip:
info = ZipInfo(filename)
info.external_attr = 0o755 << 16
zip_file.writestr(info, data)
else:
f = open(os.path.join(target, filename), mode)
try:
f.write(data)
finally:
f.close()
if zip is not None:
from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED
zip_file = ZipFile(target, 'w', dict(deflated=ZIP_DEFLATED,
stored=ZIP_STORED)[zip])
log_function('Compiling into Zip archive "%s"' % target)
else:
if not os.path.isdir(target):
os.makedirs(target)
log_function('Compiling into folder "%s"' % target)
try:
for name in self.list_templates(extensions, filter_func):
source, filename, _ = self.loader.get_source(self, name)
try:
code = self.compile(source, name, filename, True, True)
except TemplateSyntaxError as e:
if not ignore_errors:
raise
log_function('Could not compile "%s": %s' % (name, e))
continue
filename = ModuleLoader.get_module_filename(name)
if py_compile:
c = self._compile(code, encode_filename(filename))
write_file(filename + 'c', py_header +
marshal.dumps(c), 'wb')
log_function('Byte-compiled "%s" as %s' %
(name, filename + 'c'))
else:
write_file(filename, code, 'w')
log_function('Compiled "%s" as %s' % (name, filename))
finally:
if zip:
zip_file.close()
log_function('Finished compiling templates')
def list_templates(self, extensions=None, filter_func=None):
"""Returns a list of templates for this environment. This requires
that the loader supports the loader's
:meth:`~BaseLoader.list_templates` method.
If there are other files in the template folder besides the
actual templates, the returned list can be filtered. There are two
ways: either `extensions` is set to a list of file extensions for
templates, or a `filter_func` can be provided which is a callable that
is passed a template name and should return `True` if it should end up
in the result list.
If the loader does not support that, a :exc:`TypeError` is raised.
.. versionadded:: 2.4
"""
x = self.loader.list_templates()
if extensions is not None:
if filter_func is not None:
raise TypeError('either extensions or filter_func '
'can be passed, but not both')
filter_func = lambda x: '.' in x and \
x.rsplit('.', 1)[1] in extensions
if filter_func is not None:
x = ifilter(filter_func, x)
return x
def handle_exception(self, exc_info=None, rendered=False, source_hint=None):
"""Exception handling helper. This is used internally to either raise
rewritten exceptions or return a rendered traceback for the template.
"""
global _make_traceback
if exc_info is None:
exc_info = sys.exc_info()
# the debugging module is imported when it's used for the first time.
# we're doing a lot of stuff there and for applications that do not
# get any exceptions in template rendering there is no need to load
# all of that.
if _make_traceback is None:
from jinja2.debug import make_traceback as _make_traceback
traceback = _make_traceback(exc_info, source_hint)
if rendered and self.exception_formatter is not None:
return self.exception_formatter(traceback)
if self.exception_handler is not None:
self.exception_handler(traceback)
exc_type, exc_value, tb = traceback.standard_exc_info
reraise(exc_type, exc_value, tb)
def join_path(self, template, parent):
"""Join a template with the parent. By default all the lookups are
relative to the loader root so this method returns the `template`
parameter unchanged, but if the paths should be relative to the
parent template, this function can be used to calculate the real
template name.
Subclasses may override this method and implement template path
joining here.
"""
return template
@internalcode
def _load_template(self, name, globals):
if self.loader is None:
raise TypeError('no loader for this environment specified')
if self.cache is not None:
template = self.cache.get(name)
if template is not None and (not self.auto_reload or \
template.is_up_to_date):
return template
template = self.loader.load(self, name, globals)
if self.cache is not None:
self.cache[name] = template
return template
@internalcode
def get_template(self, name, parent=None, globals=None):
"""Load a template from the loader. If a loader is configured this
method ask the loader for the template and returns a :class:`Template`.
If the `parent` parameter is not `None`, :meth:`join_path` is called
to get the real template name before loading.
The `globals` parameter can be used to provide template wide globals.
These variables are available in the context at render time.
If the template does not exist a :exc:`TemplateNotFound` exception is
raised.
.. versionchanged:: 2.4
If `name` is a :class:`Template` object it is returned from the
function unchanged.
"""
if isinstance(name, Template):
return name
if parent is not None:
name = self.join_path(name, parent)
return self._load_template(name, self.make_globals(globals))
@internalcode
def select_template(self, names, parent=None, globals=None):
"""Works like :meth:`get_template` but tries a number of templates
before it fails. If it cannot find any of the templates, it will
raise a :exc:`TemplatesNotFound` exception.
.. versionadded:: 2.3
.. versionchanged:: 2.4
If `names` contains a :class:`Template` object it is returned
from the function unchanged.
"""
if not names:
raise TemplatesNotFound(message=u'Tried to select from an empty list '
u'of templates.')
globals = self.make_globals(globals)
for name in names:
if isinstance(name, Template):
return name
if parent is not None:
name = self.join_path(name, parent)
try:
return self._load_template(name, globals)
except TemplateNotFound:
pass
raise TemplatesNotFound(names)
@internalcode
def get_or_select_template(self, template_name_or_list,
parent=None, globals=None):
"""Does a typecheck and dispatches to :meth:`select_template`
if an iterable of template names is given, otherwise to
:meth:`get_template`.
.. versionadded:: 2.3
"""
if isinstance(template_name_or_list, string_types):
return self.get_template(template_name_or_list, parent, globals)
elif isinstance(template_name_or_list, Template):
return template_name_or_list
return self.select_template(template_name_or_list, parent, globals)
def from_string(self, source, globals=None, template_class=None):
"""Load a template from a string. This parses the source given and
returns a :class:`Template` object.
"""
globals = self.make_globals(globals)
cls = template_class or self.template_class
return cls.from_code(self, self.compile(source), globals, None)
def make_globals(self, d):
"""Return a dict for the globals."""
if not d:
return self.globals
return dict(self.globals, **d)
class Template(object):
“”"The central template object. This class represents a compiled template
and is used to evaluate it.
Normally the template object is generated from an :class:`Environment` but
it also has a constructor that makes it possible to create a template
instance directly using the constructor. It takes the same arguments as
the environment constructor but it's not possible to specify a loader.
Every template object has a few methods and members that are guaranteed
to exist. However it's important that a template object should be
considered immutable. Modifications on the object are not supported.
Template objects created from the constructor rather than an environment
do have an `environment` attribute that points to a temporary environment
that is probably shared with other templates created with the constructor
and compatible settings.
>>> template = Template('Hello {{ name }}!')
>>> template.render(name='John Doe')
u'Hello John Doe!'
>>> stream = template.stream(name='John Doe')
>>> stream.next()
u'Hello John Doe!'
>>> stream.next()
Traceback (most recent call last):
...
StopIteration
"""
def __new__(cls, source,
block_start_string=BLOCK_START_STRING,
block_end_string=BLOCK_END_STRING,
variable_start_string=VARIABLE_START_STRING,
variable_end_string=VARIABLE_END_STRING,
comment_start_string=COMMENT_START_STRING,
comment_end_string=COMMENT_END_STRING,
line_statement_prefix=LINE_STATEMENT_PREFIX,
line_comment_prefix=LINE_COMMENT_PREFIX,
trim_blocks=TRIM_BLOCKS,
lstrip_blocks=LSTRIP_BLOCKS,
newline_sequence=NEWLINE_SEQUENCE,
keep_trailing_newline=KEEP_TRAILING_NEWLINE,
extensions=(),
optimized=True,
undefined=Undefined,
finalize=None,
autoescape=False):
env = get_spontaneous_environment(
block_start_string, block_end_string, variable_start_string,
variable_end_string, comment_start_string, comment_end_string,
line_statement_prefix, line_comment_prefix, trim_blocks,
lstrip_blocks, newline_sequence, keep_trailing_newline,
frozenset(extensions), optimized, undefined, finalize, autoescape,
None, 0, False, None)
return env.from_string(source, template_class=cls)
@classmethod
def from_code(cls, environment, code, globals, uptodate=None):
"""Creates a template object from compiled code and the globals. This
is used by the loaders and environment to create a template object.
"""
namespace = {
'environment': environment,
'__file__': code.co_filename
}
exec(code, namespace)
rv = cls._from_namespace(environment, namespace, globals)
rv._uptodate = uptodate
return rv
@classmethod
def from_module_dict(cls, environment, module_dict, globals):
"""Creates a template object from a module. This is used by the
module loader to create a template object.
.. versionadded:: 2.4
"""
return cls._from_namespace(environment, module_dict, globals)
@classmethod
def _from_namespace(cls, environment, namespace, globals):
t = object.__new__(cls)
t.environment = environment
t.globals = globals
t.name = namespace['name']
t.filename = namespace['__file__']
t.blocks = namespace['blocks']
# render function and module
t.root_render_func = namespace['root']
t._module = None
# debug and loader helpers
t._debug_info = namespace['debug_info']
t._uptodate = None
# store the reference
namespace['environment'] = environment
namespace['__jinja_template__'] = t
return t
def render(self, *args, **kwargs):
"""This method accepts the same arguments as the `dict` constructor:
A dict, a dict subclass or some keyword arguments. If no arguments
are given the context will be empty. These two calls do the same::
template.render(knights='that say nih')
template.render({'knights': 'that say nih'})
This will return the rendered template as unicode string.
"""
vars = dict(*args, **kwargs)
try:
return concat(self.root_render_func(self.new_context(vars)))
except Exception:
exc_info = sys.exc_info()
return self.environment.handle_exception(exc_info, True)
def stream(self, *args, **kwargs):
"""Works exactly like :meth:`generate` but returns a
:class:`TemplateStream`.
"""
return TemplateStream(self.generate(*args, **kwargs))
def generate(self, *args, **kwargs):
"""For very large templates it can be useful to not render the whole
template at once but evaluate each statement after another and yield
piece for piece. This method basically does exactly that and returns
a generator that yields one item after another as unicode strings.
It accepts the same arguments as :meth:`render`.
"""
vars = dict(*args, **kwargs)
try:
for event in self.root_render_func(self.new_context(vars)):
yield event
except Exception:
exc_info = sys.exc_info()
else:
return
yield self.environment.handle_exception(exc_info, True)
def new_context(self, vars=None, shared=False, locals=None):
"""Create a new :class:`Context` for this template. The vars
provided will be passed to the template. Per default the globals
are added to the context. If shared is set to `True` the data
is passed as it to the context without adding the globals.
`locals` can be a dict of local variables for internal usage.
"""
return new_context(self.environment, self.name, self.blocks,
vars, shared, self.globals, locals)
def make_module(self, vars=None, shared=False, locals=None):
"""This method works like the :attr:`module` attribute when called
without arguments but it will evaluate the template on every call
rather than caching it. It's also possible to provide
a dict which is then used as context. The arguments are the same
as for the :meth:`new_context` method.
"""
return TemplateModule(self, self.new_context(vars, shared, locals))
@property
def module(self):
"""The template as module. This is used for imports in the
template runtime but is also useful if one wants to access
exported template variables from the Python layer:
>>> t = Template('{% macro foo() %}42{% endmacro %}23')
>>> unicode(t.module)
u'23'
>>> t.module.foo()
u'42'
"""
if self._module is not None:
return self._module
self._module = rv = self.make_module()
return rv
handler.py
Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
MIT License. See license.txt
from future import unicode_literals
import frappe
from frappe import _
import frappe.utils
import frappe.sessions
import frappe.utils.file_manager
import frappe.widgets.form.run_method
from frappe.utils.response import build_response
@frappe.whitelist(allow_guest=True)
def startup():
frappe.response.update(frappe.sessions.get())
@frappe.whitelist()
def runserverobj(method, docs=None, dt=None, dn=None, arg=None, args=None):
frappe.widgets.form.run_method.runserverobj(method, docs=docs, dt=dt, dn=dn, arg=arg, args=args)
@frappe.whitelist(allow_guest=True)
def logout():
frappe.local.login_manager.logout()
frappe.db.commit()
@frappe.whitelist(allow_guest=True)
def web_logout():
frappe.local.login_manager.logout()
frappe.db.commit()
frappe.respond_as_web_page(“Logged Out”, “”“
You have been logged out.
”“”)
@frappe.whitelist(allow_guest=True)
def run_custom_method(doctype, name, custom_method):
“”“cmd=run_custom_method&doctype={doctype}&name={name}&custom_method={custom_method}”“”
doc = frappe.get_doc(doctype, name)
if getattr(doc, custom_method, frappe.dict()).is_whitelisted:
frappe.call(getattr(doc, custom_method), **frappe.local.form_dict)
else:
frappe.throw((“Not permitted”), frappe.PermissionError)
@frappe.whitelist()
def uploadfile():
try:
if frappe.form_dict.get(‘from_form’):
try:
ret = frappe.utils.file_manager.upload()
except frappe.DuplicateEntryError:
# ignore pass
ret = None
frappe.db.rollback()
else:
if frappe.form_dict.get(‘method’):
ret = frappe.get_attr(frappe.form_dict.method)()
except Exception:
frappe.errprint(frappe.utils.get_traceback())
ret = None
return ret
def handle():
“”“handle request”“”
cmd = frappe.local.form_dict.cmd
if cmd!='login':
execute_cmd(cmd)
return build_response("json")
def execute_cmd(cmd):
“”“execute a request as python module”“”
for hook in frappe.get_hooks(“override_whitelisted_methods”, {}).get(cmd, []):
# override using the first hook
cmd = hook
break
method = get_attr(cmd)
# check if whitelisted
if frappe.session['user'] == 'Guest':
if (method not in frappe.guest_methods):
frappe.msgprint(_("Not permitted"))
raise frappe.PermissionError('Not Allowed, %s' % str(method))
else:
if not method in frappe.whitelisted:
frappe.msgprint(_("Not permitted"))
raise frappe.PermissionError('Not Allowed, %s' % str(method))
ret = frappe.call(method, **frappe.form_dict)
# returns with a message
if ret:
frappe.response['message'] = ret
def get_attr(cmd):
“”“get method object from cmd”“”
if ‘.’ in cmd:
method = frappe.get_attr(cmd)
else:
method = globals()[cmd]
frappe.log(“method:” + cmd)
return method
Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
MIT License. See license.txt
“”"
globals attached to frappe module
- some utility functions that should probably be moved
“”"
from future import unicode_literals
from werkzeug.local import Local, release_local
import os, importlib, inspect, logging, json
public
from frappe.version import version
from .exceptions import *
from .utils.jinja import get_jenv, get_template, render_template
local = Local()
class _dict(dict):
“”“dict like object that exposes keys as attributes”“”
def getattr(self, key):
ret = self.get(key)
if not ret and key.startswith(“__”):
raise AttributeError()
return ret
def setattr(self, key, value):
self[key] = value
def getstate(self):
return self
def setstate(self, d):
self.update(d)
def update(self, d):
“”“update and return self – the missing dict feature in python”“”
super(_dict, self).update(d)
return self
def copy(self):
return _dict(dict(self).copy())
def _(msg):
“”“translate object in current lang, if exists”“”
if local.lang == “en”:
return msg
from frappe.translate import get_full_dict
return get_full_dict(local.lang).get(msg, msg)
def get_lang_dict(fortype, name=None):
if local.lang==“en”:
return {}
from frappe.translate import get_dict
return get_dict(fortype, name)
def set_user_lang(user, user_language=None):
from frappe.translate import get_user_lang
local.lang = get_user_lang(user)
local-globals
db = local(“db”)
conf = local(“conf”)
form = form_dict = local(“form_dict”)
request = local(“request”)
request_method = local(“request_method”)
response = local(“response”)
session = local(“session”)
user = local(“user”)
flags = local(“flags”)
error_log = local(“error_log”)
debug_log = local(“debug_log”)
message_log = local(“message_log”)
lang = local(“lang”)
def init(site, sites_path=None):
if getattr(local, “initialised”, None):
return
if not sites_path:
sites_path = '.'
local.error_log = []
local.message_log = []
local.debug_log = []
local.flags = _dict({})
local.rollback_observers = []
local.test_objects = {}
local.site = site
local.sites_path = sites_path
local.site_path = os.path.join(sites_path, site)
local.request_method = request.method if request else None
local.request_ip = None
local.response = _dict({"docs":[]})
local.conf = _dict(get_site_config())
local.lang = local.conf.lang or "en"
local.module_app = None
local.app_modules = None
local.user = None
local.role_permissions = {}
local.jenv = None
local.jloader =None
local.cache = {}
setup_module_map()
local.initialised = True
def connect(site=None, db_name=None):
from database import Database
if site:
init(site)
local.db = Database(user=db_name or local.conf.db_name)
local.form_dict = _dict()
local.session = _dict()
set_user(“Administrator”)
def get_site_config(sites_path=None, site_path=None):
config = {}
sites_path = sites_path or getattr(local, "sites_path", None)
site_path = site_path or getattr(local, "site_path", None)
if sites_path:
common_site_config = os.path.join(sites_path, "common_site_config.json")
if os.path.exists(common_site_config):
config.update(get_file_json(common_site_config))
if site_path:
site_config = os.path.join(site_path, "site_config.json")
if os.path.exists(site_config):
config.update(get_file_json(site_config))
return _dict(config)
def destroy():
“”“closes connection and releases werkzeug local”“”
if db:
db.close()
release_local(local)
_memc = None
memcache
def cache():
global _memc
if not _memc:
from frappe.memc import MClient
_memc = MClient([‘localhost:11211’])
return _memc
def get_traceback():
import utils
return utils.get_traceback()
def errprint(msg):
from utils import cstr
if not request or (not “cmd” in local.form_dict):
print cstr(msg)
error_log.append(cstr(msg))
def log(msg):
if not request:
if conf.get(“logging”) or False:
print repr(msg)
from utils import cstr
debug_log.append(cstr(msg))
def msgprint(msg, small=0, raise_exception=0, as_table=False):
def _raise_exception():
if raise_exception:
if flags.rollback_on_exception:
db.rollback()
import inspect
if inspect.isclass(raise_exception) and issubclass(raise_exception, Exception):
raise raise_exception, msg
else:
raise ValidationError, msg
if flags.mute_messages:
_raise_exception()
return
from utils import cstr
if as_table and type(msg) in (list, tuple):
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>'
if flags.print_messages:
print "Message: " + repr(msg)
message_log.append((small and '__small:' or '')+cstr(msg or ''))
_raise_exception()
def throw(msg, exc=ValidationError):
msgprint(msg, raise_exception=exc)
def create_folder(path, with_init=False):
from frappe.utils import touch_file
if not os.path.exists(path):
os.makedirs(path)
if with_init:
touch_file(os.path.join(path, "__init__.py"))
def set_user(username):
from frappe.utils.user import User
local.session.user = username
local.session.sid = username
local.cache = {}
local.form_dict = _dict()
local.jenv = None
local.session.data = {}
local.user = User(username)
local.role_permissions = {}
def get_request_header(key, default=None):
return request.headers.get(key, default)
def sendmail(recipients=(), sender=“”, subject=“No Subject”, message=“No Message”,
as_markdown=False, bulk=False, ref_doctype=None, ref_docname=None,
add_unsubscribe_link=False, attachments=None):
if bulk:
import frappe.utils.email_lib.bulk
frappe.utils.email_lib.bulk.send(recipients=recipients, sender=sender,
subject=subject, message=message, ref_doctype = ref_doctype,
ref_docname = ref_docname, add_unsubscribe_link=add_unsubscribe_link, attachments=attachments)
else:
import frappe.utils.email_lib
if as_markdown:
frappe.utils.email_lib.sendmail_md(recipients, sender=sender,
subject=subject, msg=message, attachments=attachments)
else:
frappe.utils.email_lib.sendmail(recipients, sender=sender,
subject=subject, msg=message, attachments=attachments)
logger = None
whitelisted = []
guest_methods = []
def whitelist(allow_guest=False):
“”"
decorator for whitelisting a function
Note: if the function is allowed to be accessed by a guest user,
it must explicitly be marked as allow_guest=True
for specific roles, set allow_roles = ['Administrator'] etc.
"""
def innerfn(fn):
global whitelisted, guest_methods
whitelisted.append(fn)
if allow_guest:
guest_methods.append(fn)
return fn
return innerfn
def only_for(roles):
if not isinstance(roles, (tuple, list)):
roles = (roles,)
roles = set(roles)
myroles = set(get_roles())
if not roles.intersection(myroles):
raise PermissionError
def clear_cache(user=None, doctype=None):
“”“clear cache”“”
import frappe.sessions
if doctype:
import frappe.model.meta
frappe.model.meta.clear_cache(doctype)
reset_metadata_version()
elif user:
frappe.sessions.clear_cache(user)
else: # everything
import translate
frappe.sessions.clear_cache()
translate.clear_cache()
reset_metadata_version()
for fn in frappe.get_hooks("clear_cache"):
get_attr(fn)()
frappe.local.role_permissions = {}
def get_roles(username=None):
if not local.session:
return [“Guest”]
return get_user(username).get_roles()
def get_user(username):
from frappe.utils.user import User
if not username or username == local.session.user:
return local.user
else:
return User(username)
def has_permission(doctype, ptype=“read”, doc=None, user=None):
import frappe.permissions
return frappe.permissions.has_permission(doctype, ptype, doc, user=user)
def is_table(doctype):
tables = cache().get_value(“is_table”)
if tables==None:
tables = db.sql_list(“select name from tabDocType where ifnull(istable,0)=1”)
cache().set_value(“is_table”, tables)
return doctype in tables
def clear_perms(doctype):
db.sql(“”“delete from tabDocPerm where parent=%s”“”, doctype)
def reset_perms(doctype):
from frappe.core.doctype.notification_count.notification_count import delete_notification_count_for
delete_notification_count_for(doctype)
clear_perms(doctype)
reload_doc(db.get_value("DocType", doctype, "module"),
"DocType", doctype, force=True)
def generate_hash(txt=None):
“”“Generates random hash for session id”“”
import hashlib, time
from .utils import random_string
return hashlib.sha224((txt or “”) + repr(time.time()) + repr(random_string(8))).hexdigest()
def reset_metadata_version():
v = generate_hash()
cache().set_value(“metadata_version”, v)
return v
def new_doc(doctype, parent_doc=None, parentfield=None):
from frappe.model.create_new import get_new_doc
return get_new_doc(doctype, parent_doc, parentfield)
def set_value(doctype, docname, fieldname, value):
import frappe.client
return frappe.client.set_value(doctype, docname, fieldname, value)
def get_doc(arg1, arg2=None):
import frappe.model.document
return frappe.model.document.get_doc(arg1, arg2)
def get_meta(doctype, cached=True):
import frappe.model.meta
return frappe.model.meta.get_meta(doctype, cached=cached)
def delete_doc(doctype=None, name=None, force=0, ignore_doctypes=None, for_reload=False, ignore_permissions=False):
import frappe.model.delete_doc
frappe.model.delete_doc.delete_doc(doctype, name, force, ignore_doctypes, for_reload, ignore_permissions)
def delete_doc_if_exists(doctype, name):
if db.exists(doctype, name):
delete_doc(doctype, name)
def reload_doc(module, dt=None, dn=None, force=False):
import frappe.modules
return frappe.modules.reload_doc(module, dt, dn, force=force)
def rename_doc(doctype, old, new, debug=0, force=False, merge=False, ignore_permissions=False):
from frappe.model.rename_doc import rename_doc
return rename_doc(doctype, old, new, force=force, merge=merge, ignore_permissions=ignore_permissions)
def insert(doclist):
import frappe.model
return frappe.model.insert(doclist)
def get_module(modulename):
return importlib.import_module(modulename)
def scrub(txt):
return txt.replace(’ ‘,’‘).replace(’-', '').lower()
def unscrub(txt):
return txt.replace(‘_’,’ ‘).replace(’-', ’ ').title()
def get_module_path(module, *joins):
module = scrub(module)
return get_pymodule_path(local.module_app[module] + “.” + module, *joins)
def get_app_path(app_name, *joins):
return get_pymodule_path(app_name, *joins)
def get_site_path(*joins):
return os.path.join(local.site_path, *joins)
def get_pymodule_path(modulename, *joins):
joins = [scrub(part) for part in joins]
return os.path.join(os.path.dirname(get_module(scrub(modulename)).file), *joins)
def get_module_list(app_name):
return get_file_items(os.path.join(os.path.dirname(get_module(app_name).file), “modules.txt”))
def get_all_apps(with_frappe=False, with_internal_apps=True, sites_path=None):
if not sites_path:
sites_path = local.sites_path
apps = get_file_items(os.path.join(sites_path, "apps.txt"), raise_not_found=True)
if with_internal_apps:
apps.extend(get_file_items(os.path.join(local.site_path, "apps.txt")))
if with_frappe:
apps.insert(0, 'frappe')
return apps
def get_installed_apps():
if getattr(flags, “in_install_db”, True):
return []
installed = json.loads(db.get_global(“installed_apps”) or “[]”)
return installed
@whitelist()
def get_versions():
versions = {}
for app in get_installed_apps():
versions[app] = {
“title”: get_hooks(“app_title”, app_name=app),
“description”: get_hooks(“app_description”, app_name=app)
}
try:
versions[app][“version”] = get_attr(app + “.version”)
except AttributeError:
versions[app][“version”] = ‘0.0.1’
return versions
def get_hooks(hook=None, default=None, app_name=None):
def load_app_hooks(app_name=None):
hooks = {}
for app in [app_name] if app_name else get_installed_apps():
app = “frappe” if app==“webnotes” else app
app_hooks = get_module(app + “.hooks”)
for key in dir(app_hooks):
if not key.startswith(“_”):
append_hook(hooks, key, getattr(app_hooks, key))
return hooks
def append_hook(target, key, value):
if isinstance(value, dict):
target.setdefault(key, {})
for inkey in value:
append_hook(target[key], inkey, value[inkey])
else:
append_to_list(target, key, value)
def append_to_list(target, key, value):
target.setdefault(key, [])
if not isinstance(value, list):
value = [value]
target[key].extend(value)
if app_name:
hooks = _dict(load_app_hooks(app_name))
else:
hooks = _dict(cache().get_value("app_hooks", load_app_hooks))
if hook:
return hooks.get(hook) or (default if default is not None else [])
else:
return hooks
def setup_module_map():
_cache = cache()
if conf.db_name:
local.app_modules = _cache.get_value("app_modules")
local.module_app = _cache.get_value("module_app")
if not local.app_modules:
local.module_app, local.app_modules = {}, {}
for app in get_all_apps(True):
if app=="webnotes": app="frappe"
local.app_modules.setdefault(app, [])
for module in get_module_list(app):
module = scrub(module)
local.module_app[module] = app
local.app_modules[app].append(module)
if conf.db_name:
_cache.set_value("app_modules", local.app_modules)
_cache.set_value("module_app", local.module_app)
def get_file_items(path, raise_not_found=False, ignore_empty_lines=True):
import frappe.utils
content = read_file(path, raise_not_found=raise_not_found)
if content:
content = frappe.utils.strip(content)
return [p.strip() for p in content.splitlines() if (not ignore_empty_lines) or (p.strip() and not p.startswith("#"))]
else:
return []
def get_file_json(path):
with open(path, ‘r’) as f:
return json.load(f)
def read_file(path, raise_not_found=False):
from frappe.utils import cstr
if os.path.exists(path):
with open(path, “r”) as f:
return cstr(f.read())
elif raise_not_found:
raise IOError(“{} Not Found”.format(path))
else:
return None
def get_attr(method_string):
modulename = ‘.’.join(method_string.split(‘.’)[:-1])
methodname = method_string.split(‘.’)[-1]
return getattr(get_module(modulename), methodname)
def call(fn, *args, **kwargs):
if hasattr(fn, ‘fnargs’):
fnargs = fn.fnargs
else:
fnargs, varargs, varkw, defaults = inspect.getargspec(fn)
newargs = {}
for a in fnargs:
if a in kwargs:
newargs[a] = kwargs.get(a)
return fn(*args, **newargs)
def make_property_setter(args, ignore_validate=False, validate_fields_for_doctype=True):
args = _dict(args)
ps = get_doc({
‘doctype’: “Property Setter”,
‘doctype_or_field’: args.doctype_or_field or “DocField”,
‘doc_type’: args.doctype,
‘field_name’: args.fieldname,
‘property’: args.property,
‘value’: args.value,
‘property_type’: args.property_type or “Data”,
‘__islocal’: 1
})
ps.ignore_validate = ignore_validate
ps.validate_fields_for_doctype = validate_fields_for_doctype
ps.insert()
def import_doc(path, ignore_links=False, ignore_insert=False, insert=False):
from frappe.core.page.data_import_tool import data_import_tool
data_import_tool.import_doc(path, ignore_links=ignore_links, ignore_insert=ignore_insert, insert=insert)
def copy_doc(doc, ignore_no_copy=True):
“”" No_copy fields also get copied.“”"
import copy
def remove_no_copy_fields(d):
for df in d.meta.get("fields", {"no_copy": 1}):
if hasattr(d, df.fieldname):
d.set(df.fieldname, None)
if not isinstance(doc, dict):
d = doc.as_dict()
else:
d = doc
newdoc = get_doc(copy.deepcopy(d))
newdoc.name = None
newdoc.set("__islocal", 1)
newdoc.owner = None
newdoc.creation = None
newdoc.amended_from = None
newdoc.amendment_date = None
if not ignore_no_copy:
remove_no_copy_fields(newdoc)
for d in newdoc.get_all_children():
d.name = None
d.parent = None
d.set("__islocal", 1)
d.owner = None
d.creation = None
if not ignore_no_copy:
remove_no_copy_fields(d)
return newdoc
def compare(val1, condition, val2):
import frappe.utils
return frappe.utils.compare(val1, condition, val2)
def respond_as_web_page(title, html, success=None, http_status_code=None):
local.message_title = title
local.message = html
local.message_success = success
local.response[‘type’] = ‘page’
local.response[‘page_name’] = ‘message’
if http_status_code:
local.response[‘http_status_code’] = http_status_code
def build_match_conditions(doctype, as_condition=True):
import frappe.widgets.reportview
return frappe.widgets.reportview.build_match_conditions(doctype, as_condition)
def get_list(doctype, filters=None, fields=None, or_filters=None, docstatus=None,
group_by=None, order_by=None, limit_start=0, limit_page_length=None,
as_list=False, debug=False, ignore_permissions=False, user=None):
import frappe.model.db_query
return frappe.model.db_query.DatabaseQuery(doctype).execute(filters=filters,
fields=fields, docstatus=docstatus, or_filters=or_filters,
group_by=group_by, order_by=order_by, limit_start=limit_start,
limit_page_length=limit_page_length, as_list=as_list, debug=debug,
ignore_permissions=ignore_permissions, user=user)
def get_all(doctype, **args):
args[“ignore_permissions”] = True
return get_list(doctype, **args)
run_query = get_list
def add_version(doc):
get_doc({
“doctype”: “Version”,
“ref_doctype”: doc.doctype,
“docname”: doc.name,
“doclist_json”: json.dumps(doc.as_dict(), indent=1, sort_keys=True)
}).insert(ignore_permissions=True)
def get_test_records(doctype):
from frappe.modules import get_doctype_module, get_module_path
path = os.path.join(get_module_path(get_doctype_module(doctype)), “doctype”, scrub(doctype), “test_records.json”)
if os.path.exists(path):
with open(path, “r”) as f:
return json.loads(f.read())
else:
return []
def format_value(value, df, doc=None, currency=None):
import frappe.utils.formatters
return frappe.utils.formatters.format_value(value, df, doc, currency=currency)
def get_print_format(doctype, name, print_format=None, style=None, as_pdf=False):
from frappe.website.render import build_page
from frappe.utils.pdf import get_pdf
local.form_dict.doctype = doctype
local.form_dict.name = name
local.form_dict.format = print_format
local.form_dict.style = style
html = build_page("print")
if as_pdf:
return get_pdf(html)
else:
return html
def attach_print(doctype, name, file_name):
from frappe.utils import scrub_urls
print_settings = db.get_singles_dict("Print Settings")
if int(print_settings.send_print_as_pdf or 0):
return {
"fname": file_name + ".pdf",
"fcontent": get_print_format(doctype, name, as_pdf=True)
}
else:
return {
"fname": file_name + ".html",
"fcontent": scrub_urls(get_print_format(doctype, name)).encode("utf-8")
}
logging_setup_complete = False
def get_logger(module=None):
from frappe.setup_logging import setup_logging
global logging_setup_complete
if not logging_setup_complete:
setup_logging()
logging_setup_complete = True
return logging.getLogger(module or "frappe")
This code fetch value from master into custom print format.
{% set c = frappe.get_doc("Customer", doc.customer) %}
{{ c.territory or '' }}
{{ c.customer_group or '' }}
{{ c.credit_days or '' }}
If you share your custom print format I can test It locally.
Print.py
Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
MIT License. See license.txt
from future import unicode_literals
import frappe, os, copy, json, re
from frappe import _
from frappe.modules import get_doc_path
from jinja2 import TemplateNotFound
from frappe.utils import cint, strip_html
from frappe.utils.pdf import get_pdf
no_cache = 1
no_sitemap = 1
base_template_path = “templates/pages/print.html”
standard_format = “templates/print_formats/standard.html”
def get_context(context):
if not frappe.form_dict.format:
frappe.form_dict.format = standard_format
if not frappe.form_dict.doctype or not frappe.form_dict.name:
return {
"body": """<h1>Error</h1>
<p>Parameters doctype, name and format required</p>
<pre>%s</pre>""" % repr(frappe.form_dict)
}
doc = frappe.get_doc(frappe.form_dict.doctype, frappe.form_dict.name)
meta = frappe.get_meta(doc.doctype)
return {
"body": get_html(doc, print_format = frappe.form_dict.format,
meta=meta, trigger_print = frappe.form_dict.trigger_print, no_letterhead=frappe.form_dict.no_letterhead),
"css": get_print_style(frappe.form_dict.style),
"comment": frappe.session.user,
"title": doc.get(meta.title_field) if meta.title_field else doc.name
}
@frappe.whitelist()
def get_html(doc, name=None, print_format=None, meta=None,
no_letterhead=None, trigger_print=False):
if isinstance(no_letterhead, basestring):
no_letterhead = cint(no_letterhead)
elif no_letterhead is None:
no_letterhead = not cint(frappe.db.get_single_value("Print Settings", "with_letterhead"))
if isinstance(doc, basestring) and isinstance(name, basestring):
doc = frappe.get_doc(doc, name)
if isinstance(doc, basestring):
doc = frappe.get_doc(json.loads(doc))
doc.in_print = True
validate_print_permission(doc)
if hasattr(doc, "before_print"):
doc.before_print()
if not hasattr(doc, "print_heading"): doc.print_heading = None
if not hasattr(doc, "sub_heading"): doc.sub_heading = None
if not meta:
meta = frappe.get_meta(doc.doctype)
jenv = frappe.get_jenv()
if print_format in ("Standard", standard_format):
template = jenv.get_template("templates/print_formats/standard.html")
else:
template = jenv.from_string(get_print_format(doc.doctype,
print_format))
args = {
"doc": doc,
"meta": frappe.get_meta(doc.doctype),
"layout": make_layout(doc, meta),
"no_letterhead": no_letterhead,
"trigger_print": cint(trigger_print),
"letter_head": get_letter_head(doc, no_letterhead)
}
html = template.render(args, filters={"len": len})
return html
@frappe.whitelist()
def download_pdf(doctype, name, format=None):
html = frappe.get_print_format(doctype, name, format)
frappe.local.response.filename = “{name}.pdf”.format(name=name.replace(" “, “-”).replace(”/", “-”))
frappe.local.response.filecontent = get_pdf(html)
frappe.local.response.type = “download”
def validate_print_permission(doc):
for ptype in (“read”, “print”):
if not frappe.has_permission(doc.doctype, ptype, doc):
raise frappe.PermissionError(_(“No {0} permission”).format(ptype))
def get_letter_head(doc, no_letterhead):
if no_letterhead:
return “”
if doc.get(“letter_head”):
return frappe.db.get_value(“Letter Head”, doc.letter_head, “content”)
else:
return frappe.db.get_value(“Letter Head”, {“is_default”: 1}, “content”) or “”
def get_print_format(doctype, format_name):
if format_name==standard_format:
return format_name
opts = frappe.db.get_value("Print Format", format_name, "disabled", as_dict=True)
if not opts:
frappe.throw(_("Print Format {0} does not exist").format(format_name), frappe.DoesNotExistError)
elif opts.disabled:
frappe.throw(_("Print Format {0} is disabled").format(format_name), frappe.DoesNotExistError)
# server, find template
path = os.path.join(get_doc_path(frappe.db.get_value("DocType", doctype, "module"),
"Print Format", format_name), frappe.scrub(format_name) + ".html")
if os.path.exists(path):
with open(path, "r") as pffile:
return pffile.read()
else:
html = frappe.db.get_value("Print Format", format_name, "html")
if html:
return html
else:
frappe.throw(_("No template found at path: {0}").format(path),
frappe.TemplateNotFoundError)
def make_layout(doc, meta):
layout, page = [], []
layout.append(page)
for df in meta.fields:
if df.fieldtype==“Section Break” or page==[]:
page.append([])
if df.fieldtype=="Column Break" or (page[-1]==[] and df.fieldtype!="Section Break"):
page[-1].append([])
if df.fieldtype=="HTML" and df.options:
doc.set(df.fieldname, True) # show this field
if is_visible(df) and has_value(df, doc):
page[-1][-1].append(df)
# if table, add the row info in the field
# if a page break is found, create a new docfield
if df.fieldtype=="Table":
df.rows = []
df.start = 0
df.end = None
for i, row in enumerate(doc.get(df.fieldname)):
if row.get("page_break"):
# close the earlier row
df.end = i
# new page, with empty section and column
page = [[[]]]
layout.append(page)
# continue the table in a new page
df = copy.copy(df)
df.start = i
df.end = None
page[-1][-1].append(df)
# filter empty sections
layout = [filter(lambda s: any(filter(lambda c: any(c), s)), page) for page in layout]
return layout
def is_visible(df):
no_display = (“Section Break”, “Column Break”, “Button”)
return (df.fieldtype not in no_display) and not df.get(“__print_hide”) and not df.print_hide
def has_value(df, doc):
value = doc.get(df.fieldname)
if value in (None, “”):
return False
elif isinstance(value, basestring) and not strip_html(value).strip():
return False
return True
def get_print_style(style=None):
print_settings = frappe.get_doc(“Print Settings”)
if not style:
style = print_settings.print_style or "Standard"
context = {"print_settings": print_settings, "print_style": style}
css = frappe.get_template("templates/styles/standard.css").render(context)
try:
additional_css = frappe.get_template("templates/styles/" + style.lower() + ".css").render(context)
# move @import to top
for at_import in list(set(re.findall("(@import url\([^\)]+\)[;]?)", additional_css))):
additional_css = additional_css.replace(at_import, "")
# prepend css with at_import
css = at_import + css
css += "\n" + additional_css
except TemplateNotFound:
pass
return css
def get_visible_columns(data, table_meta):
columns = []
for tdf in table_meta.fields:
if is_visible(tdf) and column_has_value(data, tdf.fieldname):
columns.append(tdf)
return columns
def column_has_value(data, fieldname):
“”“Check if at least one cell in column has non-zero and non-blank value”“”
has_value = False
for row in data:
value = row.get(fieldname)
if value:
if isinstance(value, basestring):
if strip_html(value).strip():
has_value = True
break
else:
has_value = True
break
return has_value
I don’t know why you are sharing file code.
I asked about custom print format code. which is in jinjha template.
Sorry for my mistake.
If you have added custom field in Sales Invoice and you want custom field default print format.
just un-check the print hide option.
- go to Setup >> Customize >> Customize Form
select “Enter Form Type” Sales Invoice.
go to your custom field
uncheck print hide, see photo.
If you want to create new print format.
go to Setup >> Printing and branding >> Print Format.
You can create new print format for sales invoice.
Check POS Invoice example.
Please view my question again.
i have created custome sales invoice print format from printing and branding option but i want customer details from my customer record into my custom print formate.
In my customer form have also customise field i.e ECC_NO,CST_NO,GST_NO…etc
how can call this customise field in my printing custom formate.???
Try this in custom print format.
{% set c = frappe.get_doc("Customer", doc.customer) %}
{{ c.ecc_no or '' }}
ecc_no is your custom field in customer doctype.
To print customer detail write this code.
{% set c = frappe.get_doc("Customer", doc.customer) %}
{{ c.territory or '' }}
{{ c.customer_group or '' }}
{{ c.credit_days or '' }}
Again… i have apply this in custom print formate but found following server error.
Traceback (innermost last):
File "/home/erpadmin/frappe-bench/apps/frappe/frappe/app.py", line 49, in application
response = frappe.handler.handle()
File "/home/erpadmin/frappe-bench/apps/frappe/frappe/handler.py", line 66, in handle
execute_cmd(cmd)
File "/home/erpadmin/frappe-bench/apps/frappe/frappe/handler.py", line 89, in execute_cmd
ret = frappe.call(method, **frappe.form_dict)
File "/home/erpadmin/frappe-bench/apps/frappe/frappe/__init__.py", line 532, in call
return fn(*args, **newargs)
File "/home/erpadmin/frappe-bench/apps/frappe/frappe/templates/pages/print.py", line 86, in get_html
html = template.render(args, filters={"len": len})
File "/home/erpadmin/frappe-bench/env/local/lib/python2.7/site-packages/jinja2/environment.py", line 969, in render
return self.environment.handle_exception(exc_info, True)
File "/home/erpadmin/frappe-bench/env/local/lib/python2.7/site-packages/jinja2/environment.py", line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "
Can’t help till you share custom print format.
Looks like you have error in jinja template.
I have added some custom print-format here.
sorry i am late to send code. Here is my custom format code
Customise field on customer : ECC_NO (DATA type)
Customise field on sales Invoice: SO_NO
******************** script ********************************************
<div align="center"><font face="Arial, sans-serif"><font style="font-size: 9pt" size="2"><img src="/files/acroslogo.jpg" height="41" width="32"></font></font>
<div align="center"><font face="Arial, sans-serif"><font style="font-size: 16pt" size="2">Excise Cum Tax/Retail Invoice </font></font>
<table cellpadding="0" cellspacing="0">
<tr>
<td width="350" text-align: right; <font face="Arial, sans-serif"><font style="font-size: 6pt" size="2"></font></font></td>
<td width="850" text-align: center;<font face="Arial, sans-serif"><font style="font-size: 6pt" size="2">for removal of Excisable goods from factory of Warehouse on payment of duty</font></font></td>
<td width="300" text-align: right;<font face="Arial, sans-serif"><font style="font-size: 8pt" size="2"><b>Original/Duplicate/Triplicate</b> </font></font></td>
</tr></table>
<div align="center"><font face="Arial, sans-serif"><font style="font-size: 12pt" size="2">ACROS PRIVATE LIMITED</font></font>
<div align="center"><font face="Arial, sans-serif"><font style="font-size: 8pt" size="2">Regd. Office & Factory : A-2 Vijay Industrial Estate, Padra Road, Samiyala - 391 410, Baroda,Gujarat.</font></font>
<table <table class="table table-bordered" cellpadding="0" cellspacing="0">
<tr>
<td width="350" <font face="Arial, sans-serif"><font style="font-size: 7pt" size="2">CIN : U36999GJ1994PTC021080<br/>C.Ex.Reg.No:AABCA7802NXM002<br/>ECC.No.:AABCA7802NXM002<br/>TIN G.S.T. NO.:24191700101 Dtd.12.09.2005 <br/>TIN C.S.T.NO.:24191700101 Dtd.12.09.2005
</font></font></td>
<td width="450" <font face="Arial, sans-serif"><font style="font-size: 7pt" size="2">Range :IV Central Excise Building,Race Cource<br/>Division : II Race Course Circle,Baroda<br/>Collectorate : Vadodara Chapter : 39<br/>Tariff Sub Heading No. 3926. 90-99</font></font></td>
<td width="250" <font face="Arial, sans-serif"><font style="font-size: 7pt" size="2">Invoice No.:{{ doc.name }} <br/> Invoice Date :{{ doc.get_formatted("posting_date") }} <br/>Challan No.:{{ doc.name }} <br/> Challan Date :{{ doc.get_formatted("posting_date") }}<br/> Sales Order:{{doc.so_no}}</font></font></p></td></tr>
<td colspan=2 width="800" <font face="Arial, sans-serif"><font style="font-size: 7pt" size="2"><b>{{ _("Customer Name") }}:</b><font face="Arial, sans-serif"><font style="font-size: 8pt" size="2">{{ doc.customer_name }} <br><font face="Arial, sans-serif"><font style="font-size: 7pt" size="2">{{ doc.address_display }}<br/> Buyer Ecc No.: {%set c = frappe.get_doc("customer",doc.customer)%}
{{ c.ecc_no or ''}} </font></font> </td>
<td width="250" <font face="Arial, sans-serif"><font style="font-size: 7pt" size="2">P.O No.:<br/>P.O.Date:<br/>Date of Prepration:{{doc.posting_date}} <br/>Time of Prepration:{{doc.posting_time}} <br/>Date of Removal:{{doc.posting_date}} <br/>Time of Removal{{doc.posting_time}} </font></font></p></td></tr>
</tr></table>
</div>
<table class="table table-bordered">
<tbody>
<tr>
<th>Sr</th>
<th>Description</th>
<th class="text-right">Quantity</th>
<th class="text-right">Rate</th>
<th class="text-right">Amount</th>
</tr>
{%- for row in doc.entries -%}
<tr>
<td style="width: 3%;">{{ row.idx }}</td>
<td style="width: 52%;"><b>{{ row.item_code or '' }} </b>:
{{ row.description or '' }} </td>
<td style="width: 10%; text-align: right;">{{ row.qty }}</td>
<td style="width: 15%; text-align: right;">
{{ row.get_formatted("rate", doc) or ''}}
<td style="width: 20%; text-align: right;">{{
row.get_formatted("amount", doc) or ''}}</td>
</tr>
{%- endfor -%}
</tbody>
</table>
<table class="table table-condensed no-border">
<tbody>
<tr>
<td class="text-right" style="width: 70%">
{{ _("Net Total") }}
</td>
<td class="text-right">
{{ doc.get_formatted("net_total_export") }}
</td>
</tr>
{%- for row in doc.other_charges -%}
{%- if not row.included_in_print_rate -%}
<tr>
<td class="text-right" style="width: 70%">
{{ row.description }}
</td>
<td class="text-right">
{{ row.get_formatted("tax_amount", doc) }}
</td>
</tr>
{%- endif -%}
{%- endfor -%}
{%- if doc.discount_amount -%}
<tr>
<td class="text-right" style="width: 70%">
{{ _("Discount") }}
</td>
<td class="text-right">
{{ doc.get_formatted("discount_amount") }}
</td>
</tr>
{%- endif -%}
<tr>
<td class="text-right" style="width: 70%">
<b>{{ _("Grand Total") }}</b>
</td>
<td class="text-right">
{{ doc.get_formatted("grand_total_export") }}
</td>
</tr>
</tbody>
</table>
<font face="Arial, sans-serif"><font style="font-size: 9pt" size="2">Invoice Value(in word):{{doc.in_words}}</font>
{% if doc.get("other_charges", filters={"included_in_print_rate": 1}) %}
<hr>
<p><b>Taxes Included:</b></p>
<table class="table table-condensed no-border">
<tbody>
{%- for row in doc.other_charges -%}
{%- if row.included_in_print_rate -%}
<tr>
<td class="text-right" style="width: 70%">
{{ row.description }}
</td>
<td class="text-right">
{{ row.get_formatted("tax_amount_after_discount_amount", doc) }}
</td>
<tr>
{%- endif -%}
{%- endfor -%}
</tbody>
</table>
{%- endif -%}
<hr>
<p>{{ doc.terms or "" }}</p>
{% set c = frappe.get_doc(“Customer”, doc.customer) %}
please correct this
Thank you very much, it is working… Gr8