WSGI - Why does it cache the output for : os.popen("date").read() in multi threads and picks one randomly?
Question: I woke up and refreshed my wsgi script via web.  
within this wsgi script there is this python code.

    
    
    import os
    ooo = os.popen("date").read()
    

the system date was incorrect. so i refreshed the wsgi script.

the system time was now showing something that was BEFORE the system time i
saw earlier.

the more i refreshed the web browser.. the more i noticed the output is rather
random.

the system time was as if..

either python or wsgi was caching it 10 times in 10 different threads and then
displaying one randomly from those 10 cached threads.

based on information.. it turns out python is not doing the caching and that
WSGI might be responsible for this caching.

well... my understanding was WSGI was simply permitting python to work via
web.. i had no idea it was doing things as well such as threading and caching.

i even see suggestions that WSGI is loaded once and thus it can only execute
it once.

does this mean i have to reload the WSGI script for every time i want a non-
cached result ?

so basically might as well restart the whole apache for everytime i execute a
wsgi script on my web site ?

i suppose this means i would be restarting apache 1 million times daily if my
web site received that many hits per day ?

how can i tell WSGI to not cache the output for

    
    
    os.popen("date").read()
    

?


Answer: The 'caching' happens because the WSGI server/container only loads the
application once. After that, for each request it calls the WSGI function.
That means that any global (module level) variables will only be initialized
once.

Take this simple example:

    
    
    #!/usr/bin/python2
    import time
    
    startup_time = time.ctime()
    
    def application(environ, start_response):
        current_time = time.ctime()
        start_response('200 OK', [('Content-Type', 'text/plain')])
        return [startup_time, '\n', current_time]
    
    if __name__ == '__main__':
        from wsgiref import simple_server
        srv = simple_server.make_server('localhost', 8080, application)
        srv.serve_forever()
    

if you'll run this, you'll see that the first time stays constant, the second
doesn't. The same is true if you run this example using a different WSGI
server (like apache/mod_wsgi), only that usually multiple instances of the
application are launced and used to serve different requests. That explains
why you see different values.

So the solution is simple: everything that should be dynamic must be generated
within the call to the wsgi function, don't use globals.

