python连接mongodb

方式一:

#!/usr/bin/python
# coding:utf-8

from __future__ import unicode_literals
from pymongo import MongoClient
from django.conf import settings

__author__ = 'klx'


class MongodbModel:
    """
    mongodb单例模式
    """
    __con = None

    @classmethod
    def conn(cls):
        """
        这里第一个参数是cls, 表示调用当前的类名
        :return:
        """
        if settings.DEBUG:
            cls.client = MongoClient('mongodb://120.77.12.144:27017/')
            cls.client.admin.authenticate("root", "root")
            cls.db = cls.client['nahuomallv3_dev']
        else:
            cls.client = MongoClient('mongodb://120.77.12.144:27017/')
            cls.client.admin.authenticate("root", "root")
            cls.db = cls.client['nahuomallv3_prod']
        # 进行单例判断
        if cls.__con:
            return cls.__con
        else:
            cls.__con = MongodbModel()
            return cls.__con

 

 方式二:

 

from pymongo import MongoClient
class MongodbModel:
    def __init__(self):
        """
        初始化MongoClient
        """
        self.client = MongoClient()
        # 指定端口和地址
        # self.client = MongoClient('127.0.0.1', 27017)
 
        if settings.DEBUG:
            # 使用URI
            self.client = MongoClient('mongodb://120.77.12.144:27017/')
            self.client.admin.authenticate("root", "root")
            self.db = self.client['nahuomallv3_dev']
        else:
            # 使用URI
            self.client = MongoClient('mongodb://120.77.12.144:27017/')
            self.client.admin.authenticate("root", "root")
            self.db = self.client['nahuomallv3_prod']
 
    def __del__(self):     
        """
        删除对象(del mgngomodel_obj) 
        """
        self.client.close()     

 

posted @ 2018-10-24 17:22  詹姆溪  阅读(2159)  评论(0编辑  收藏  举报