What is Django?

Django is a Python-based web framework. It endorses the doctrine of clear Model-View-Controller design pattern and provides convenient APIs and shortcuts for programmers to maximize their efficiency when creating a website.

So, what is a web framework? Web frameworks are programming libraries and tools that are used by programmers to create web service endpoints. A web framework provides lots of idioms, APIs and shortcuts so that a programmer can save lots of effort when creating a website. In the following parts of the article, we’re going to evaluate the Python code of a website written in two-styles, one with framework support and one without.

Without a Python Web Framework: CGI

The Common Gateway Interface is a standard method for web server software to delegate the generation of web content to executable files. Such executable files are also called CGI scripts.

Here’s an example of a simple CGI script that generates a simple web page:

#!/usr/bin/env python
print 'Content-Type: text/html\n'
print '<h1>Hello World!</h1>'

The code seems pretty simple, and you can simply deploy this page by saving the script file with a '.cgi' extension and copy-and-pasting the script file into the ‘cgi-bin/’ folder in the document root of your web server (Apache, Nginx, Lighttpd, etc.).

Why use a Web Framework with Python?

So, if writing CGI scripts does not look bad at all, why do we need web frameworks? Well, there are couple of reasons. First, the previous example is extremely simple. It’s basically a static web page with simple text content. More often than not, we’re going to write websites with dynamic content generated from a backend database and writing CGI scripts to handle dynamic content is error-prone and tedious. Second, the CGI script in the previous example puts everything, the model (the text “Hello World”), the view (the print statements) and the controller (the Content-Type statement) all in one script file. Although it’s fine for a small file like the previous example, it’s definitely too complex to manage for any significant website. You need a web framework to provide a clean Model-View-Controller guideline so that you can write the website code in a way that separates the model, the view and the controller away from each other, which allows you to modify each component without affecting others.

With a Web Framework: Django

Just like the previous CGI script, the following snippet is a Django-based approach to serve the same static page behind a web server. Notice that the code is split into three Python files (models.py, views.py, urls.py) and one HTML template file (hello_world.html).

models.py

# Define database models and tables; empty for
# now since this example does not require any
# database-generated content
from django.db import models

views.py

# Define how database models are exposed and what kind
# of business logic is used to process the data
from django.shortcuts import render_to_response

def hello_world(request):
    # The request object encapsulates information about the current
    # HTTP request, the web server's environment, the session, etc.
    # It's almost equivalent to a user-input object in a desktop application.
    return render_to_response('hello_world.html')

urls.py

# Configure how URLs under the website's root
# path are mapped to which views in views.py
from django.conf.urls.defaults import *
import views

urlpatterns = patterns(
    '',
    # This line says the url '/hello_world/' triggers
    # views.hello_world(request) when the user accesses
    # /hello_world/, the function 'views.hello_world'
    # will be called to handle it.
    (r'^hello_world/$', views.hello_world)
)

hello_world.html

<h1>Hello World!</h1>

Don’t worry about the details of the code; instead get a feel of the big picture. Compared to the CGI script, Django’s implementation separates concerns away from each other:

  • The models.py file describes database tables using Django’s own Object Relational Mapping (ORM). Instead of writing raw SQL statements like in a CGI script, Django’s ORM frees the programmer from tedious, error-prone SQL statements and allows one to treat database records and tables like plain old Python objects.
  • The views.py file describes views or business logic. These views allow a programmer to expose endpoints of the website so that users can create, read, update and delete database records in a way that makes sense to the users.
  • The urls.py file describes URL patterns that map from a URL to a view function. For example, the URL /hello_world/ is handled by the hello_world(request) function. More specifically, suppose your domain is myawesomewebsite.com, then any visit to the URL http://myawesomewebsite.com/hello_world/ will call the function hello_world(request).
  • The hello_world.html file describes how to render the /hello_world/ page using Django’s template language. In addition to normal HTML syntax, Django’s template language introduces powerful idioms for the programmer to write normal Python code inside a HTML page. For example:
    <ul>
    {% for user in user_list %}
    	<li>{{ user.username }}</li>
    {% endfor %}
    </ul>
    

    Outputs a list of usernames onto the page.

Summary

Django’s Model-View-Controller pattern is a very powerful software engineering doctrine which separates the components defining data models (M) from the components defining request handling logic (C), which in turn is separated from the user interface (V). Notice that Django’s views are controllers (C) while its templates are views (V).

The most important advantage of MVC pattern over the ad-hoc CGI pattern is that each separated group of components can be modified, maintained and tested within their own context which does not affect other groups of components. For example, a Python developer can change the URL patterns without changing the underlying views while a CSS and Javascript designer can change the HTML pages without changing models and views. On the contrary, the CGI pattern requires the developer to worry about URL pattern changes breaking the underlying views and the designer to worry about Javascript changes breaking the URL patterns.

Download Source Code
Download as PDF
Tags: ,

About The Author