How to initialize global variables in TurboGears 2 with values from a table

流过昼夜 提交于 2019-12-24 21:07:24

问题


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.



来源:https://stackoverflow.com/questions/1521264/how-to-initialize-global-variables-in-turbogears-2-with-values-from-a-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!