繼(和靈感)josephmosby的回答,我使用類似以下內容:
# project/settings
MONGO_DB = {
'default': {
'HOST': 'localhost',
'PORT': 27017
},
...
}
# project/__init__.py
gMongoClient = {}
# project/utils/mongo_tool.py
from project import gMongoClient
from project.settings import MONGO_DB
import pymongo
def get_mongo_db(dbname="default"):
if dbname in gMongoClient:
return gMongoClient[dbname]
if dbname in MONGO_DB:
with MONGO_DB[dbname] as config:
gMongoClient = pymongo.MongoClient(config["HOST"],
config["PORT"])
else:
gMongoClient[dbname] = None
return gMongoClient[dbname]
# .../view.py
from utils import mongo_tool
...
db = mongo_tool.get_mongo_db()
results = db["collection"].find(...)
這可以b e更漂亮,例如查看是否在特定連接的設置中指定了用戶名和密碼等,但以上內容捕捉到了這個想法的實質。
我會將它保存在Django應用程序中的'__init __。py'中。這樣它就被實例化了一次。儘管我對你瞭解正確的程序同樣感興趣:) – shaktimaan 2014-08-28 18:56:52