Django 与 Flex.
想要开发一个漂亮的网站,总要一些flash效果滴。这就涉及到django如何与flex打交道。基本的原理是利用pyamf这个中间件,把django里的request和flex里的actionscript 互相转化。
1. 安装pyamf. 我使用的是0.6.1. 没说的,老方法,python manage.py install就安装好了。
2. django端(服务器端)创建方法:
a. 创建amfgateway.py在你的工程根目录下
b. 添加如下内容:
def say_hello(request, name):
return "hello : %s" % name
usersGateway = DjangoGateway({
'my.sayHello':say_hello,
})
注意里面的"my", 这会在后面的flex端使用。
c. 修改你的urls.py,添加 (r'^my/gateway/', 'my.amfgateway.usersGateway'),
3. Flex端:
首先创建services-config.xml,添加如下内容:
<services-config>
<services>
<service id="activeService" class="flex.messaging.services.RemotingService" messageTypes="flex.messaging.messages.RemotingMessage">
<destination id="my">
<channels>
<channel ref="myChannel"/>
</channels>
<properties>
<source>*</source>
</properties>
</destination>
</service>
</services>
<channels>
<channel-definition id="myChannel" class="mx.messaging.channels.AMFChannel">
<endpoint uri="http://127.0.0.1:8000/my/gateway/" class="flex.messaging.endpoints.AMFEndpoint"/>
</channel-definition>
</channels>
</services-config>
注意destination 的 id属性必须与第二步的my相同。
3. Flex端写一个简单的测试:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute" initialize="init();" xmlns:s="library://ns.adobe.com/flex/spark">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.rpc.AsyncResponder;
import mx.rpc.AsyncToken;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
private function sayHello():void{
var token:AsyncToken = djangoService.sayHello('Joe');
token.addResponder(new AsyncResponder(afterSayHello, falutHandler));
}
private function falutHandler(error:Object, token:Object=null):void{
var evt:FaultEvent=error as FaultEvent;
Alert.show(evt.message.toString());
}
private function afterSayHello(result:Object, token:Object=null):void{
var evt:ResultEvent=result as ResultEvent;
Alert.show(evt.result as String);
}
protected function button1_clickHandler(event:MouseEvent):void
{
sayHello();
}
]]>
</mx:Script>
<mx:RemoteObject id="djangoService" destination="my"/>
<s:Button click="button1_clickHandler(event)" content="Click Me">
</s:Button>
</mx:Application>
试着运行一下:
下一篇会写如何将写好的swf文件插入到html里。