在python中连接MongoDB集群(MongoDB Clus

作者: jiaxiaolei | 来源:发表于2017-08-10 17:43 被阅读926次

    建立了一个mongo集群,有3个节点,分别为:
    mongo-1
    mongo-2
    mongo-3

    mongo集群没有提供类似mysql集群和redis集群中的虚拟IP。在使用的时候需要客户端连接时指定mongo集群的所有节点。

    python连接MongoDB的驱动为pymongo, 基于pymongo 有封装的mongoengine,以及基于mongoengine 的 flask_mongoengie.

    具体写法如下:

    pymongo

    #!/usr/bin/env python
    # coding=utf-8
    
    from pymongo import MongoClient
    
    # single mongo
    #c = MongoClient(host="mongo-1", port=28010) # okay
    #c = MongoClient('mongodb://admin:123456@mongo-1:28010,mongo-2:28010/?replicaSet=rsname')
    
    # mongo cluster
    c = MongoClient('mongodb://admin:123456@mongo-1:28010,mongo-2:28010,mongo-3:28010')
    #c = MongoClient('mongodb://admin:123456@mongo-1:28010,mongo-2:28010,mongo-3:28010/?readPreference=secondary')
    #c = MongoClient('mongodb://admin:123456@mongo-3:28010/?readPreference=secondary')
    
    print c.nodes
    print c.database_names()
    

    mongoengine

    from mongoengine import connect
    from mongoengine import Document
    from mongoengine import StringField
    
    connect('mpc', host='mongodb://mpc:mpc@mongo-1:28010,mongo-2:28010,mongo-3:28010/mpc')
    
    class User(Document):
        title = StringField(required=True, max_length=200)
    
    print User.objects.count()
    

    flask_mongoengine

    from flask_mongoengine import MongoEngine
    
    from flask import Flask
    
    
    app = Flask(__name__)
    
    #app.config.from_pyfile('the-config.cfg')
    
    #app.config['MONGODB_SETTINGS'] = {
    #        'db': 'mpc',
    #        'username': 'mpc',
    #        'password': 'mpc',
    #        'host': 'mongo-2',
    #        'port': 28010 
    #        }
    
    """ 
    # NOTE: connect_settings invalid.
    app.config['MONGODB_SETTINGS'] = [
            {
            'db': 'mpc',
            'username': 'mpc',
            'password': 'mpc',
            'host': 'mongo-1',
            'port': 28010 
            },
            {
            'db': 'mpc',
            'username': 'mpc',
            'password': 'mpc',
            'host': 'mongo-2',
            'port': 28010 
            }
            ]
    """
    
    app.config['MONGODB_SETTINGS'] = {
            'host': 'mongodb://mpc:mpc@mongo-1:28010,mongo-2:28010,mongo-3:2801/mpc',
            }
    
    
    db = MongoEngine(app)
    
    class User(db.Document):
        email = db.StringField(required=True)
        first_name = db.StringField(max_length=50)
        last_name = db.StringField(max_length=50)
    
    print 'filter', User.objects.filter()
    

    扩展阅读:

    python_mongo
    https://github.com/jiaxiaolei/projects/tree/master/python_mongo
    简介:
    上面示例代码可以在github上看到。

    相关文章

      网友评论

        本文标题:在python中连接MongoDB集群(MongoDB Clus

        本文链接:https://www.haomeiwen.com/subject/iqahrxtx.html