简体   繁体   English

如何在turbogears2的app_globals.py中使用数据库?

[英]How to use database in app_globals.py in turbogears2?

Possibly related topic, but from which I could not solve the problem: How to initialize global variables in TurboGears 2 with values from a table 可能是相关主题,但我无法从中解决问题: 如何使用表中的值初始化TurboGears 2中的全局变量

The issue is that I'm trying to read some config parameters from the database when initializing some of the global variables in app_globals.py in Turbogears. 问题是,在Turbogears中初始化app_globals.py中的某些全局变量时,我试图从数据库中读取一些配置参数。

When attempting to access the database however, I receive an exception: 但是,当尝试访问数据库时,出现异常:

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

Just as the exception states this is probably due to the db not being bound yet (global parameters are set up first). 正如异常指出的那样,这可能是由于尚未绑定数据库(首先设置了全局参数)引起的。 From the other topic I was pointed in the direction of going to app_cfg.py and using "on_startup" to bind the database before initializing the global variables, but it's not working for me. 从另一个主题出发,我的方向是转到app_cfg.py,并在初始化全局变量之前使用“ on_startup”绑定数据库,但这对我不起作用。 Either I'm not doing it right or this is not the solution to the problem. 我不是做对了,还是这不是解决问题的方法。 For instance, I tried writing: 例如,我尝试编写:

def on_startup():
    print "Foo bar!!!"

base_config.register_hook('startup', on_startup)

But the print statement is never executed (the crash occurs before). 但是print语句从不执行(崩溃发生在之前)。

Does anyone have any pointers on where to go from here? 有人对从这里到哪里有任何指示吗?

Thanks in advance. 提前致谢。

You can use the after_config hook to call a setup method in your app_globals which gets to the database and retrieves the data it needs to set itself up. 您可以使用after_config挂钩app_globals中调用一个设置方法,该方法将进入数据库并检索其自身设置所需的数据。

after_config hooks is actually called after the full turbogears application got configured and so you will have both app_globals and the database built and configured. 在配置了完整的turbogears应用程序之后,实际上会调用after_config挂钩,因此您将同时构建和配置了app_globals以及数据库。 You can access app_globals from the hook using config['tg.app_globals'] or config['pylons.app_globals'] depending on which version of TG you are using. 您可以使用config['tg.app_globals']config['pylons.app_globals']从钩子访问app_globals,具体取决于所使用的TG版本。

Pay attention that the after_config hook has to return the turbogears application itself, so just return the parameter you get. 注意after_config钩子必须返回turbogears应用程序本身,因此只需返回您获得的参数即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM