How to initialize global variables in TurboGears 2

2019-09-05 14:36发布

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.

3条回答
一夜七次
2楼-- · 2019-09-05 14:55

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.

查看更多
做个烂人
3楼-- · 2019-09-05 15:04

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.

查看更多
狗以群分
4楼-- · 2019-09-05 15:13

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.

查看更多
登录 后发表回答