How to initialize global variables in TurboGears 2

2019-09-05 14:31发布

问题:

I need a global variable that I can call from the templates.

I edited app_globals.py in lib directory to declare PATH_TO_IMAGES like this

class Globals(object):
    """Container for objects available throughout the life of the application.

    One instance of Globals is created during application initialization and
    is available during requests via the 'app_globals' variable.

    """

    PATH_TO_IMAGES = ""

    def __init__(self):
        """Do nothing, by default."""
        pass

Now I can call from any template the image path like this

<img src="${g.PATH_TO_IMAGES}/${p.image}" />

The image path is stored inside a settings table on the app's database, but I can't initialize it from Globals declaration, i get this error:

sqlalchemy.exc.UnboundExecutionError: Could not locate a bind configured on mapper Mapper|Settings|settings, SQL expression or this Session

My guess is that database binding happens after Globals is initialized. So my questions is, which is the best place to initialize a global variable in TurboGears 2 and which is the best practice to that.

回答1:

Just use a cached property:

class Globals(object):
    """Container for objects available throughout the life of the application.

    One instance of Globals is created during application initialization and
    is available during requests via the 'app_globals' variable.

    """

    @property
    def PATH_TO_IMAGES(self):
        try:
            return self._path_to_images
        except AttributeError:
            self._path_to_images = db_session.query(XXX)  # Fill in your query here
            return self._path_to_images

PS : your question is a generic Python question really. I suggest you read the official Python docs before posting other similar questions.



回答2:

You probably need to create your own database connection to get this data from the database.

In SQLAlchemy terms, you'll want to create your own engine, session, etc. Just make sure to clean up after you're done.

I would probably do this in app_cfg.py using on_startup to get it into the config, and then stick it in the Globals object later on if you still need to.



回答3:

You may set PATH_TO_IMAGES to it's definite value once the models are initialized. The sooner being at the end of the 'init_model' function declared in model/init.py.