[Web-SIG] Request and Response objects

Stuart Bishop stuart at stuartbishop.net
Tue Nov 4 20:01:54 EST 2003


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On 30/10/2003, at 3:31 PM, David Fraser wrote:

> A lot of the arguments for the dual object model are about what you 
> can do with a separate object.
> But these seem to me to miss the point .... you can create your own 
> "response"-type class that holds the *value* of a response, and as 
> many instances of it per request as you want to. But the actual Web 
> API response object is for *writing* the response back to the client. 
> You can only write one response back per request, so it makes sense 
> for them to be the same object.

The "response"-type class is the interesting bit - the API for setting
status codes, headers, cookies etc. And you do want multiples, of
which only one is sent to the client. In particular, if you catch an
exception and are preparing an error message you will want a clean
response to work with rather than, for example, accidently sending
your error message with the wrong content-type. The alternative would
be a reset() method on the response buffer, although this isn't as
flexible.

def handler(request):
	try:
		response = Reponse(request)
		filename = response.request.getFirst('filename')
		response.headers['Content-Type'] = 'image/jpeg'
		response.cookies['latest'] = filename
		response.write(open(filename,'rb').read()) # A filelike object
	except IOError:
		response = Response(request)
		response.status = 404
		print >> response, 'File not found'
	response.close() # No more data - compute content-length header
	response.send() # Send to client.

In this example, response is a file like object that buffers the 
document's
content and is explicitly sent to the client. The use of a close method
before the send would allow you to use response.send(somedata) or
combinations of response.write(somedata) and response.send() to stream
unbuffered content to the client. As others have suggested, the send 
method
could just as easily be a method of the request object (such as the
case in Zope), although I personally prefer response.send() rather than
request.send(response) or 'request.response = response; request.send()'

- -- 
Stuart Bishop <stuart at stuartbishop.net> ☞ http://www.stuartbishop.net/

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.3 (Darwin)

iD8DBQE/qEwHAfqZj7rGN0oRAgYYAKCV2Qpbm1M28pdgKWBTBPY+scYc5wCeLkiE
cWXlE+pjB+RNHUFbleLkQpk=
=gzez
-----END PGP SIGNATURE-----




More information about the Web-SIG mailing list