def do_exec(args, kwargs): try: source_code = kwargs.get('source', '') source_cleaned = clean_code(source_code) locals_ = dict() response = dict() if RESTRICTION_OFF: with Capturing() as stdout: exec(source_cleaned, get_globals(), locals_) if len(stdout) > 0: response['stdout'] = '\n'.join(stdout) else: code = RestrictedPython.compile_restricted(source_cleaned, '<inline>', 'exec') # noqa exec(code, get_restricted_globals(), locals_) if '_print' in locals_: response['stdout'] = ''.join(locals_['_print'].txt) if 'return' in kwargs: if isinstance(kwargs['return'], list): data = dict() for variable in kwargs['return']: data[variable] = locals_.get(variable, None) else: data = locals_.get(kwargs['return'], None) response['data'] = nest.hl_api.serializable(data) return response except Exception as e: for line in traceback.format_exception(*sys.exc_info()): print(line, flush=True) abort(Response(str(e), EXCEPTION_ERROR_STATUS))
def _evalExp(self, exp, context): # protect context _context = copy.deepcopy(context) _context['_getattr_'] = self._hook_getattr _context['_getitem_'] = self._hook_getattr # _context = context # compile expressions try: code = RestrictedPython.compile_restricted(exp, '<string>', 'eval') except: raise RuntimeError('ERROR import expression') return eval(code, _context)
def udfize_def(code: str, glbCtx: dict = None, lclCtx: dict = None): if glbCtx is None: glbCtx = LuciUdfRegistry.get_safe_globals() if lclCtx is None: lclCtx = {} udf = LuciUdfRegistry.udfize_def_string(code) udf_ast = ast.parse(udf, filename="<udf>") result = rp.compile_restricted(udf_ast, filename="<string>", mode="exec") exec(result, glbCtx, lclCtx) return lclCtx["udf"]
def route_exec(): """ Route to execute script in Python. """ try: args, kwargs = get_arguments(request) source_code = kwargs.get('source', '') source_cleaned = clean_code(source_code) locals = dict() response = dict() if RESTRICTION_OFF: with Capturing() as stdout: exec(source_cleaned, get_globals(), locals) if len(stdout) > 0: response['stdout'] = '\n'.join(stdout) else: code = RestrictedPython.compile_restricted(source_cleaned, '<inline>', 'exec') exec(code, get_restricted_globals(), locals) if '_print' in locals: response['stdout'] = ''.join(locals['_print'].txt) if 'return' in kwargs: if isinstance(kwargs['return'], list): data = dict() for variable in kwargs['return']: data[variable] = locals.get(variable, None) else: data = locals.get(kwargs['return'], None) response['data'] = nest.hl_api.serializable(data) return jsonify(response) except nest.kernel.NESTError as e: print('NEST error: {}'.format(e)) abort(Response(getattr(e, 'errormessage'), NEST_ERROR_STATUS)) except Exception as e: print('Error: {}'.format(e)) abort(Response(str(e), EXCEPTION_ERROR_STATUS))
def compile(self, source, name, elevated=False): return RestrictedPython.compile_restricted(source, name, 'exec', elevated=elevated)