From 3591c9ed0700fa1d703fefc19593e3b59c51c9e9 Mon Sep 17 00:00:00 2001 From: Ryan Petrello Date: Mon, 2 Feb 2015 08:53:27 -0500 Subject: Document how to serve static files (with an iterable, not in-memory). Fixes bug 1221342 Change-Id: Icfad6a262ed211a73291eaead568248f67cfbfc9 --- docs/source/routing.rst | 54 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) 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 --------------------- -- cgit v1.2.1