python pymongoの例

969 ワード

公式ドキュメントはちょっと国语が简単なようです
save
col = mdb[mdb_config_col].find_one({})
if col is not None:
    id = col['_id']
    city_key['_id'] = id
    mdb[mdb_config_col].save(city_key)
else:


auth
# connect to mongo
mongo_db = MongoClient(mdb_host, mdb_port)
mdb = mongo_db[mdb_db] 
if mdb_user:
    mdb.authenticate(mdb_user, mdb_pwd)

pymongoの単一モード
from common import config
from pymongo import MongoClient
class Mongo():
    __instance = None

    def __init__(self):
        app_config = config.DevelopmentConfig()
        mdb_url = app_config.MDB_URL
        self.mdb_client = MongoClient(mdb_url)
        self.mdb = self.mdb_client[app_config.MDB]
        print 'mongo init....'

    @staticmethod
    def getInstance():
        if Mongo.__instance is None:
            Mongo.__instance = Mongo()
        return Mongo.__instance

呼び出し時に静的メソッドgetInstance()で取得