0
The Django Web Application Framework


Simon Willison
http://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 screensh...
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 possibl...
We didn’t mean to
build a framework...
... but nothing else
really fitted the bill
Building a framework
HTTP handling
GET /community/ HTTP/1.0
Host: www.djangoproject.com

HTTP/1.1 200 OK
Date: Wed, 19 Apr 2006 23:53:29 GMT
Server: Apache
V...
Parse the request;
generate a response
GET variables, POST
 variables, cookies,
   uploaded files,
  caching, content
     negotiation
HttpRequest
HttpResponse
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:
  ...
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
  )
  retur...
class Poll(Model):
  question = CharField(maxlength=200)
  pub_date = DateTimeField('date published')

class Choice(Model)...
BEGIN;
CREATE TABLE quot;polls_pollquot; (
    quot;idquot; serial NOT NULL PRIMARY KEY,
    quot;questionquot; varchar(20...
p = Poll(
  question = quot;What's up?quot;,
  pub_date = datetime.now()
)
p.save()
>>> p.id
1

>>> p.question
quot;What's up?quot;

>>> p.pub_date
datetime(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 %}
    ...
<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': ...
All you really need are
variables, conditionals
      and loops
Essential ingredients
  HTTP handling
  URL dispatching
  Templating
  Documentation
  Database access (optional)


  ... ...
Extras
Forms are boring
1. Display form

2. Validate submitted data

3. If errors, redisplay with:

  3.1. Contextual error messages

  3.2. Corre...
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:
    l...
Smarter templating
Common headers and
    footers?
Template inheritance
base.html
<html>
<head>
<title>
  {% block title %}{% endblock %}
</title>
</head>
<body>
{% block main %}{% endblock %}
<...
home.html

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

{% block main %}
Main page contents goes her...
combined
<html>
<head>
<title>
  Homepage
</title>
</head>
<body>
Main page contents goes here.
<div id=”footer”>
(c) 2006...
Custom template tags
{{ page.content|textile }}
{{ page.content|textile }}

{% comment_form for news.stories
   story.id with is_public yes
   photos_optional thumbs,200,...
from django import template

register = template.Library()

def textile(value):
    try:
         import textile
    excep...
i18n and l10n
Bengali         Japanese
 Czech             Dutch
  Welsh         Norwegian
 Danish           Brazilian
German          Ro...
Authentication and
  authorisation
Community
?
It’s a matter of taste
HTTP handling
 What happens to form variables? GET vs POST
 How to handle /path?foo=1&foo=2
 How to send back non-standard...
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 o...
Templating
 Plain text or XML?
 Markup visible on the page or hidden in
 HTML attributes?
 Logic in the template vs logic ...
Where’s the line?

  Authentication and authorisation?
  Automated admin / forms?
  i18n and l10n?
  JavaScript and Ajax?
Getting involved
Summer of Code 2006
www.djangoproject.com
Extra slides
Comparisons
$_GET, $_POST,
HTTP
                    $_REQUEST etc
URL dispatch           Filesystem

Database handling   mysql_* funct...
HTTP                  CherryPy
                     Object path
URL dispatch
                      traversal
Database hand...
HTTP                ActionController?
                    Object traversal,
URL dispatch
                        Routes
Da...
The Django Web Application Framework
The Django Web Application Framework
The Django Web Application Framework
The Django Web Application Framework
The Django Web Application Framework
The Django Web Application Framework
The Django Web Application Framework
The Django Web Application Framework
The Django Web Application Framework
The Django Web Application Framework
The Django Web Application Framework
The Django Web Application Framework
The Django Web Application Framework
The Django Web Application Framework
The Django Web Application Framework
The Django Web Application Framework
The Django Web Application Framework
The Django Web Application Framework
Upcoming SlideShare
Loading in...5
×

The Django Web Application Framework

32,580

Published on

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

Published in: Technology, Design
4 Comments
48 Likes
Statistics
Notes
No Downloads
Views
Total Views
32,580
On Slideshare
0
From Embeds
0
Number of Embeds
10
Actions
Shares
0
Downloads
1,162
Comments
4
Likes
48
Embeds 0
No embeds

No notes for slide

Transcript of "The Django Web Application Framework"

  1. 1. The Django Web Application Framework Simon Willison http://simonwillison.net/ ACCU, Python Track, 20th April 2006
  2. 2. This talk An overview of Django What's in a web framework, anyway? Framework comparison (and some pretty screenshots, too)
  3. 3. Origins
  4. 4. Lawrence, Kansas - 2003
  5. 5. Web development on Journalism deadlines
  6. 6. ... in three days
  7. 7. The ideal framework... Clean URLs Loosely coupled components Designer-friendly templates As little code as possible Really fast development
  8. 8. We didn’t mean to build a framework...
  9. 9. ... but nothing else really fitted the bill
  10. 10. Building a framework
  11. 11. HTTP handling
  12. 12. GET /community/ HTTP/1.0 Host: www.djangoproject.com HTTP/1.1 200 OK Date: Wed, 19 Apr 2006 23:53:29 GMT Server: Apache Vary: Cookie Connection: close Content-Type: text/html; charset=utf-8 <!DOCTYPE html PUBLIC quot;-//W3C//DTD XHTML 1.0 Transitional//ENquot; quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1- transitional.dtdquot;> <html xmlns=quot;http://www.w3.org/1999/xhtmlquot; xml:lang=quot;enquot; lang=quot;enquot;> <head> [...]
  13. 13. Parse the request; generate a response
  14. 14. GET variables, POST variables, cookies, uploaded files, caching, content negotiation
  15. 15. HttpRequest HttpResponse
  16. 16. def index(request): s = “Hello, World” return HttpResponse(s)
  17. 17. def index(request): r = HttpResponse( mimetype='text/plain' ) r.write(“Hello, World”) return r
  18. 18. def index(request): if request.GET: s = “Hi, %s” % escape(request.GET.get( ’name’, ‘anon’) else: s = “Hello, World” return HttpResponse(s)
  19. 19. URL dispatching
  20. 20. http://www.example.com/poll/5/ What code shall we execute?
  21. 21. urlpatterns = patterns('', (r'^$', 'views.index'), (r'^hello/', ‘views.hello'), (r'^poll/(d+)/', ‘views.poll'), )
  22. 22. Database access
  23. 23. ... (r'^poll/(d+)/', 'views.poll'), ... def poll(request, poll_id): poll = Poll.objects.get( pk=poll_id ) return HttpResponse( 'Title: ' + poll.title )
  24. 24. class Poll(Model): question = CharField(maxlength=200) pub_date = DateTimeField('date published') class Choice(Model): poll = ForeignKey(Poll) choice = CharField(maxlength=200) votes = IntegerField()
  25. 25. BEGIN; CREATE TABLE quot;polls_pollquot; ( quot;idquot; serial NOT NULL PRIMARY KEY, quot;questionquot; varchar(200) NOT NULL, quot;pub_datequot; timestamp with time zone NOT NULL ); CREATE TABLE quot;polls_choicequot; ( quot;idquot; serial NOT NULL PRIMARY KEY, quot;poll_idquot; integer NOT NULL REFERENCES quot;polls_pollsquot; (quot;idquot;), quot;choicequot; varchar(200) NOT NULL, quot;votesquot; integer NOT NULL ); COMMIT;
  26. 26. p = Poll( question = quot;What's up?quot;, pub_date = datetime.now() ) p.save()
  27. 27. >>> p.id 1 >>> p.question quot;What's up?quot; >>> p.pub_date datetime(2005, 7, 15, 12, 00, 53)
  28. 28. Templating
  29. 29. Gluing strings together gets old fast
  30. 30. { 'today': datetime.date.today(), 'edibles': ['pear', 'apple', 'orange'] }
  31. 31. <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 %}
  32. 32. <h1>Hello World!</h1> <p>Today is 20th April, 2006</p> <ul> <li>pear</li> <li>apple</li> <li>orange</li> </ul>
  33. 33. def hello(request): t = get_template('hello.html') c = Context({ 'today': datetime.date.today(), 'edibles': ['pear', 'apple', 'orange'] }) return HttpResponse(t.render(c))
  34. 34. All you really need are variables, conditionals and loops
  35. 35. Essential ingredients HTTP handling URL dispatching Templating Documentation Database access (optional) ... no wonder there are so many frameworks!
  36. 36. Extras
  37. 37. Forms are boring
  38. 38. 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!
  39. 39. Model validation rules + the Manipulator API do all of this for you
  40. 40. django.contrib.admin does even more
  41. 41. 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
  42. 42. Smarter templating
  43. 43. Common headers and footers?
  44. 44. Template inheritance
  45. 45. 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>
  46. 46. home.html {% extends “base.html” %} {% block title %}Homepage{% endblock %} {% block main %} Main page contents goes here. {% endblock %}
  47. 47. combined <html> <head> <title> Homepage </title> </head> <body> Main page contents goes here. <div id=”footer”> (c) 2006 <div> </body> </html>
  48. 48. Custom template tags
  49. 49. {{ page.content|textile }}
  50. 50. {{ 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 %}
  51. 51. 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)
  52. 52. i18n and l10n
  53. 53. Bengali Japanese Czech Dutch Welsh Norwegian Danish Brazilian German Romanian Greek Russian English Slovak Spanish Slovenian French Serbian Galician Swedish Hebrew Ukrainian Icelandic Simplified Chinese Italian Traditional Chinese
  54. 54. Authentication and authorisation
  55. 55. Community
  56. 56. ?
  57. 57. It’s a matter of taste
  58. 58. HTTP handling What 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?
  59. 59. URL dispatching Object traversal or explicit configuration? Reversible URLs? Parameter extraction Trailing slashes?
  60. 60. Database handling To ORM or not to ORM? Pluralisation? Handling joins Lookup syntax When should you fall back on raw SQL?
  61. 61. Templating Plain 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?
  62. 62. Where’s the line? Authentication and authorisation? Automated admin / forms? i18n and l10n? JavaScript and Ajax?
  63. 63. Getting involved
  64. 64. Summer of Code 2006
  65. 65. www.djangoproject.com
  66. 66. Extra slides
  67. 67. Comparisons
  68. 68. $_GET, $_POST, HTTP $_REQUEST etc URL dispatch Filesystem Database handling mysql_* functions Templating <?php ... ?>
  69. 69. HTTP CherryPy Object path URL dispatch traversal Database handling SQLObject Kid (XML), Templating common templating API
  70. 70. HTTP ActionController? Object traversal, URL dispatch Routes Database handling ActiveRecord Templating ERb, Builder, RJS
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×