diff options
author | Jenkins <jenkins@review.openstack.org> | 2015-02-04 19:28:17 +0000 |
---|---|---|
committer | Gerrit Code Review <review@openstack.org> | 2015-02-04 19:28:17 +0000 |
commit | ff88de0f8c4579d29f8fe9fe2bde3ab48a763288 (patch) | |
tree | 8550f95ddccfe66496ad7de611bc7779b43a83b7 | |
parent | ec8b95e432975a2f6b334709a820f8ae9526367c (diff) | |
parent | 3591c9ed0700fa1d703fefc19593e3b59c51c9e9 (diff) | |
download | pecan-ff88de0f8c4579d29f8fe9fe2bde3ab48a763288.tar.gz |
Merge "Document how to serve static files (with an iterable, not in-memory)."
-rw-r--r-- | docs/source/routing.rst | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/docs/source/routing.rst b/docs/source/routing.rst index 80deca5..a2bf378 100644 --- a/docs/source/routing.rst +++ b/docs/source/routing.rst @@ -427,6 +427,60 @@ The same effect can be achieved with HTTP ``POST`` body variables: $ curl -X POST "http://localhost:8080/" -H "Content-Type: application/x-www-form-urlencoded" -d "arg=foo" foo +Static File Serving +------------------- + +Because Pecan gives you direct access to the underlying +:class:`~webob.request.Request`, serving a static file download is as simple as +setting the WSGI ``app_iter`` and specifying the content type:: + + import os + from random import choice + + from webob.static import FileIter + + from pecan import expose, response + + + class RootController(object): + + @expose(content_type='image/gif') + def gifs(self): + filepath = choice(( + "/path/to/funny/gifs/catdance.gif", + "/path/to/funny/gifs/babydance.gif", + "/path/to/funny/gifs/putindance.gif" + )) + f = open(filepath, 'rb') + response.app_iter = FileIter(f) + response.headers[ + 'Content-Disposition' + ] = 'attachment; filename="%s"' % os.path.basename(f.name) + +If you don't know the content type ahead of time (for example, if you're +retrieving files and their content types from a data store), you can specify +it via ``response.headers`` rather than in the :func:`~pecan.decorators.expose` +decorator:: + + import os + from mimetypes import guess_type + + from webob.static import FileIter + + from pecan import expose, response + + + class RootController(object): + + @expose() + def download(self): + f = open('/path/to/some/file', 'rb') + response.app_iter = FileIter(f) + response.headers['Content-Type'] = guess_type(f.name) + response.headers[ + 'Content-Disposition' + ] = 'attachment; filename="%s"' % os.path.basename(f.name) + Handling File Uploads --------------------- |