views:

28

answers:

1

I've got a webapp running on CherryPy that needs to access the CherryPy config files before a user creates a request. The docs say to use:

host = cherrypy.request.app.config['database']['host']

But that won't work outside of a user request. You can also use the application object when you start the app like so:

...
application = cherrypy.tree.mount(root, '/', app_conf)
host = application.config['database']['host']
...

But I can see no way of accessing 'application' from other classes outside of a user request.

I ask because our app looks at several databases and we set them up when the app starts rather than on user request. I have a feeling this would be useful in other places too; so is there any way to store a reference to 'application' somewhere or access it through the CherryPy API?

A: 

is there any way to store a reference to 'application' somewhere...

Just use normal Python. For a package called 'myapp':

# __init__.py
...
application = cherrypy.tree.mount(root, '/', app_conf)
...

# notarequest.py
import myapp
host = myapp.application.config['database']['host']

However, I would recommend using config to set up your database objects, and then inspect those database objects instead of inspecting the config.

fumanchu
I see what you mean but our `app.py` imports `notarequest.py` so I can't import `app.py` from there without import errors. I also see what you mean about the config but it's quite complex so we moved it to a different module to avoid clutter in our main app module. I just used a third module as a temporary hack as per: http://effbot.org/pyfaq/how-do-i-share-global-variables-across-modules.htm
OrganicPanda