8 November 2010
Familiarity with Flex, Flash Builder, and ActionScript 3.0; basic understanding of UNIX command-line commands and open source databases
Intermediate
This article explains how to create a Flex 4 application that accesses a back-end based on Python's intuitive web framework, Django. I will show you how to install Django and how to create a simple subscription module that enables users to subscribe to an e-mail list. On the front-end, you will develop a simple subscription application using Adobe Flash Builder 4 and the Flex 4 SDK.
For simplicity, the sample project uses a SQLite3 database interface. You will learn how to pull dynamic content into the Flex 4 application using PyAMF, which enables communication between applications running in Flash Player and Python. I will explain how to install PyAMF and use it to pass data back to your Flex application as strongly typed data objects, which eliminates the need for using XML schemas. I will also cover registering your ActionScript 3.0 classes on the server side, so when the Flex application receives your data, it will be correctly formatted data and ready to use.
One problem developers often run into with Django is a lack of resources that explain how to use it with Flex. This article explores one use case to help you understand just how easy it can be to integrate Flex with Django.
Django is "a Web framework for perfectionists with deadlines" (according to the official Django web site). Django provides an easy way to build applications such as content management systems, widgets, and dynamic components. The framework focuses on adhering to the principle of Don't Repeat Yourself, or DRY. Few developers are excited about repeatedly redeveloping application components, such as a subscription module. Django makes developing this kind of application easy—it just works and gets the job done quickly. Plus, Django derives from Python, which is a language that is relatively easy to pick up. The code is clean and to the point.
In order to install Django, you must have Python 2.5 or later. Although Django works fine with Python 2.4, you'll want to use Python 2.5 because it includes an interface to a lightweight database called SQLite3, which will be used in this tutorial. SQLite3 is bundled with Python 2.5.
To verify your version of Python:
If Python is installed, you'll see a short message indicating its version number (see Figure 1).
Alternatively, you can type python –version, which just displays the version and returns to the command prompt.
If you do not have Python installed, visit the official Python website to download and install the latest version.
Follow these steps to download and install Django:
Note: Django-1.2.1 is the official version as of the writing of this article. You may use a more recent version if it exists; simply adjust the steps below by replacing 1.2.1 with the current version as needed.
Note: On some systems, you may not need to type sudo before the python command. The sudo command executes your command as the superuser, or the admin, of the system, which may not be necessary depending on your permissions. On Mac OS X, this ability is built in to your primary account. If you're using Windows, you'll need to start a command shell with administrator privileges and then run setup.py install.
Next, verify that you've successfully installed Django.
You should see the version number of your Django installation.
PyAMF is a great framework for sending binary objects from the server to your client. PyAMF uses the Adobe Action Message Format (AMF) specification to serialize server-side objects. One benefit to using AMF is performance. AMF is used to encode remote procedures into compact binary representation that can be efficiently transferred over HTTP/HTTPS or RTMP/RTMPS protocols. Another benefit to using PyAMF is that you can maintain the object's data type. So, if the server sends the client an object as an ArrayCollection, for example, the client will receive the object as an ArrayCollection.
The easiest way to install PyAMF is by running the Easy Install package manager for Python. If you have Easy Install set up on your system, simply run the following command:
easy_install pyamfIf you don't have Easy Install or if you encounter problems with the installation, visit the PyAMF site for instructions on manual installation.
With Python, Django, and PyAMF installed, you're ready to create your first Django project. If this is your first time working with Django, you'll have to do some initial setup. You will have to create a Django project in a directory that you will use for all your Django code. A Django project is a directory of code that contains all the settings, such as database configurations, Django-specific options, and application-specific settings.
Follow these steps to start your Django project:
The settings.py file is used to set up your Django-specific configuration. The urls.py file is similar to a controller within an MVC paradigm; it loads the appropriate views (HTML pages) when it receives an URL from the browser. When it finds a match to the HTTP request, it loads the correct view by calling the view's function. You'll delve into this file later, when you hook up the PyAMF gateway.
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = '/Users/anthonycintron/Sites/myapp/mydb'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3'# Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '/Users/anthonycintron/Sites/myapp/mydb', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
The next step is to make the data model for the subscription application. Because this is a small project, you will only have to make one model with a few database fields. Before you create your model, you first have to create a project application. Applications are like modules, or components, in Flex. You should try to make sure that the applications you create are easily adaptable to future projects, since one of the goals of using Django is to create reusable code.
Follow these steps to create the application and data model:
from django.db import models
# Create your models here.
class Subscribe(models.Model):
email = models.EmailField()
receive_communication = models.NullBooleanField(null=True)
def __unicode__(self):
return self.email
This Subscribe class extends Django's Model class. When you run syncdb, the Subscribe model is created and two columns are added: email and receive_communication. The function definition within the class makes the entry a human readable label.
# :from django.contrib import admin
admin.autodiscover()
This enables the controller to find the admin query. The controller is invoked by any request made to the application. It uses the URL to determine what view to display for the user. For example, if an administrator visits http://yourapp.com/admin/, the controller identifies that pattern and then calls the associated view method, which is in the admin.site namespace.
(r'^admin/', include(admin.site.urls)),Now you need to install your Admin and Subscription application.
'django.contrib.admin' and add 'myapp.subscription' to the INSTALLED_APPS setting:INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'myapp.subscription',
)
When you login to your Django administration console, you'll notice the Subscription application is not displayed. This is because you need make the Django project aware of the Subscription model so it can use the model to display the databases data.
To register the Subscription model with Django, follow these steps:
from myapp.subscription.models import Subscribe
from django.contrib import admin
admin.site.register(Subscribe)
Now that you've registered Subscribe, Django will recognize Subscribe in the Administration console (see Figure 4).
You are now ready to build your Flex 4 interface in Flash Builder 4.
You can follow the procedures in this section to build the Flex application yourself, or, if you prefer, import the sample project by completing these steps:
To start your own Flex application, follow these steps:
You may lay out the elements however you like, but you'll need to set some of the component properties to wire them up.
id property of the elements, the click property of the button, and the dataprovider property for the list as shown in the MXML below:<s:layout>
<s:VerticalLayout horizontalAlign="center" verticalAlign="middle"/>
</s:layout>
<s:HGroup>
<s:TextInput id="inputField" width="150" />
<s:Button click="onSend(event)" label="Send"/>
</s:HGroup>
<s:CheckBox label="Email me site updates"
selected="true"
id="receiveUpdates"/>
<s:List id="subscriptionList"
dataProvider="{_list}"
labelField="email"
width="225"
height="100">
<s:layout>
<s:VerticalLayout/>
</s:layout>
</s:List>
To send and receive your ActionScript data, you will need to create a RemoteObject component within the <fx:Declarations> tag. The RemoteObject class gives you access to classes on a remote server. You must include a few attributes for your remote object to work. The channelSet is an array of Channels that are used to send messages to a target destination. (This is defined in the ChannelSet tag immediately above the RemoteObject.) The destination property is the name of your gateway service. Lastly, you need to add the names of your server-side methods.
See the example code below:
<fx:Declarations>
<!-- connection to gateway -->
<s:ChannelSet id="channels">
<s:AMFChannel id="pyamf" uri="http://127.0.0.1:8000/gateway/"/>
</s:ChannelSet>
<s:RemoteObject id="getSubscriptionService"
channelSet="{channels}"
destination="myservice"
showBusyCursor="true"
>
<s:method name="saveEmail"
result="onSaveEmailSuccess(event)"
fault="onFault(event)"/>
<s:method name="getEmailList"
result="onEmailListSuccess(event)"
fault="onFault(event)"/>
</s:RemoteObject>
</fx:Declarations>
One of the great advantages of using PyAMF is the ability to register your ActionScript classes on the server side. You can set the data type of the remote objects so that when they are sent via AMF, ActionScript will already receive strongly typed data. This works well using value objects.
package com.subscription.vos
{
[RemoteClass (alias="com.subscription.vos.SubscriberVO")]
[Bindable]
public class SubscriberVO extends Object
{
public var id:int;
public var email:String;
public var receive_communication:Boolean;
public function SubscriberVO(email:String, receive:Boolean)
{
this.email = email;
this.receive_communication = receive;
}
}
}
In order to register your class for remote use, you must add the RemoteClass metadata tag. This allows the class to be accessible during run time. The class properties must match the server object.
Lastly you will need to add some ActionScript code to handle events.
Back in your project's main MXML file add the following <fx:Script> block after your <fx:Declarations> :
<fx:Declarations>:
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
import mx.collections.ArrayCollection;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
[ArrayElementType("SubscriberVO")]
[Bindable]
private var _list:ArrayCollection;
private function onSaveEmailSuccess(event:ResultEvent):void
{
getSubscriptionService.getEmailList();
}
private function onFault(event:FaultEvent):void
{
trace(event.fault);
}
private function onEmailListSuccess(event:ResultEvent):void
{
_list = new ArrayCollection( event.result as Array );
}
private function onSend(e:MouseEvent):void
{
getSubscriptionService.saveEmail(inputField.text, receiveUpdates.selected );
}
protected function init(event:FlexEvent):void
{
getSubscriptionService.getEmailList();
}
]]>
</fx:Script>
Note the metadata tag ArrayElementType above the private property _list:ArrayCollection . This ensures that every object within the _list ArrayCollection is strictly typed as SubscriberVO.
As a final step, add creationComplete="init(event)" to the main Application tag. The init() method populates the list with email addresses when the application starts.
Next you need to set up your Python methods and then register those methods for front-end accessibility.
import pyamf
from pyamf.flex import ArrayCollection, ObjectProxy
from pyamf.remoting.gateway.django import DjangoGateway
from myapp.subscription.models import Subscribe
pyamf.register_class(Subscribe, 'com.subscription.vos.SubscriberVO')
def saveEmail(request, email, notify):
subscribe = Subscribe()
subscribe.email = email
subscribe.receive_communication = notify
subscribe.save()
return True
def getEmailList(request):
emailList = Subscribe.objects.all()
return emailList
services = {
'myservice.getEmailList':getEmailList,
'myservice.saveEmail':saveEmail,
}
myGateway = DjangoGateway(services, expose_request=True)
This PyAMF gateway has two methods, which provide the ability to add subscribers and retrieve a list of subscribers.
In order for your gateway to be accessible, you must place its path pattern inside your url.py file.
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^myapp/', include('myapp.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'^gateway/', 'myapp.amfgateway.myGateway'),
)
With everything set up on the server, you should be able to run your Flex application and start sending and receiving data.
One of the many helpful features in Flash Builder is the Network Monitor, which enables you to inspect the data that is being passed to and from the server.
To see how it works, follow these steps:
getEmailList operation in Network Monitor.
Now that you have more insight on how to use Python and Django with Flex 4 and Flash Builder 4, you may want to explore http://djangoprojects.com or http://pyamf.org. There are great mailing lists you can subscribe to. You might also want to pay a visit to #pyamf or #flex IRC, as there are people there who will be helpful.
There are hosting companies that provide easy-to-use, pre-installed Django deployments. For a comprehensive list of hosting companies that offer Django friendly services, visit djangofriendly.com. Media Temple and WebFaction are among the most popular. Media Temple has a great control panel, which allows you to easily create applications, restart, and turn on/off your Django project.

This work is licensed under a Creative Commons Attribution-Noncommercial 3.0 Unported License.