How to create Flash RPC applications using Web2PY and PyAMF
[edit]Since web2py 1.61 which include decorator @service.amfrpc3 descrived here
by Sharriff Aina modified by MDP
I would explain with a very simple example how you can create Flash RPC applications using Web2py as a RPC service provider. I expect you to be familiar with the following topics as they are beyond the scope of this HowTo: Actionscript programming
- RPC Web services
- AMF
- Web2PY programming
Start off by getting the latest Web2Py from the site. Next, retrieve the latest version of PyAMF from the Python CheeseShop or directly from the PyAMF site http://pyamf.org/wiki/Download
Lets create a simple service that takes 2 numerical values, adds them together and returns the sum. We would call the service myservice. Create a flash file using Adobe Flash (all versions as from MX 2004), in the first frame of the file, add these lines:
import mx.remoting.Service;
import mx.rpc.RelayResponder;
import mx.rpc.FaultEvent;
import mx.rpc.ResultEvent;
import mx.remoting.PendingCall;
val1 = 23;
val2 = 86;
service = new Service("http://localhost:8000/pyamf_test/default/
data/amfrpc3", null, "myservice", null, null);
var pc:PendingCall = service.addNumbers(val1, val2);
pc.responder = new RelayResponder(this, "onResult", "onFault");
function onResult(re:ResultEvent):Void {
trace("Result : " + re.result);
txt_result.text = re.result;
}
function onFault(fault:FaultEvent):Void {
trace("Fault: " + fault.fault.faultstring);
}
stop();
The last thing to do would be to create a dynamic text field called txt_result and place it on the stage.
As you have noticed, we have imported the mx remoting classes to enable Remoting in Flash, you can get them here. I would be using the Actionscript version 2 version of the classes. Add the path of the classes to your class path in the Adobe Flash IDE or just place the mx folder next to the newly created file. Compile and export(publish) the swf flash file as pyamf_test.swf.
Lets set up the gateway in Web2Py as we defined in our Flash file, create a new appliance, pyamf_test, in the default controller, create a function called gateway and add these lines to it:
@service.amfrpc3('myservice')
def addNumbers(val1, val2):
return val1 + val2
def data(): return service()
The latter action is already in the scaffolding app.
You can add other function to the service my using the @service.amfrpc3() decorator. Web2py provides similar decorators for json, jsonrpc, xml, xmrrpc, rss, and csv, and the can be combined to expose the same function using multiple protocols.
Next, place the pyamftest.amf, pyamftest.html, ACRunActiveContent.js, crossdomain.xml files in the static folder of the pyamftest controller,fireup web2py using 8000 as the server port, point your browser to
http://localhost:8000/pyamf_test/static/pyamf_test.html
and see the result of the addNumbers function displayed in the textfield.