Search code examples
pythonapachemod-wsgiweb.py

Apache/ mod wsgi if __name__ == '__main__' equivalent


To use a leveldb (python database) for my I need the database to be loaded only when I start the server and not each time a user uses my website.

Previously I used web.py and the if __name__ == '__main__' statement to make that happen. Once I switched to Apache the __name__ variable is always modwsgi_.....

Can someone provide me with an alternative that would work with Apache and modwsgi please?


Solution

  • The value of __name__ would be of the form _mod_wsgi_?????, so use:

    if __name__.startswith('_mod_wsgi_'):
        ...
    

    Better still, use a WSGI script file distinct from everything else which is only used by mod_wsgi. Thus create an app.wsgi file which then imports your application object from elsewhere. You then don't need a check and can do the loading at global scope.

    Just make sure you are using daemon mode in either case, as in embedded mode the WSGI script file could technically be loaded more than once in the life of the process if its modification time is changed. In daemon mode this doesn't happen as changing the WSGI script file will cause the whole process to be shutdown and reloaded instead.

    BTW, how to know if mod_wsgi is running is documented in: