Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
for field, source in fields.items():
if not isinstance(field, six.string_types):
app_log.error('flattener:%s: key %s is not a str', filename, field)
continue
if isinstance(source, six.string_types):
target = 'obj'
if source:
for item in source.split('.'):
target += ('[%s]' if item.isdigit() else '[%r]') % item
assign(field, target, catch_errors=True)
elif source is True:
assign(field, 'obj')
elif isinstance(source, int) and not isinstance(source, bool):
assign(field, 'obj[%d]' % source, catch_errors=True)
else:
app_log.error('flattener:%s: value %s is not a str/int', filename, source)
continue
body.append('\treturn r')
code = compile(''.join(body), filename='flattener:%s' % filename, mode='exec')
context = {'AttrDict': AttrDict, 'default': default}
eval(code, context) # nosec - code constructed entirely in this function
return context[filename]
- ``cookies.key`` => ``request.cookies[key].value``
- ``args.key`` => ``handler.args[key]`` joined with a comma.
- ``user.key`` => ``handler.current_user[key]`` as str
Invalid key strings are ignored with a warning. If all key strings are
invalid, the default cache.key of ``request.uri`` is used.
'''
default_key = 'request.uri'
keys = conf.get('key', default_key)
if not isinstance(keys, list):
keys = [keys]
key_getters = []
for key in keys:
parts = key.split('.', 2)
if len(parts) < 2:
app_log.warning('url: %s: ignoring invalid cache key %s', name, key)
continue
# convert second part into a Python string representation
val = repr(parts[1])
if parts[0] == 'request':
key_getters.append('u(getattr(request, %s, missing))' % val)
elif parts[0].startswith('header'):
key_getters.append('request.headers.get(%s, missing)' % val)
elif parts[0].startswith('cookie'):
key_getters.append(
'request.cookies[%s].value if %s in request.cookies else missing' % (val, val))
elif parts[0].startswith('user'):
key_getters.append('u(handler.current_user.get(%s, missing)) '
'if handler.current_user else missing' % val)
elif parts[0].startswith('arg'):
key_getters.append('argsep.join(handler.args.get(%s, [missing]))' % val)
else:
def set_format(self, fmt, meta):
# Identify format to render in. The default format, json, is defined in
# the base gramex.yaml under handlers.FormHandler.formats
if fmt in self.formats:
fmt = dict(self.formats[fmt])
else:
app_log.error('%s: _format=%s unknown. Using _format=json' % (self.name, fmt))
fmt = dict(self.formats['json'])
# Set up default headers, and over-ride with headers for the format
for key, val in self.headers.items():
self.set_header(key, val)
for key, val in fmt.pop('headers', {}).items():
self.set_header(key, val)
if fmt['format'] in {'template', 'pptx', 'vega', 'vega-lite', 'vegam'}:
fmt['handler'] = self
if fmt['format'] in {'template'}:
fmt['meta'] = meta['data'] if self.single else meta
return fmt
folders.add(os.path.dirname(path))
handler = FileEventHandler(patterns, **events)
for folder in folders:
_folder, watch = get_watch(folder, watches)
# If a watch for this folder (or a parent) exists, use that folder's watch instead
if watch is not None:
observer.add_handler_for_watch(handler, watch)
folder = _folder
# If it's a new folder, create a new watch for it
elif os.path.exists(folder):
try:
watch = watches[folder] = observer.schedule(handler, folder, recursive=True)
except PermissionError:
app_log.warning('No permission to watch changes on %s', folder)
continue
else:
app_log.warning('watch directory %s does not exist', folder)
continue
# If EXISTING sub-folders of folder have watches, consolidate into this watch
consolidate_watches(folder, watch)
# Keep track of all handler-watch associations
handlers[handler, watch] = (folder, name)
release_unscheduled_watches()
def _conda_r_home():
'''
Returns the R home directory for Conda R if it is installed. Else None.
Typically, people install Conda AND R (in any order), and use the system R
(rather than the conda R) by placing it before Conda in the PATH.
But the system R does not work with Conda rpy2. So we check if Conda R
exists and return its path, so that it can be used as R_HOME.
'''
try:
from conda.base.context import context
except ImportError:
app_log.error('Anaconda not installed. Cannot use Anaconda R')
return None
r_home = os.path.normpath(os.path.join(context.root_prefix, 'lib', 'R'))
if os.path.isdir(os.path.join(r_home, 'bin')):
return r_home
app_log.error('Anaconda R not installed')
return None
# Delay delete a bit if directory is used by another process.
# Typically happens on uninstall immediately after bower / npm / git
# (e.g. during testing.)
elif exc_info[1].winerror == winerror.ERROR_SHARING_VIOLATION:
import time
delays = [0.001, 0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1.0]
for delay in delays:
time.sleep(delay)
try:
return os.remove(path)
except WindowsError:
pass
# npm creates windows shortcuts that shutil.rmtree cannot delete.
# os.listdir failes with a PATH_NOT_FOUND. Delete these and try again
elif function == os.listdir and exc_info[1].winerror == winerror.ERROR_PATH_NOT_FOUND:
app_log.error('Cannot delete %s', path)
from win32com.shell import shell, shellcon
options = shellcon.FOF_NOCONFIRMATION | shellcon.FOF_NOERRORUI
code, err = shell.SHFileOperation((0, shellcon.FO_DELETE, path, None, options))
if code == 0:
raise TryAgainError()
raise exc_info[1]
# methods=['get'] will show all file into as JSON on GET
if not isinstance(methods, list):
methods = [methods]
methods = {method.lower() for method in methods}
if 'get' in methods:
cls.get = cls.fileinfo
cls.transform = []
if transform is not None:
if isinstance(transform, dict) and 'function' in transform:
cls.transform.append(build_transform(
transform, vars=AttrDict((('content', None), ('handler', None))),
filename='url:%s' % cls.name))
else:
app_log.error('UploadHandler %s: no function: in transform: %r',
cls.name, transform)
if method in {
'install', 'uninstall', 'setup', 'run', 'service', 'init',
'mail', 'license',
}:
import gramex.install
return getattr(gramex.install, method), kwargs
raise NotImplementedError('Unknown gramex command: %s' % base_command)
# Use current dir as base (where gramex is run from) if there's a gramex.yaml.
# Else use source/guide, and point the user to the welcome screen
if not os.path.isfile('gramex.yaml'):
from gramex.install import run
args.setdefault('browser', '/welcome')
return run, {'cmd': ['guide'], 'args': args}
app_log.info('Gramex %s | %s | Python %s', __version__, os.getcwd(),
sys.version.replace('\n', ' '))
return init, {'cmd': AttrDict(app=args)}