Executing server side scripts from browser

Published by tactic on

TACTIC provides a number of mechanism to Python code on the server. We can start with a widget in the Custom Layout Editor with the HTML definition:

<div>
  <input type=”button press_me” name=”Press Me”/>
</div>

In the behaviors:

var script_path = “my_scripts/press_me”;
var kwargs = {};
var server = TacticServerStub.get();
server.execute_python_script(path, kwargs);
 

In the Script Editor, you can create a script with the folder “my_scripts” and title “press_me”.

print(“Button is pressed”)

This simple example prints “Button is pressed” to the console. Of course, this script can contain any Python code. In this example, the script is blocking. This is not usually desirable because blocking scripts cause the Javascript engine to wait until the full execution of the script. Except for very fast and small scripts, this will negatively influence the user experience. In order to run the script asynchronously, you could run the following call instead:

server.execute_python_script(path, kwargs, {
    on_complete: function() {
        spt.alert(“Script Complete”);
    }
} )

This works well for simple scripts that need to be executed on the server. It is often desirable to use full python classes to execute scripts on the server side. To execute a class on the server, you need to derive the class from the TACTIC Command class and override the execute function.

from pyasm.command import Command

class MyCmd(Command):
    def exectute(self):
        print “Running ....”
        print “kwargs: “, self.kwargs

        my.info = {
            test: 456
        }

Instead of “server.execute_python_script” in the behavior, you would have:

var cmd = “foo.MyCmd”
var kwargs = {
     test: 123
}
var server = TacticServerStub.get()
var ret_val = server.execute_cmd(cmd, kwargs);

The kwargs for the command will be the dictionary with key “test” and value “123”. The returned value is a dictionary that will contain any error information as well as an “info” dictionary that will contained any returned data from the command itself. In the example above, it would return the dictionary with the key “test” and value “456”.

This method allows you to create interface elements and then run custom scripts on the server based on interaction with those interface elements. The HTML code is connected to the behaviors which run Javascript code. The javascript uses the TACTIC API to execute commands directly on the TACTIC Server and provides a clear mechanism to send information to the command as well as receive information from the command.

Categories: Articles

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *