Functional Python Programming

(Wang) #1
Chapter 15

We can define a WSGI application that provides static content as follows:


def static_app(environ, start_response):


try:


with open(CONTENT_HOME+environ['PATH_INFO']) as static:


content= static.read().encode(""utf-8"")


headers= [


(""Content-Type"",'text/plain; charset=""utf-8""'),
(""Content-Length"",str(len(content))),
]


start_response('200 OK', headers)


return [content]


except IsADirectoryError as e:


return index_app(environ, start_response)


except FileNotFoundError as e:


start_response('404 NOT FOUND', [])


return([repr(e).encode(""utf-8"")])


In this case, we simply tried to open the requested path as a text file. There are
two common reasons why we can't open a given file, both of which are handled
as exceptions:



  • If the file is a directory, we'll use a different application to present
    directory contents

  • If the file is simply not found, we'll return an HTTP 404 NOT FOUND
    response


Any other exceptions raised by this WSGI application will not be caught.
The application that invoked this should be designed with some generic error
response capability. If it doesn't handle the exceptions, a generic WSGI failure
response will be used.


Our processing involves a strict ordering of operations. We must read
the entire file so that we can create a proper HTTP Content-Length
header.

Further, we must provide the content as bytes. This means that the Python
strings must be properly encoded and we must provide the encoding information
to the user agent. Even the error message, repr(e), is properly encoded before
being downloaded.

Free download pdf