The Django Web Application Framework

88
The Django Web Application Framework Simon Willison http://simonwillison.net/ ACCU, Python Track, 20th April 2006

description

Slides from a talk given to the ACCU Python Track in Oxford, on the 20th April 2006.

Transcript of The Django Web Application Framework

Page 1: The Django Web Application Framework

The Django Web Application Framework

Simon Willisonhttp://simonwillison.net/

ACCU, Python Track, 20th April 2006

Page 2: The Django Web Application Framework

This talk

An overview of Django

What's in a web framework, anyway?

Framework comparison

(and some pretty screenshots, too)

Page 3: The Django Web Application Framework

Origins

Page 4: The Django Web Application Framework

Lawrence, Kansas - 2003

Page 5: The Django Web Application Framework
Page 6: The Django Web Application Framework
Page 7: The Django Web Application Framework
Page 8: The Django Web Application Framework
Page 9: The Django Web Application Framework
Page 10: The Django Web Application Framework

Web development on Journalism deadlines

Page 11: The Django Web Application Framework
Page 12: The Django Web Application Framework
Page 13: The Django Web Application Framework
Page 14: The Django Web Application Framework
Page 15: The Django Web Application Framework

... in three days

Page 16: The Django Web Application Framework

The ideal framework...Clean URLs

Loosely coupled components

Designer-friendly templates

As little code as possible

Really fast development

Page 17: The Django Web Application Framework

We didn’t mean to build a framework...

Page 18: The Django Web Application Framework

... but nothing else really fitted the bill

Page 19: The Django Web Application Framework

Building a framework

Page 20: The Django Web Application Framework

HTTP handling

Page 21: The Django Web Application Framework

HTTP/1.1 200 OKDate: Wed, 19 Apr 2006 23:53:29 GMTServer: ApacheVary: CookieConnection: closeContent-Type: text/html; charset=utf-8

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1- transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> [...]

GET /community/ HTTP/1.0Host: www.djangoproject.com

Page 22: The Django Web Application Framework

Parse the request; generate a response

Page 23: The Django Web Application Framework

GET variables, POST variables, cookies,

uploaded files, caching, content

negotiation

Page 24: The Django Web Application Framework

HttpRequestHttpResponse

Page 25: The Django Web Application Framework

def index(request): s = “Hello, World” return HttpResponse(s)

Page 26: The Django Web Application Framework

def index(request): r = HttpResponse( mimetype='text/plain' ) r.write(“Hello, World”) return r

Page 27: The Django Web Application Framework

def index(request): if request.GET: s = “Hi, %s” % \ escape(request.GET.get( ’name’, ‘anon’) else: s = “Hello, World” return HttpResponse(s)

Page 28: The Django Web Application Framework

URL dispatching

Page 29: The Django Web Application Framework

http://www.example.com/poll/5/

What code shall we execute?

Page 30: The Django Web Application Framework

urlpatterns = patterns('', (r'^$', 'views.index'), (r'^hello/', ‘views.hello'), (r'^poll/(\d+)/', ‘views.poll'),)

Page 31: The Django Web Application Framework

Database access

Page 32: The Django Web Application Framework

...(r'^poll/(\d+)/', 'views.poll'),...

def poll(request, poll_id): poll = Poll.objects.get( pk=poll_id ) return HttpResponse( 'Title: ' + poll.title )

Page 33: The Django Web Application Framework

class Poll(Model): question = CharField(maxlength=200) pub_date = DateTimeField('date published')

class Choice(Model): poll = ForeignKey(Poll) choice = CharField(maxlength=200) votes = IntegerField()

Page 34: The Django Web Application Framework

BEGIN;CREATE TABLE "polls_poll" ( "id" serial NOT NULL PRIMARY KEY, "question" varchar(200) NOT NULL, "pub_date" timestamp with time zone NOT NULL);CREATE TABLE "polls_choice" ( "id" serial NOT NULL PRIMARY KEY, "poll_id" integer NOT NULL REFERENCES "polls_polls" ("id"), "choice" varchar(200) NOT NULL, "votes" integer NOT NULL);COMMIT;

Page 35: The Django Web Application Framework

p = Poll( question = "What's up?", pub_date = datetime.now())p.save()

Page 36: The Django Web Application Framework

>>> p.id1

>>> p.question"What's up?"

>>> p.pub_datedatetime(2005, 7, 15, 12, 00, 53)

Page 37: The Django Web Application Framework

Templating

Page 38: The Django Web Application Framework

Gluing strings together gets old fast

Page 39: The Django Web Application Framework

{ 'today': datetime.date.today(), 'edibles': ['pear', 'apple', 'orange']}

Page 40: The Django Web Application Framework

<h1>Hello World!</h1>

<p>Today is {{ today|date:”jS F, Y” }}</p>

{% if edibles %}<ul> {% for fruit in edibles %} <li>{{ fruit }}</li> {% endfor %}</ul>{% endif %}

Page 41: The Django Web Application Framework

<h1>Hello World!</h1>

<p>Today is 20th April, 2006</p>

<ul> <li>pear</li> <li>apple</li> <li>orange</li></ul>

Page 42: The Django Web Application Framework

def hello(request): t = get_template('hello.html') c = Context({ 'today': datetime.date.today(), 'edibles': ['pear', 'apple', 'orange'] }) return HttpResponse(t.render(c))

Page 43: The Django Web Application Framework

All you really need are variables, conditionals

and loops

Page 44: The Django Web Application Framework

HTTP handling

URL dispatching

Templating

Documentation

Database access (optional)

... no wonder there are so many frameworks!

Essential ingredients

Page 45: The Django Web Application Framework

Extras

Page 46: The Django Web Application Framework

Forms are boring

Page 47: The Django Web Application Framework

1. Display form

2. Validate submitted data

3. If errors, redisplay with:

3.1. Contextual error messages

3.2. Correct fields pre-filled

4. ... do something useful!

Page 48: The Django Web Application Framework

Model validation rules + the Manipulator API

do all of this for you

Page 49: The Django Web Application Framework

django.contrib.admin does even more

Page 50: The Django Web Application Framework
Page 51: The Django Web Application Framework

class Poll(Model): question = CharField(maxlength=200) pub_date = DateTimeField('date published') class Admin: list_display = ('question', 'pub_date')

class Choice(Model): poll = ForeignKey(Poll) choice = CharField(maxlength=200) votes = IntegerField() class Admin: pass

Page 52: The Django Web Application Framework

Smarter templating

Page 53: The Django Web Application Framework

Common headers and footers?

Page 54: The Django Web Application Framework

Template inheritance

Page 55: The Django Web Application Framework

base.html<html><head><title> {% block title %}{% endblock %}

</title></head><body>{% block main %}{% endblock %}

<div id=”footer”>{% block footer %}(c) 2006{% endblock %}<div></body></html>

Page 56: The Django Web Application Framework

home.html

{% extends “base.html” %}{% block title %}Homepage{% endblock %}

{% block main %}

Main page contents goes here.{% endblock %}

Page 57: The Django Web Application Framework

combined<html><head><title> Homepage</title></head><body>Main page contents goes here.

<div id=”footer”>(c) 2006<div></body></html>

Page 58: The Django Web Application Framework

Custom template tags

Page 59: The Django Web Application Framework
Page 60: The Django Web Application Framework

{{ page.content|textile }}

Page 61: The Django Web Application Framework

{{ page.content|textile }}

{% comment_form for news.stories story.id with is_public yes photos_optional thumbs,200,400 ratings_optional scale:1-5|first_option|second_option %}

Page 62: The Django Web Application Framework

from django import template

register = template.Library()

def textile(value): try: import textile except ImportError: return value else: return textile.textile(value)

register.filter(textile)

Page 63: The Django Web Application Framework

i18n and l10n

Page 64: The Django Web Application Framework
Page 65: The Django Web Application Framework

BengaliCzechWelshDanishGermanGreekEnglishSpanishFrenchGalicianHebrewIcelandicItalian

JapaneseDutch

NorwegianBrazilian

RomanianRussianSlovak

SlovenianSerbianSwedish

UkrainianSimplified ChineseTraditional Chinese

Page 66: The Django Web Application Framework

Authentication and authorisation

Page 67: The Django Web Application Framework

Community

Page 68: The Django Web Application Framework

?

Page 69: The Django Web Application Framework

It’s a matter of taste

Page 70: The Django Web Application Framework

HTTP handlingWhat happens to form variables? GET vs POST

How to handle /path?foo=1&foo=2

How to send back non-standard responses

Different Content-Type (and other) headers

404s, 500s

Session support?

Page 71: The Django Web Application Framework

URL dispatching

Object traversal or explicit configuration?

Reversible URLs?

Parameter extraction

Trailing slashes?

Page 72: The Django Web Application Framework

Database handling

To ORM or not to ORM?

Pluralisation?

Handling joins

Lookup syntax

When should you fall back on raw SQL?

Page 73: The Django Web Application Framework

TemplatingPlain text or XML?

Markup visible on the page or hidden in HTML attributes?

Logic in the template vs logic in the view/controller

Safe (and limited) or unsafe (and more powerful)

Language extension mechanism?

Page 74: The Django Web Application Framework

Where’s the line?

Authentication and authorisation?

Automated admin / forms?

i18n and l10n?

JavaScript and Ajax?

Page 75: The Django Web Application Framework

Getting involved

Page 76: The Django Web Application Framework
Page 77: The Django Web Application Framework
Page 78: The Django Web Application Framework

Summer of Code 2006

Page 80: The Django Web Application Framework
Page 81: The Django Web Application Framework

Extra slides

Page 82: The Django Web Application Framework

Comparisons

Page 83: The Django Web Application Framework
Page 84: The Django Web Application Framework

HTTP$_GET, $_POST, $_REQUEST etc

URL dispatch Filesystem

Database handling mysql_* functions

Templating <?php ... ?>

Page 85: The Django Web Application Framework
Page 86: The Django Web Application Framework

HTTP CherryPy

URL dispatchObject path

traversal

Database handling SQLObject

TemplatingKid (XML), common

templating API

Page 87: The Django Web Application Framework
Page 88: The Django Web Application Framework

HTTP ActionController?

URL dispatchObject traversal,

Routes

Database handling ActiveRecord

Templating ERb, Builder, RJS