How to use the pymongo.Connection function in pymongo

To help you get started, we’ve selected a few pymongo examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mongodb-labs / edda / test / View on Github external
def db_setup():
    """Set up a database for use by tests"""
    c = Connection()
    db = c["test"]
    servers = db["zoo.servers"]
    return servers
github mzupan / nagios-plugin-mongodb / View on Github external
con_args['ssl_ca_certs'] = ssl_ca_cert_file
        if ssl_cert:
            con_args['ssl_certfile'] = ssl_cert

        # ssl connection for pymongo > 2.3
        if pymongo.version >= "2.3":
            if replica is None:
                con = pymongo.MongoClient(host, port, **con_args)
                con = pymongo.MongoClient(host, port, read_preference=pymongo.ReadPreference.SECONDARY, replicaSet=replica, **con_args)
            if replica is None:
                con = pymongo.Connection(host, port, slave_okay=True, network_timeout=10)
                con = pymongo.Connection(host, port, slave_okay=True, network_timeout=10)

        # we must authenticate the connection, otherwise we won't be able to perform certain operations
        if ssl_cert and ssl_ca_cert_file and user and auth_mechanism == 'SCRAM-SHA-256':
            con.the_database.authenticate(user, mechanism='SCRAM-SHA-256')
        elif ssl_cert and ssl_ca_cert_file and user and auth_mechanism == 'SCRAM-SHA-1':
            con.the_database.authenticate(user, mechanism='SCRAM-SHA-1')
        elif ssl_cert and ssl_ca_cert_file and user and auth_mechanism == 'MONGODB-X509':
            con.the_database.authenticate(user, mechanism='MONGODB-X509')

          result = con.admin.command("ismaster")
        except ConnectionFailure:
          print("CRITICAL - Connection to Mongo server on %s:%s has failed" % (host, port) )

        if 'arbiterOnly' in result and result['arbiterOnly'] == True:
github rjurney / Agile_Data_Code / ch8 / web / View on Github external
from flask import Flask, render_template, request
import pymongo
import json, pyelasticsearch
import re
import config

# Setup Flask
app = Flask(__name__)

# Setup Mongo
conn = pymongo.Connection() # defaults to localhost
db = conn.agile_data
emails = db['emails']
addresses_per_email = db['addresses_per_email']
emails_per_address = db['emails_per_address']
sent_distributions = db['sent_distributions']

# Setup ElasticSearch
elastic = pyelasticsearch.ElasticSearch(config.ELASTIC_URL)

# Controller: Fetch an email and display it
def email(message_id):
  email = emails.find_one({'message_id': message_id})
  address_hash = addresses_per_email.find_one({'message_id': message_id})
  sent_dist_records = sent_distributions.find_one({'address': email['from']['address']})
  print sent_dist_records
github google / grr / lib / data_stores / View on Github external
def __init__(self):
    logging.warning("Starting MongoDataStore. This Datastore is DEPRECATED!")
    logging.warning("This datastore will be removed!!!")
    logging.warning("Recommended alternatives include MySQLAdvancedDataStore")
    logging.warning("and HTTPDataStore.")

    # Support various versions on the pymongo connection object.
      connector = pymongo.MongoClient
    except AttributeError:
      connector = pymongo.Connection

    if config_lib.CONFIG["Mongo.server"]:
      mongo_client = connector(

      mongo_client = connector()

    # For now use a single "data" collection
    self.db_handle = mongo_client[config_lib.CONFIG["Mongo.db_name"]]

    # We have two collections - the latest collection maintains the latest data
    # and the versioned collection maintains versioned data.
    self.latest_collection = self.db_handle.latest
    self.versioned_collection = self.db_handle.versioned
github EMSL-MSC / NWPerf / lib / nwperf / View on Github external
def fork(self):
		if self.mongouri:
			self.db = pymongo.Connection(self.mongouri)
			self.db = pymongo.Connection().nwperf
github qcl / master-research / vectorSpaceModel / View on Github external
def mapper(jobid,filename,inputPath,inputPtnPath,model,table):

    # Read article
    contentJson = projizz.jsonRead( os.path.join(inputPath,filename) )
    # Read ptn
    contentPtnJson = projizz.jsonRead( os.path.join(inputPtnPath,filename) )

    print "Worker %d : Read %s into filter" % (jobid,filename)
    ### Connect to database
    connect = pymongo.Connection()
    db = connect.projizz
    collection = db.result.yago.answer
    queries = map(lambda x: x[:-4], contentPtnJson)
    itr = collection.find({"revid":{"$in":queries}})
    print "worker %d query=%d, result=%d" % (jobid,len(queries),itr.count())

    count = 0

    supportInstanceByFile = {}

    for ans in itr:
        count += 1

        key = "%s.txt" % (ans["revid"])
        relation = ans["observed"]
github Lothiraldan / saltpad / saltpad / _returners / View on Github external
def _get_conn():
    Return a mongodb connection object
    conn = pymongo.Connection(
    mdb = conn[__salt__['config.option']('mongo.db')]

    user = __salt__['config.option']('mongo.user')
    password = __salt__['config.option']('mongo.password')

    if user and password:
        mdb.authenticate(user, password)
    return conn, mdb
github mcfunley / oplogutils / oplogutils / View on Github external
def connection(self):
        return Connection(, self.opts.port)
github kaazoo / DrQueueIPython / DrQueue / View on Github external
def store_db(pool):
        import pymongo
        """store pool information in MongoDB"""
        connection = pymongo.Connection(os.getenv('DRQUEUE_MONGODB'))
        db = connection['ipythondb']
        pools = db['drqueue_pools']
        pool_id = pools.insert(pool)
        pool['_id'] = str(pool['_id'])
        return pool_id
github kbase / assembly / lib / assembly / View on Github external
def remove_doc(self, collection, key, value):
        connection = pymongo.Connection(, self.port)
        database = connection[self.db]
        col = database[collection]