使数据库连接可跨许多python模块使用的正确方法 [英] the proper method for making a DB connection available across many python modules
问题描述
我想在多个python模块中使一个数据库对象可用.
I want to make a single database object available across many python modules.
对于与相关的示例,我创建globl.py:
For a related example, I create globl.py:
DOCS_ROOT="c:\docs" ## as an example
SOLR_BASE="http://localhost:8636/solr/"
任何其他需要它的模块都可以做
Any other module which needs it can do a
from globl import DOCS_ROOT
现在除了这个示例之外,我想对数据库连接对象做相同的事情,在许多模块中共享它们.
Now this example aside, I want to do the same thing with database connection objects, share them across many modules.
import MySQLdb
conn = MySQLdb.connect (host="localhost"...)
cursor = conn.cursor()
我在翻译器上尝试过
from globl import cursor
,它似乎有效.但是我怀疑这会每次导入一个模块都会导致执行相同的模块.那么这是正确的方法吗?
and it seems to work. But I suspect that this will cause the same module to be executed each time one imports from it. So is this the proper way?
推荐答案
您猜错了.该代码将仅执行一次-后续导入仅通过sys.modules
引用该模块,而无需重新运行它.
You suspect wrongly. The code will only be executed once - subsequent imports just refer to the module via sys.modules
, and don't re-run it.
(请注意,只要您始终使用相同的路径来导入模块,就是这种情况-如果您在一个位置执行from globl import cursor
,而在另一个位置执行from my.fullyqualified.project.global import cursor
,则可能会发现代码重新执行.)
(Note that this is the case as long as you always use the same path to import the module - if you do from globl import cursor
in one place, and from my.fullyqualified.project.global import cursor
in another, you probably will find the code is re-executed.)
编辑以添加,这是处理全局对象的一种非常好的方法.
Edit to add as S.Lott says in the comment, this is a perfectly good way to handle a global object.
这篇关于使数据库连接可跨许多python模块使用的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!