The Django Web Application Framework

35,813
-1

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
35,813
On Slideshare
0
From Embeds
0
Number of Embeds
11
Actions
Shares
0
Downloads
1,205
Comments
4
Likes
48
Embeds 0
No embeds

No notes for slide

The Django Web Application Framework

  1. The Django Web Application Framework Simon Willison http://simonwillison.net/ ACCU, Python Track, 20th April 2006
  2. This talk An overview of Django What's in a web framework, anyway? Framework comparison (and some pretty screenshots, too)
  3. Origins
  4. Lawrence, Kansas - 2003
  5. Web development on Journalism deadlines
  6. ... in three days
  7. The ideal framework... Clean URLs Loosely coupled components Designer-friendly templates As little code as possible Really fast development
  8. We didn’t mean to build a framework...
  9. ... but nothing else really fitted the bill
  10. Building a framework
  11. HTTP handling
  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. Parse the request; generate a response
  14. GET variables, POST variables, cookies, uploaded files, caching, content negotiation
  15. HttpRequest HttpResponse
  16. def index(request): s = “Hello, World” return HttpResponse(s)
  17. def index(request): r = HttpResponse( mimetype='text/plain' ) r.write(“Hello, World”) return r
  18. def index(request): if request.GET: s = “Hi, %s” % escape(request.GET.get( ’name’, ‘anon’) else: s = “Hello, World” return HttpResponse(s)
  19. URL dispatching
  20. http://www.example.com/poll/5/ What code shall we execute?
  21. urlpatterns = patterns('', (r'^$', 'views.index'), (r'^hello/', ‘views.hello'), (r'^poll/(d+)/', ‘views.poll'), )
  22. Database access
  23. ... (r'^poll/(d+)/', 'views.poll'), ... def poll(request, poll_id): poll = Poll.objects.get( pk=poll_id ) return HttpResponse( 'Title: ' + poll.title )
  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. 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. p = Poll( question = quot;What's up?quot;, pub_date = datetime.now() ) p.save()
  27. >>> p.id 1 >>> p.question quot;What's up?quot; >>> p.pub_date datetime(2005, 7, 15, 12, 00, 53)
  28. Templating
  29. Gluing strings together gets old fast
  30. { 'today': datetime.date.today(), 'edibles': ['pear', 'apple', 'orange'] }
  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. <h1>Hello World!</h1> <p>Today is 20th April, 2006</p> <ul> <li>pear</li> <li>apple</li> <li>orange</li> </ul>
  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. All you really need are variables, conditionals and loops
  35. Essential ingredients HTTP handling URL dispatching Templating Documentation Database access (optional) ... no wonder there are so many frameworks!
  36. Extras
  37. Forms are boring
  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. Model validation rules + the Manipulator API do all of this for you
  40. django.contrib.admin does even more
  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. Smarter templating
  43. Common headers and footers?
  44. Template inheritance
  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. home.html {% extends “base.html” %} {% block title %}Homepage{% endblock %} {% block main %} Main page contents goes here. {% endblock %}
  47. combined <html> <head> <title> Homepage </title> </head> <body> Main page contents goes here. <div id=”footer”> (c) 2006 <div> </body> </html>
  48. Custom template tags
  49. {{ page.content|textile }}
  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. 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. i18n and l10n
  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. Authentication and authorisation
  55. Community
  56. ?
  57. It’s a matter of taste
  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. URL dispatching Object traversal or explicit configuration? Reversible URLs? Parameter extraction Trailing slashes?
  60. Database handling To ORM or not to ORM? Pluralisation? Handling joins Lookup syntax When should you fall back on raw SQL?
  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. Where’s the line? Authentication and authorisation? Automated admin / forms? i18n and l10n? JavaScript and Ajax?
  63. Getting involved
  64. Summer of Code 2006
  65. www.djangoproject.com
  66. Extra slides
  67. Comparisons
  68. $_GET, $_POST, HTTP $_REQUEST etc URL dispatch Filesystem Database handling mysql_* functions Templating <?php ... ?>
  69. HTTP CherryPy Object path URL dispatch traversal Database handling SQLObject Kid (XML), Templating common templating API
  70. HTTP ActionController? Object traversal, URL dispatch Routes Database handling ActiveRecord Templating ERb, Builder, RJS

×