toastdriven / multiresponse

A Python class for Django that allows a request to provide content-type aware responses.

This URL has Read+Write access

multiresponse / README.txt
2209590d » toastdriven 2008-12-01 Vasted revamped over 50% of... 1 MultiResponse
2 =============
3
4 A Python class for Django to provide mime type aware responses. This allows a client to receive different responses based on the HTTP "Accept" header they send. This is used in place of ``render_to_response`` or a manual ``HttpResponse``.
5
6
7 Requirements
8 ------------
9
10 * Python 2.5+ (lower versions may work but are untested.)
11 * Django 1.0+ (again, lower versions may work but are untested.)
12 * mimeparse 0.1.2+ - http://code.google.com/p/mimeparse/
13
14
15 Sample Usage:
16 -------------
17
18 from django.conf import settings
19 from django.shortcuts import render_to_response
20 from multiresponse import MultiResponse
21
22 def index(request, extension):
23 sample_people = [
24 {'name': 'Daniel', 'age': 26},
25 {'name': 'John', 'age': 26},
26 {'name': 'Jane', 'age': 20},
27 {'name': 'Bob', 'age': 35},
28 ]
29
30 mr = MultiResponse(request)
31 mr.register('html', 'index.html')
32 mr.register('xml', 'people.xml')
33 mr.register('json', 'people.json')
34 mr.register('txt', 'people.txt')
35 return mr.render({
36 'people': sample_people,
37 })
38
39
40 Output
41 ------
42
43 A HTTP GET to http://localhost:8000/ with a web browser would yield something like:
44
45 HTTP/1.0 200 OK
46 Date: Tue, 02 Dec 2008 05:39:53 GMT
47 Server: WSGIServer/0.1 Python/2.5.1
48 Content-Type: text/html; charset=utf-8
49
50 <html>
51 <head>
52 <title>People</title>
53 </head>
54
55 <body>
56 <h1>People</h1>
57
58 <ul>
59
60 <li>Daniel</li>
61
62 <li>John</li>
63
64 <li>Jane</li>
65
66 <li>Bob</li>
67
68 </ul>
69 </body>
70 </html>
71
72 However, a HTTP GET to http://localhost:8000/ via "curl -i -H 'Accept: application/xml' http://localhost:8000/" would yield:
73
74 HTTP/1.0 200 OK
75 Date: Tue, 02 Dec 2008 05:42:14 GMT
76 Server: WSGIServer/0.1 Python/2.5.1
77 Content-Type: application/xml; charset=utf-8
78
79 <?xml version="1.0"?>
80 <people>
81
82 <person>
83 <name>Daniel</name>
84 <age>26</age>
85 </person>
86
87 <person>
88 <name>John</name>
89 <age>26</age>
90 </person>
91
92 <person>
93 <name>Jane</name>
94 <age>20</age>
95 </person>
96
97 <person>
98 <name>Bob</name>
99 <age>35</age>
100 </person>
101
102 </people>
103
104 And a HTTP GET to http://localhost:8000/ via Javascript might look like:
105
106 HTTP/1.0 200 OK
107 Date: Tue, 02 Dec 2008 05:42:47 GMT
108 Server: WSGIServer/0.1 Python/2.5.1
109 Content-Type: application/json; charset=utf-8
110
111 {
112 'people': [
113
114 {'name': 'Daniel', 'age': '26'},
115
116 {'name': 'John', 'age': '26'},
117
118 {'name': 'Jane', 'age': '20'},
119
120 {'name': 'Bob', 'age': '35'},
121
122 ]
123 }