我想让一个数据库对象在多个 python 模块中可用。
对于一个相关的例子,我创建了 globl.py:
DOCS_ROOT="c:\docs" ## as an example
SOLR_BASE="http://localhost:8636/solr/"
任何其他需要它的模块都可以做一个
from globl import DOCS_ROOT
现在抛开这个例子,我想对数据库连接对象做同样的事情,在多个模块之间共享它们。
import MySQLdb
conn = MySQLdb.connect (host="localhost"...)
cursor = conn.cursor()
我在解释器上试过这个:
from globl import cursor
它似乎有效。但我怀疑这会导致每次导入时都执行相同的模块。那么这是正确的方法吗?
最佳答案
即使导入没有多次运行代码,这也绝对不是正确的方式。
您应该将获取连接或游标的过程隐藏在函数后面。然后,您可以使用 Singleton 来实现此功能。或 Object Pool设计模式。
所以它会是这样的:
db.py:
_connection = None
def get_connection():
global _connection
if not _connection:
_connection = MySQLdb.connect(host="localhost"...)
return _connection
# List of stuff accessible to importers of this module. Just in case
__all__ = [ 'getConnection' ]
## Edit: actually you can still refer to db._connection
## if you know that's the name of the variable.
## It's just left out from enumeration if you inspect the module
someothermodule.py:
import db
conn = db.get_connection() # This will always return the same object
顺便说一下,根据你在做什么,分享可能不是一个好主意 您的连接对象,而不是每次需要时都创建一个新连接对象。
但是,这就是为什么您要编写一个 get_connection()
方法,以便在您的其余代码中从这些问题中抽象出来。
关于python - 在许多 python 模块中建立数据库连接的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6829675/