Requirements
     
Prerequisite knowledge
Required products    

Familiarity with Flex, Flash Builder, and ActionScript 3.0; basic understanding of UNIX command-line commands and open source databases

Flash Builder 4 (Download trial)

 

   
User level      
Intermediate      

 
Additional Requirements

 
Django 1.2.1
 
PyAMF 0.6
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.
 

 
Installing 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.
 

 
Checking for Python

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:
 
  1. Open a terminal.
  2. Type python. (At the command line, press Enter to execute each command after you type it.)
If Python is installed, you'll see a short message indicating its version number (see Figure 1).
 
  1. Press Ctrl+D to quit Python.
Alternatively, you can type python –version, which just displays the version and returns to the command prompt.
 
Python displays its version on startup.
Figure 1. Python displays its version on startup.
If you do not have Python installed, visit the official Python website to download and install the latest version.
 

 
Download and install Django

Follow these steps to download and install Django:
 
  1. Visit the Django download page and download the latest official version.
  2. In your terminal, change to the directory in which you downloaded the Django-1.2.1.tar.gz file; for example, type cd /downloads if you downloaded the file to /downloads.
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.
 
  1. Type tar xzvf Django-1.2.1.tar.gz to extract the compressed archive file.
  2. Type cd Django-1.2.1.
  3. Type sudo python setup.py install
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.
 
  1. Type python.
  2. At the python prompt (>>>), type import django.
  3. Type django.get_version().
You should see the version number of your Django installation.
 

 
Installing PyAMF

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 pyamf
If you don't have Easy Install or if you encounter problems with the installation, visit the PyAMF site for instructions on manual installation.
 

 
Creating a Django project

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.
 

 
Creating a project

Follow these steps to start your Django project:
 
  1. Change to a directory that will contain all your Django code. For example, create a folder named /Django and then type cd /Django.
  2. Type django-admin.py startproject myapp.
  3. Type cd myapp to change to the newly create myapp directory.
  4. Type ls to see the automatically generated files (see Figure 2).
The newly created Django projects directory contains several files.
Figure 2. The newly created Django projects directory contains several files.
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.
 
  1. Edit your settings.py file and set the database engine and name as shown below. (Change the path to the database to a file in the newly created myapp directory.)
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. } }
  1. Save the changes you made to settings.py and return to the command line.
  2. At the command line, type python manage.py syncdb.
  3. You will be asked to define a superuser; follow the instructions to do so (see Figure 3).
Run python manage.py syncdb to create the database.
Figure 3. Run python manage.py syncdb to create the database.

 
Creating your data model

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:
 
  1. In the myapp directory, type python manage.py startapp subscription to create a new application named subscription.
  2. Type cd subscription to change to the new subscription directory.
  3. Edit the models.py file and add the following lines:
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
  1. Save your changes.
  2. Type cd .. to change back to the myapp directory.
  3. Type python manage.py syncdb.
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.
 
  1. Edit urls.py and uncomment the following lines by removing the leading # :
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.
 
  1. While editing urls.py, uncomment the following line to enable the Django Admin application:
(r'^admin/', include(admin.site.urls)),
  1. Save your changes.
Now you need to install your Admin and Subscription application.
 
  1. Edit settings.py again.
  2. At the end of the file uncomment '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', )
  1. Save your changes.
  2. Back at the command line, type python manage.py syncdb to add the applications to the database.
  3. Finally, type python manage.py runserver to start the server.
  4. In your browser, go to http://127.0.0.1:8000/admin/ and login to your Django administration console.

 
View Subscription inside Django Admin

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:
 
  1. Change to your myapp/subscription directory.
  2. In that directory, create a file named admin.py file with the following contents:
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).
 
After Subscription is registered it appears in the Django administration console.
Figure 4. After Subscription is registered it appears in the Django administration console.

 
Building the Flex 4 application

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:
 
  1. Download and extract the sample files for this tutorial.
  2. Start Flash Builder.
  3. Choose File > Import Flex Project (FXP).
  4. Browse to and select Subscription.fxp.

 
Setting up the user interface

To start your own Flex application, follow these steps:
 
  1. Start Flash Builder.
  2. Choose File > New > Flex Project
  3. Give the project a name, select the Flex 4 SDK, and set the Application Server Type to None/Other.
  4. Click Finish.
  5. In Design view, add a TextInput, a Submit Button, a List, and a Checkbox with a label (see Figure 5).
The layout includes a TextInput, Button, Checkbox, and List.
Figure 5. The layout includes a TextInput, Button, Checkbox, and List.
You may lay out the elements however you like, but you'll need to set some of the component properties to wire them up.
 
  1. Switch back to Source view.
  2. Set the 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>

 
Adding RemoteObject

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>

 
Creating a Subscriber value object

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.
 
  1. In Flash Builder right-click the src folder and select New > Package.
  2. Name the package com.subscription.vos.
  3. Right-click the new package and select New > ActionScript Class.
  4. Name the class SubscriberVO.
  5. Give SubscriberVO properties that match the data model on the server; for example:
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.
 

 
Handling events

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.
 

 
Configuring the PyAMF gateway

Next you need to set up your Python methods and then register those methods for front-end accessibility.
 
  1. In the terminal, change to the myapp directory.
  2. Create a file named amfgateway.py.
  3. Add the following code to the new file:
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.
 
  1. Edit url.py and add the code in bold below:
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'), )
  1. Restart Django.

 
Running the application using Network Monitor

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:
 
  1. Click the Network Monitor tab to open Network Monitor (or choose Window > Network Monitor).
  2. To enable monitoring, click the Enable Monitor button in the upper right.
  3. Run your application.
  4. Type an email address and click the button to send it to the server.
  5. Back in Flash Builder, select the getEmailList operation in Network Monitor.
  6. Click the Response tab to see the AMF object (see Figure 6).
Network Monitor helps you debug your requests and responses.
Figure 6. Network Monitor helps you debug your requests and responses.

 
Where to go from here

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.