def _compile(self):
        bind_names = self.getBindingAssignments().getAssignedNamesInOrder()
        compile_result = compile_restricted_function(self._params,
                                                     body=self._body or 'pass',
                                                     name=self.id,
                                                     filename=self.meta_type,
                                                     globalize=bind_names)

        code = compile_result.code
        errors = compile_result.errors
        self.warnings = tuple(compile_result.warnings)
        if errors:
            self._code = None
            self._v_ft = None
            self._setFuncSignature((), (), 0)
            # Fix up syntax errors.
            filestring = '  File "<string>",'
            for i in range(len(errors)):
                line = errors[i]
                if line.startswith(filestring):
                    errors[i] = line.replace(filestring, '  Script', 1)
            self.errors = errors
            return

        self._code = marshal.dumps(code)
        self.errors = ()
        f = self._newfun(code)
        fc = f.__code__
        self._setFuncSignature(f.__defaults__, fc.co_varnames, fc.co_argcount)
        self.Python_magic = Python_magic
        self.Script_magic = Script_magic
        self._v_change = 0
def test_compile_restricted_function_pretends_the_code_is_executed_in_a_global_scope(
):  # NOQA: E501
    p = ''
    body = """output = output + 'bar'"""
    name = "hello_world"
    global_symbols = ['output']

    result = compile_restricted_function(
        p,  # parameters
        body,
        name,
        filename='<string>',
        globalize=global_symbols)

    assert result.code is not None
    assert result.errors == ()

    safe_globals = {
        '__name__': 'script',
        'output': 'foo',
        '__builtins__': {},
    }
    safe_locals = {}
    exec(result.code, safe_globals, safe_locals)
    hello_world = safe_locals['hello_world']
    assert type(hello_world) == FunctionType
    hello_world()
    assert safe_globals['output'] == 'foobar'
def test_compile_restricted_function_allows_invalid_python_identifiers_as_function_name(
):  # NOQA: E501
    p = ''
    body = """output = output + 'bar'"""
    name = "<foo>.bar.__baz__"
    global_symbols = ['output']

    result = compile_restricted_function(
        p,  # parameters
        body,
        name,
        filename='<string>',
        globalize=global_symbols)

    assert result.code is not None
    assert result.errors == ()

    safe_globals = {
        '__name__': 'script',
        'output': 'foo',
        '__builtins__': {},
    }
    safe_locals = {}
    exec(result.code, safe_globals, safe_locals)
    generated_function = tuple(safe_locals.values())[0]
    assert type(generated_function) == FunctionType
    generated_function()
    assert safe_globals['output'] == 'foobar'
def test_compile_restricted_function_allows_invalid_python_identifiers_as_function_name():  # NOQA: E501
    p = ''
    body = """output = output + 'bar'"""
    name = "<foo>.bar.__baz__"
    global_symbols = ['output']

    result = compile_restricted_function(
        p,  # parameters
        body,
        name,
        filename='<string>',
        globalize=global_symbols
    )

    assert result.code is not None
    assert result.errors == ()

    safe_globals = {
        '__name__': 'script',
        'output': 'foo',
        '__builtins__': {},
    }
    safe_locals = {}
    exec(result.code, safe_globals, safe_locals)
    generated_function = tuple(safe_locals.values())[0]
    assert type(generated_function) == FunctionType
    generated_function()
    assert safe_globals['output'] == 'foobar'
def test_compile_restricted_function_pretends_the_code_is_executed_in_a_global_scope():  # NOQA: E501
    p = ''
    body = """output = output + 'bar'"""
    name = "hello_world"
    global_symbols = ['output']

    result = compile_restricted_function(
        p,  # parameters
        body,
        name,
        filename='<string>',
        globalize=global_symbols
    )

    assert result.code is not None
    assert result.errors == ()

    safe_globals = {
        '__name__': 'script',
        'output': 'foo',
        '__builtins__': {},
    }
    safe_locals = {}
    exec(result.code, safe_globals, safe_locals)
    hello_world = safe_locals['hello_world']
    assert type(hello_world) == FunctionType
    hello_world()
    assert safe_globals['output'] == 'foobar'
    def _compile(self):
        bind_names = self.getBindingAssignments().getAssignedNamesInOrder()
        compile_result = compile_restricted_function(
            self._params,
            body=self._body or 'pass',
            name=self.id,
            filename=self.meta_type,
            globalize=bind_names)

        code = compile_result.code
        errors = compile_result.errors
        self.warnings = tuple(compile_result.warnings)
        if errors:
            self._code = None
            self._v_ft = None
            self._setFuncSignature((), (), 0)
            # Fix up syntax errors.
            filestring = '  File "<string>",'
            for i in range(len(errors)):
                line = errors[i]
                if line.startswith(filestring):
                    errors[i] = line.replace(filestring, '  Script', 1)
            self.errors = errors
            return

        self._code = marshal.dumps(code)
        self.errors = ()
        f = self._newfun(code)
        fc = f.__code__
        self._setFuncSignature(f.__defaults__, fc.co_varnames,
                               fc.co_argcount)
        self.Python_magic = Python_magic
        self.Script_magic = Script_magic
        self._v_change = 0
def test_compile_restricted_function_func_wrapped():
    p = ''
    body = """
print("Hello World!")
return printed
"""
    name = "hello_world"
    global_symbols = []

    result = compile_restricted_function(
        p,  # parameters
        body,
        name,
        filename='<string>',
        globalize=global_symbols
    )

    assert result.code is not None
    assert result.errors == ()
    safe_globals = {
        '__name__': 'script',
        '_getattr_': getattr,
        '_print_': PrintCollector,
        '__builtins__': safe_builtins,
    }

    func = FunctionType(result.code, safe_globals)
    func()
    assert 'hello_world' in safe_globals
    hello_world = safe_globals['hello_world']
    assert hello_world() == 'Hello World!\n'
def test_compile_restricted_function_with_arguments():
    p = 'input1, input2'
    body = """
print(input1 + input2)
return printed
"""
    name = "hello_world"
    global_symbols = []

    result = compile_restricted_function(
        p,  # parameters
        body,
        name,
        filename='<string>',
        globalize=global_symbols
    )

    assert result.code is not None
    assert result.errors == ()

    safe_globals = {
        '__name__': 'script',
        '_getattr_': getattr,
        '_print_': PrintCollector,
        '__builtins__': safe_builtins,
    }
    safe_locals = {}
    exec(result.code, safe_globals, safe_locals)
    hello_world = safe_locals['hello_world']
    assert type(hello_world) == FunctionType
    assert hello_world('Hello ', 'World!') == 'Hello World!\n'
def test_compile_restricted_function_with_arguments():
    p = 'input1, input2'
    body = """
print(input1 + input2)
return printed
"""
    name = "hello_world"
    global_symbols = []

    result = compile_restricted_function(
        p,  # parameters
        body,
        name,
        filename='<string>',
        globalize=global_symbols)

    assert result.code is not None
    assert result.errors == ()

    safe_globals = {
        '__name__': 'script',
        '_getattr_': getattr,
        '_print_': PrintCollector,
        '__builtins__': safe_builtins,
    }
    safe_locals = {}
    exec(result.code, safe_globals, safe_locals)
    hello_world = safe_locals['hello_world']
    assert type(hello_world) == FunctionType
    assert hello_world('Hello ', 'World!') == 'Hello World!\n'
def test_compile_restricted_function_func_wrapped():
    p = ''
    body = """
print("Hello World!")
return printed
"""
    name = "hello_world"
    global_symbols = []

    result = compile_restricted_function(
        p,  # parameters
        body,
        name,
        filename='<string>',
        globalize=global_symbols)

    assert result.code is not None
    assert result.errors == ()
    safe_globals = {
        '__name__': 'script',
        '_getattr_': getattr,
        '_print_': PrintCollector,
        '__builtins__': safe_builtins,
    }

    func = FunctionType(result.code, safe_globals)
    func()
    assert 'hello_world' in safe_globals
    hello_world = safe_globals['hello_world']
    assert hello_world() == 'Hello World!\n'
    def __init__(self, uid):
        #Kompilieren der Hauptfunktion
        print("init")
        scriptpath = '.\\user001\\scripts\\render_cockpit.py'
        myscript = Path(scriptpath).read_text()
        render_cockpit_name = 'render_cockpit'
        render_cockpit = compile_restricted_function(p='',
                                                     body=myscript,
                                                     name=render_cockpit_name,
                                                     filename='<inline code>')
        safe_globals = safe_builtins
        safe_locals = {}
        hydropt = CHydropt(uid)
        additional_globals = {'hydropt': hydropt, 'html': html}
        safe_globals.update(additional_globals)
        exec(render_cockpit.code, safe_globals, safe_locals)
        render_cockpit_pointer = safe_locals[render_cockpit_name]

        self.__uid = uid
        self.render_cockpit_pointer = render_cockpit_pointer
        self.hydropt = CHydropt(uid)
        self.safe_globals = safe_globals
        self.safe_locals = safe_locals

        CInits.__numOfInstances += 1
示例#12
0
def load_script(scriptpath, additional_globals, safe_locals, name):
    myscript = Path(scriptpath).read_text()
    cr = compile_restricted_function(p='',
                                     body=myscript,
                                     name=name,
                                     filename='<inline code>')
    safe_globals = safe_builtins
    safe_globals.update(additional_globals)
    exec(cr.code, safe_globals, safe_locals)
    return safe_locals[name]
def test_compile_restricted_function_handle_SyntaxError():
    p = ''
    body = """a("""
    name = "broken"

    result = compile_restricted_function(
        p,  # parameters
        body,
        name,
    )

    assert result.code is None
    assert result.errors == (
        "Line 1: SyntaxError: unexpected EOF while parsing at statement: 'a('",
    )
def test_compile_restricted_function_handle_SyntaxError():
    p = ''
    body = """a("""
    name = "broken"

    result = compile_restricted_function(
        p,  # parameters
        body,
        name,
    )

    assert result.code is None
    assert result.errors == (
        "Line 1: SyntaxError: unexpected EOF while parsing at statement: 'a('",
    )
def test_compile_restricted_function_invalid_syntax():
    p = ''
    body = '1=1'
    name = 'broken'

    result = compile_restricted_function(
        p,  # parameters
        body,
        name,
    )

    assert result.code is None
    assert len(result.errors) == 1
    error_msg = result.errors[0]

    if IS_PY38_OR_GREATER:
        assert error_msg.startswith(
            "Line 1: SyntaxError: cannot assign to literal at statement:")
    else:
        assert error_msg.startswith(
            "Line 1: SyntaxError: can't assign to literal at statement:")
def prepare_restricted_function(p, body, name, filename, globalize=None):
    # We just do what they do in PythonScript...
    r = compile_restricted_function(p, body, name, filename, globalize)

    code = r[0]
    errors = r[1]
    warnings = tuple(r[2])

    if errors:
        logger.warning('\n'.join(errors))
        raise SyntaxError()
    elif warnings:
        logger.warning('\n'.join(warnings))

    g = get_safe_globals()
    g['_getattr_'] = guarded_getattr
    g['__debug__'] = __debug__
    g['__name__'] = 'script'
    l = {}
    exec code in g, l
    f = l.values()[0]

    return f.func_code, g, f.func_defaults or ()
def prepare_restricted_function(p, body, name, filename, globalize=None):
    # We just do what they do in PythonScript...
    r = compile_restricted_function(p, body, name, filename, globalize)

    code = r[0]
    errors = r[1]
    warnings = tuple(r[2])

    if errors:
        logger.warning('\n'.join(errors))
        raise SyntaxError()
    elif warnings:
        logger.warning('\n'.join(warnings))

    g = get_safe_globals()
    g['_getattr_'] = guarded_getattr
    g['__debug__'] = __debug__
    g['__name__'] = 'script'
    l = {}
    exec code in g, l
    f = l.values()[0]

    return f.func_code, g, f.func_defaults or ()
示例#18
0
 def _compiler(self, *args, **kw):
     return compile_restricted_function(*args, **kw)
示例#19
0
 def _compiler(self, *args, **kw):
     return compile_restricted_function(*args, **kw)
示例#20
0
            "load('" + filepath +
            "', '-mat')")  #todo: separate octave instanz für jeden user
        data = octave.pull('Data')
        #todo: fehler check + memoisierung
        return data


flask_app = Flask(__name__)
dash_app = Dash(__name__, server=flask_app)

#Kompilieren der Hauptfunktion
scriptpath = '.\\user001\\scripts\\render_cockpit.py'
myscript = Path(scriptpath).read_text()
render_cockpit_name = 'render_cockpit'
render_cockpit = compile_restricted_function(p='',
                                             body=myscript,
                                             name=render_cockpit_name,
                                             filename='<inline code>')
safe_globals = safe_builtins
safe_locals = {}
additional_globals = {'hydropt': CHydropt(uid=1), 'html': html}
safe_globals.update(additional_globals)
exec(render_cockpit.code, safe_globals, safe_locals)
render_cockpit_pointer = safe_locals[render_cockpit_name]

dash_app.layout = html.Div(id='page-content',
                           children=[dcc.Location(id='url', refresh=False)])


@dash_app.callback(Output('page-content', 'children'),
                   [Input('url', 'pathname')])
def display_page(pathname):
示例#21
0
def crf_mem(body, name):
    return compile_restricted_function(p='',
                                       body=body,
                                       name=name,
                                       filename='<inline code>')
	return h(x + 1)
	
result = math.exp(g(f(data)))
return result
"""

#globale variablen innerhalb der sandbox
safe_locals = {}
safe_globals = safe_builtins
additional_globals = {'data': 2, 'f': lambda x: x**2}
safe_globals.update(additional_globals)

#Kompilieren der Hauptfunktion
main_function_name = 'main'
main_function_compiled = compile_restricted_function(p='',
                                                     body=myscript,
                                                     name=main_function_name,
                                                     filename='<inline code>')

#Kompilieren der Hilfsfunktion
support_function_name = 'h'
support_function_parameters = 'x'
support_function_body = 'return -x'
support_function_compiled = compile_restricted_function(
    p=support_function_parameters,
    body=support_function_body,
    name=support_function_name,
    filename='<inline code>')

#Erstellen des Funktionszeigers der Hilfsfunktion
exec(support_function_compiled.code, safe_globals, safe_locals)
support_function_compiled_pointer = safe_locals[support_function_name]