The Django Web Application Framework

Post on 06-May-2015

31.994 views 2 download

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

The Django Web Application Framework

Simon Willisonhttp://simonwillison.net/

ACCU, Python Track, 20th April 2006

This talk

An overview of Django

What's in a web framework, anyway?

Framework comparison

(and some pretty screenshots, too)

Origins

Lawrence, Kansas - 2003

Web development on Journalism deadlines

... in three days

The ideal framework...Clean URLs

Loosely coupled components

Designer-friendly templates

As little code as possible

Really fast development

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

... but nothing else really fitted the bill

Building a framework

HTTP handling

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

Parse the request; generate a response

GET variables, POST variables, cookies,

uploaded files, caching, content

negotiation

HttpRequestHttpResponse

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

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

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

URL dispatching

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

What code shall we execute?

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

Database access

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

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

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

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

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;

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

>>> p.id1

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

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

Templating

Gluing strings together gets old fast

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

<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 %}

<h1>Hello World!</h1>

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

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

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

All you really need are variables, conditionals

and loops

HTTP handling

URL dispatching

Templating

Documentation

Database access (optional)

... no wonder there are so many frameworks!

Essential ingredients

Extras

Forms are boring

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!

Model validation rules + the Manipulator API

do all of this for you

django.contrib.admin does even more

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

Smarter templating

Common headers and footers?

Template inheritance

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>

home.html

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

{% block main %}

Main page contents goes here.{% endblock %}

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

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

Custom template tags

{{ page.content|textile }}

{{ 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 %}

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)

i18n and l10n

BengaliCzechWelshDanishGermanGreekEnglishSpanishFrenchGalicianHebrewIcelandicItalian

JapaneseDutch

NorwegianBrazilian

RomanianRussianSlovak

SlovenianSerbianSwedish

UkrainianSimplified ChineseTraditional Chinese

Authentication and authorisation

Community

?

It’s a matter of taste

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?

URL dispatching

Object traversal or explicit configuration?

Reversible URLs?

Parameter extraction

Trailing slashes?

Database handling

To ORM or not to ORM?

Pluralisation?

Handling joins

Lookup syntax

When should you fall back on raw SQL?

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?

Where’s the line?

Authentication and authorisation?

Automated admin / forms?

i18n and l10n?

JavaScript and Ajax?

Getting involved

Summer of Code 2006

Extra slides

Comparisons

HTTP$_GET, $_POST, $_REQUEST etc

URL dispatch Filesystem

Database handling mysql_* functions

Templating <?php ... ?>

HTTP CherryPy

URL dispatchObject path

traversal

Database handling SQLObject

TemplatingKid (XML), common

templating API

HTTP ActionController?

URL dispatchObject traversal,

Routes

Database handling ActiveRecord

Templating ERb, Builder, RJS