Text

Create a simple Guestbook Application

In this blog post, we would create a simple Guestbook application based on the set up configuration of Django on Google App Engine that we have done previously (part 1,part 2)

If you have gone through the above, your project would have the simple structure like this:

This Guestbook application is based on the Google App Engine for Python 2.7 Tutorial. Apart from that, many references also come from the Official Django Tutorial and the Django Book. I found the materials presented there very concise and easy to understand and I highly recommend them.

To create our application, we would proceed with the following steps:

  1. Create the application folder
  2. Defining the models
  3. Defining the views
  4. Defining the templates
  5. Defining the static file folder
  6. Defining the urls

Create the Application Folder

There are 3 locations our application can be put in the project:

  1. In the root project folder (together with main.py and manage.py and at the same level with Project_Name folder)
  2. In the Project_Name folder
  3. In a dedicated folder for all applications called "apps"

In the 1st and 3rd approach, the application can be referenced like:

from guestbook.models import *

In contrast, in the 2nd approach, the application needs to be referenced like:

from Project_Name.guestbook.models import *

Besides, for the 3rd approach to work, the folder "apps" needs to be added to the system path. Instruction to do so can be found here

So depending on your preference, you can choose the location for your application folder accordingly. In this blog post, we would use the 1st approach, which is also used in the Official Django Tutorial:

We proceed to create a package in the root project folder named guestbook. A folder with an __init__.py is created as a result.


Defining the MODELS

We would use Google App Engine datastore model to create the models for our guestbook application. We proceed to create a PyDev module models (which is just a file models.py) in the guestbook package and define the following:

from google.appengine.ext import db

class Greeting(db.Model):
    """Models an individual Guestbook entry with an author, content, and date."""
    author = db.StringProperty()
    content = db.StringProperty(multiline=True)
    date = db.DateTimeProperty(auto_now_add=True)
    
    @classmethod
    def get_key_from_name(cls, guestbook_name=None):
        return db.Key.from_path('Guestbook', guestbook_name or 'default_guestbook')

Defining the VIEWS

We would define the views just like we do for any Django application, with some additional Google App Engine operations to manage the data models. We proceed to create a PyDev module views (which is just a file views.py) in the guestbook package and define the following:

from django.views.generic.simple import direct_to_template
from django.http import HttpResponseRedirect

from google.appengine.api import users

from guestbook.models import Greeting

import urllib

def main_page(request):
    guestbook_name = request.GET.get('guestbook_name', 'default_guestbook')
    guestbook_key = Greeting.get_key_from_name(guestbook_name)
    greetings_query = Greeting.all().ancestor(guestbook_key).order('-date')
    greetings = greetings_query.fetch(10)
    if users.get_current_user():
        url = users.create_logout_url(request.get_full_path())
        url_linktext = 'Logout'
    else:
        url = users.create_login_url(request.get_full_path())
        url_linktext = 'Login'
    template_values = {
        'greetings': greetings,
        'guestbook_name': guestbook_name,
        'url': url,
        'url_linktext': url_linktext,
    }
    return direct_to_template(request, 'guestbook/main_page.html', template_values)

def sign_post(request):
    if request.method == 'POST':
        guestbook_name = request.POST.get('guestbook_name')
        guestbook_key = Greeting.get_key_from_name(guestbook_name)
        greeting = Greeting(parent=guestbook_key)
    
        if users.get_current_user():
            greeting.author = users.get_current_user().nickname()
    
        greeting.content = request.POST.get('content')
        greeting.put()
        return HttpResponseRedirect('/?' + urllib.urlencode({'guestbook_name': guestbook_name}))
    return HttpResponseRedirect('/')

Defining the TEMPLATES

In the main_page view above, we use the HTML template to render the content of the page. We need to configure the TEMPLATE_DIRS in the settings.py file in the Project_Name package:

import os
ROOT_PATH = os.path.dirname(__file__)
TEMPLATE_DIRS = (os.path.join(ROOT_PATH, "templates"),)

This will let Django look into all "templates" folders in the all applications to find the templates to render. Do take note of the comma near the end, it is important that it’s there.

We would also need to add “guestbook” into the list of INSTALLED_APPS:

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    
    'guestbook',
)

After that, in the guestbook package, we would create a folder called "templates" and a subfolder called "guestbook" nested under it. This is to differentiate the template folders of different applications. Then, we would create the files main_page.html in the subfolder guestbook:

<html>
  <head>
    <link type="text/css" rel="stylesheet" href="/static/css/main.css" />
  </head>
  <body>
    {% for greeting in greetings %}
      {% if greeting.author %}
        <b>{{ greeting.author }}</b> wrote:
      {% else %}
        An anonymous person wrote:
      {% endif %}
      <blockquote>{{ greeting.content|escape }}</blockquote>
    {% endfor %}

    <form action="/sign/" method="post">
      {% csrf_token %}
      <input type="hidden" name="guestbook_name" value="{{ guestbook_name }}" />
      <div><textarea name="content" rows="3" cols="60"></textarea></div>
      <div><input type="submit" value="Sign Guestbook"></div>
    </form>

    <a href="{{ url }}">{{ url_linktext }}</a>

  </body>
</html>

Defining the Static File Folder

In the template above, we serve a static stylesheet file called main.css. To do this, we would creat a folder called "static" in the root project folder. We would instruct Google App Engine to serve all files in this folder statically by adding a static_dir handler in the app.yaml file:

handlers:
  
- url: /static
  static_dir: static
  
- url: /.*
  script: main.application

Then, we would create the "css" folder and the corresponding main.css file in this static folder.

body {
  font-family: Verdana, Helvetica, sans-serif;
  background-color: #DDDDDD;
}

Defining the URLs

We would define 2 URLs to serve 2 views main_page and sign_post accordingly. We first modify the urls.py file in the Project_Name package to direct all requests to guestbook application:

from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^', include('guestbook.urls')),
)

We would then create another PyDev module urls (which is just a file urls.py) in the guestbook package to process all requests related to guestbook application:

from django.conf.urls.defaults import *
from guestbook.views import main_page, sign_post

urlpatterns = patterns('',
    (r'^sign/$', sign_post),
    (r'^$', main_page),
)

Our application has been completed! The final folder structure would look like below:


You can proceed to run and test the application. Please note that when we run our application, a file named index.yaml would be automatically created in the root project folder. This is the index file of Google App Engine.

Text

Setting Up Basic Application (Part 2 - Django Framework)

This blog post is the 2nd part of the two-part topic on setting up a basic Django on Google App Engine application. In the first part here, we have created a basic Google App Engine application backbone. In this post, I would elaborate on the steps to configure Django Framework on top of our basic Google App Engine application.

A Stand Alone Django Application

For the benefit of anyone new to Django, a good place to start is to see how we can a simple stand alone Django application looks like before moving on to put it on top of Google App Engine.

To create a stand alone Django application in Eclipse IDE using PyDev:

  1. Select menu File > New > Project
  2. Choose PyDev Django Project under PyDev
  3. Choose your Project Name, Python grammar version and Python Interpreter and click Next and Finish
  4. You have successfully created a Django application. To test run, right click on the Project Name.
  5. Select Run As > PyDev: Django
  6. According to the console, your application can now be accesed at http://localhost:8000.
  7. Done!

Your application folder should have the simple structure as below:


Configure Django on top of Google App Engine application

Our Django on Google App Engine would have similar structure as the one above with a few modifications. So we would get back to our basic Google App Engine application and proceed with the following steps, all in reference to the newly created Django Stand Alone application.

  1. Copy from the Django Stand Alone application to project folder of the Django on App Engine application the file manage.py and the folder Project_Name including the inside files __init__.py, settings.py, urls.py.
  2. The file wsgi.py can be omitted because we are defining a different WSGI interface for Google App Engine.
  3. If you do not have the Django stand alone application, you can download the files at the links I have given above (__init__.py is just an empty file).
  4. Create a new file named main.py in the project folder.

Your application folder should have the simple structure as below:

With this folder structure, we would modify the individual files accordingly as explained below.


main.py [Link]

Include the below content in your file. This is to define the WSGI for the web server.

import django.core.handlers.wsgi

application = django.core.handlers.wsgi.WSGIHandler()

settings.py [Link]

Remove the settings for DATABASES and WSGI_APPLICATION because we would be using Google App Engine datastore and have defined our WSGI in main.py above.

Change the setting for ROOT_URLCONF to the correct 'Project_Name.urls'.

ROOT_URLCONF = 'Project_Name.urls'

manage.py [Link]

Change the setting for DJANGO_SETTINGS_MODULE to the correct "Project_Name.settings".

    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Project_Name.settings")

app.yaml [Link]

Change the runtime to python27 and add threadsafe: true to inform Google App Engine that we are running Python 2.7.

Change the handlers script to main.application because it is where we define our WSGI.

Include Django with the corresponding version in the list of libraries because we are going to use it here.

Set the env_variables - DJANGO_SETTINGS_MODULE to 'Project_Name.settings' so that the application can locate where our Django settings.py is.

application: django-demoapp
version: 1
runtime: python27
api_version: 1
threadsafe: true

handlers:

- url: /.*
  script: main.application
  
libraries:

- name: django
  version: "1.4"
  
env_variables:
  DJANGO_SETTINGS_MODULE: 'Project_Name.settings'

Done! You can try running this new App Engine application. It should display the Django welcome page.

Text

Setting Up Basic Application (Part 1 - Google App Engine)

This blog post presents the operations to set up your first Django on Google App Engine application using the PyDev plug-in in Eclipse IDE. The use of IDE is just to perform some operation faster. If you prefer to use the orginal approach, it is perfectly fine, just make sure the folder structure and settings are set up correspondingly. If you would like to learn more about setting the Eclipse IDE for this development, please refer to my previous blog post for instructions to do so.

This blog post makes 2 assumptions:

  1. Your computer has Python installed. Click here if you need instructions to install it.
  2. Your computer has Google App Engine for Python installed. Click here if you need instructions to install it.

To create a basic application, there are 2 main steps:

  1. Create a Google App Engine application (presented below)
  2. Configure Django framework on this application (presented in the blog post for 2nd part)

Set up a Google App Engine application

Because our application is Django on Google App Engine, the backbone operation is resting predominently on Google App Engine configuration. Therefore, we would create a basic Google App Engine application as the starting point.

  1. Go to File > New > Project
  2. Choose PyDev Google App Engine Project under PyDev folder.
  3. Choose your own project name.
  4. If the Python interpreter for Eclipse has not been configured, you would see the link Please configure an interpreter in the related preferences before proceeding.
  5. Clicking the link will lead you to the Python Interpreters set up. Click Auto Config. The system will help add the necessary paths to your PythonPath. Just click OK to proceed.
  6. Choose the Default interpreter and click Next.
  7. Browse your installed Google App Engine directory. Normally, it is at Program File > Google > google_appengine.
  8. Click OK to include the recommended packages and then click Next.
  9. Fill in your registered App ID. If you have not registered, you can do it here.
  10. Choose one of the given starter template and click Finish.
  11. Done!

Your application folder should have the simple structure as below:


To Test Run Your Application

Our application would run on the bundled Google Appp Engine development server.

  1. Right click on the Project Name
  2. Select Run As > PyDev: Google App Run
  3. According to the console, your application can now be accesed at http://localhost:8080 and the admin portal is at http://localhost:8080/_ah/admin.
  4. Done!

To Deploy Your Application

These steps would deploy your application to the real system.

  1. Right click on the Project Name
  2. Select PyDev: Google App Engine > Upload
  3. Input your email and password in the Send to prompt when prompted.
  4. Your application is now available online at http://your-app-id.appspot.com/
  5. Done!

To Deploy Your Application

These steps would deploy your application to the real system.

  1. Right click on the Project Name
  2. Select PyDev: Google App Engine > Upload
  3. Input your email and password in the Send to prompt when prompted.
  4. Your application is now available online at http://your-app-id.appspot.com/
  5. Done!

We have just completed setting up a basic pure Google App Engine application. To configure Django framework on this application, please refer to my next blog post.

u
Text

Setting up Integrated Development Environment (IDE)

Initially, I started out developing all my applications using just Notepad. In fact, I feel it is a good experience learning from the very basic and without the aid of many automated mechanism. For anyone who would like to try this, I would highly recommend Notepad++, a light-weight but very powerful text editor with many useful functionalities.

However, as time passed, I realised when building complex application with many levels of dependencies and references, it might be a good idea to work on an IDE because it can help consolidate your work into one integrated view and speed up your coding with features such as code-completion, debugging windows, etc.

For developing Django web application on Google App Engine, I have done various research and found there are many good IDEs around. Having experience with Eclipse, I am happy to know that there is a plug-in that serves precisely this purpose called PyDev. Although I have also heard good reviews about an alternative called PyCharm, I have not tested out and have no personal comment about it. So in this blog post, I would give the intructions on how to set up Eclipse with PyDev IDE.

There are 2 main steps:

  1. Set up Eclipse
  2. Set up PyDev Plugin

Set up Eclipse

  1. Go to Java Download, download the Java Platform (JDK) and install it if your computer does not have Java JDK yet. This is necessary for Eclipse to work.
  2. Go to Eclipse Download page to download your prefered version of Eclipse IDE. I would recommend Eclipse Classic version.
  3. Extract the downloaded zip file to a folder and run the eclipse.exe file in the extracted folder.
  4. Choose your preferred Workspace folder. This is the folder where files of all you projects will be stored.
  5. Done!

Set up PyDev Plug-in

PyDev is can be found individually or bundled together in the plug-in Aptana Studio 3. Aptana Studio 3 provides many interesting functionalities to help with web development. So I would to install Aptana Studio 3 plug-in and we’ll be good to go.

  1. In Eclipse, go to menu Help > Install New Software…
  2. Input Work with: http://download.aptana.com/studio3/plugin/install
  3. Click Add. The Wizard will ask for the name of the repository and will help guide you in the installation. Just choose Yes / Agree / Next to proceed with the installation.
  4. Done!

On a side note, here is the PyDev Blog maintained by Fabio Zadrozny, the maintainer of PyDev. I find there are many interesting articles with useful insights there.