3
votes

I am building a wsgi application. The production environment is Apache mod_wsgi and configured appropriately. For development, I use wsgiref.simple_server to serve the wsgi app locally. However, I would like my dev server to serve static content also with minimal overhead. For purposes of answering the question, assume I want to serve static file "/favicon.ico".

I have come across the package "static": http://lukearno.com/projects/static/ but found the documentation a bit lacking, and haven't been able to configure it to serve both static content and my application.

Here is a sample wsgi application.

from cgi import parse_qs

def application(environ, start_response):
    qs = parse_qs(environ['QUERY_STRING'])

    response_body, content_type = ('Hello World', ('Content-type', 'text/plain'))

    content_length = 0
    for s in response_body:
        content_length += len(s)

    status = '200 OK'
    response_headers = [content_type,
                        ('Content-Length', str(content_length))]
    start_response(status, response_headers)

    return response_body



if __name__ == '__main__':
    from wsgiref.simple_server import make_server
    # Instantiate the WSGI web server.
    httpd = make_server('192.168.1.1', # The host name.
                        8080, # A port number where to wait for the request.
                        application # Our application object name, in this case a function.
                        )
    httpd.serve_forever()

Note: This may be a duplicate of unanswered question Serving static content with python wsgiref? from December. I wanted to add more than just a comment and did not want to dig up a dead thread.

1
Your response_body will end up being a string in this example and so you are iterating over that string 1 character at a time to calculate the length. Very inefficient. Go read python.org/dev/peps/pep-0333/… - Graham Dumpleton
I wasn't shooting for efficiency when I wrote an example "Hello World" program. "Go read ___ " isn't a pleasant thing to say. - bkanuka
You are ignoring that newbies will come to this site looking for code which they can cut and paste and use. If the issue wasn't pointed out then someone is bound to go use your code and so end up with something that is sub optimal or wrong. Also, if you had gotten past your sensitives and had gone and read the actual section of that document I pointed at, you would see it provides an example of the correct way of returning a file from a WSGI application. - Graham Dumpleton

1 Answers

2
votes

Let me propose the werkzeug package. It comes with a SharedDataMiddleware that solves precisely this task.