Ejemplo n.º 1
0
    def test_connection(self):
        c = Connection(host, port)
        self.assertTrue(c.auto_start_request)
        self.assertEqual(None, c.max_pool_size)
        self.assertFalse(c.slave_okay)
        self.assertFalse(c.safe)
        self.assertEqual({}, c.get_lasterror_options())

        # Connection's writes are unacknowledged by default
        doc = {"_id": ObjectId()}
        coll = c.pymongo_test.write_concern_test
        coll.drop()
        coll.insert(doc)
        coll.insert(doc)

        c = Connection("mongodb://%s:%s/?safe=true" % (host, port))
        self.assertTrue(c.safe)

        # To preserve legacy Connection's behavior, max_size should be None.
        # Pool should handle this without error.
        self.assertEqual(None, c._MongoClient__pool.max_size)
        c.end_request()

        # Connection's network_timeout argument is translated into
        # socketTimeoutMS
        self.assertEqual(123, Connection(
            host, port, network_timeout=123)._MongoClient__net_timeout)

        for network_timeout in 'foo', 0, -1:
            self.assertRaises(
                ConfigurationError,
                Connection, host, port, network_timeout=network_timeout)
    def test_connection(self):
        c = Connection(host, port)
        self.assertTrue(c.auto_start_request)
        self.assertEqual(None, c.max_pool_size)
        self.assertFalse(c.slave_okay)
        self.assertFalse(c.safe)
        self.assertEqual({}, c.get_lasterror_options())

        # Connection's writes are unacknowledged by default
        doc = {"_id": ObjectId()}
        coll = c.pymongo_test.write_concern_test
        coll.drop()
        coll.insert(doc)
        coll.insert(doc)

        c = Connection("mongodb://%s:%s/?safe=true" % (host, port))
        self.assertTrue(c.safe)

        # To preserve legacy Connection's behavior, max_size should be None.
        # Pool should handle this without error.
        self.assertEqual(None, get_pool(c).max_size)
        c.end_request()

        # Connection's network_timeout argument is translated into
        # socketTimeoutMS
        self.assertEqual(123, Connection(
            host, port, network_timeout=123)._MongoClient__net_timeout)

        for network_timeout in 'foo', 0, -1:
            self.assertRaises(
                ConfigurationError,
                Connection, host, port, network_timeout=network_timeout)
    def test_copy_db(self):
        c = Connection(self.host, self.port)
        self.assertTrue(c.in_request())

        self.assertRaises(TypeError, c.copy_database, 4, "foo")
        self.assertRaises(TypeError, c.copy_database, "foo", 4)

        self.assertRaises(InvalidName, c.copy_database, "foo", "$foo")

        c.pymongo_test.test.drop()
        c.drop_database("pymongo_test1")
        c.drop_database("pymongo_test2")

        c.pymongo_test.test.insert({"foo": "bar"})

        # Due to SERVER-2329, databases may not disappear from a master in a
        # master-slave pair
        if not server_is_master_with_slave(c):
            self.assertFalse("pymongo_test1" in c.database_names())
            self.assertFalse("pymongo_test2" in c.database_names())

        c.copy_database("pymongo_test", "pymongo_test1")
        # copy_database() didn't accidentally end the request
        self.assertTrue(c.in_request())

        self.assertTrue("pymongo_test1" in c.database_names())
        self.assertEqual("bar", c.pymongo_test1.test.find_one()["foo"])

        c.end_request()
        self.assertFalse(c.in_request())
        c.copy_database("pymongo_test", "pymongo_test2", "%s:%d" % (self.host, self.port))
        # copy_database() didn't accidentally restart the request
        self.assertFalse(c.in_request())

        self.assertTrue("pymongo_test2" in c.database_names())
        self.assertEqual("bar", c.pymongo_test2.test.find_one()["foo"])

        if version.at_least(c, (1, 3, 3, 1)):
            c.drop_database("pymongo_test1")

            c.pymongo_test.add_user("mike", "password")

            self.assertRaises(
                OperationFailure, c.copy_database, "pymongo_test", "pymongo_test1", username="******", password="******"
            )
            if not server_is_master_with_slave(c):
                self.assertFalse("pymongo_test1" in c.database_names())

            self.assertRaises(
                OperationFailure, c.copy_database, "pymongo_test", "pymongo_test1", username="******", password="******"
            )

            if not server_is_master_with_slave(c):
                self.assertFalse("pymongo_test1" in c.database_names())

            if not is_mongos(c):
                # See SERVER-6427
                c.copy_database("pymongo_test", "pymongo_test1", username="******", password="******")
                self.assertTrue("pymongo_test1" in c.database_names())
                self.assertEqual("bar", c.pymongo_test1.test.find_one()["foo"])
Ejemplo n.º 4
0
    def test_end_request(self):
        self.skip()
        connection = Connection([self.left, self.right])
        db = connection.pymongo_test

        for _ in range(100):
            db.test.remove({})
            db.test.insert({})
            self.assertTrue(db.test.find_one())
            connection.end_request()
    def test_end_request(self):
        self.skip()
        connection = Connection([self.left, self.right])
        db = connection.pymongo_test

        for _ in range(100):
            db.test.remove({})
            db.test.insert({})
            self.assertTrue(db.test.find_one())
            connection.end_request()
Ejemplo n.º 6
0
    def test_copy_db(self):
        c = Connection(self.host, self.port)
        self.assertTrue(c.in_request())

        self.assertRaises(TypeError, c.copy_database, 4, "foo")
        self.assertRaises(TypeError, c.copy_database, "foo", 4)

        self.assertRaises(InvalidName, c.copy_database, "foo", "$foo")

        c.pymongo_test.test.drop()
        c.drop_database("pymongo_test1")
        c.drop_database("pymongo_test2")

        c.pymongo_test.test.insert({"foo": "bar"})

        # Due to SERVER-2329, databases may not disappear from a master in a
        # master-slave pair
        if not server_is_master_with_slave(c):
            self.assertFalse("pymongo_test1" in c.database_names())
            self.assertFalse("pymongo_test2" in c.database_names())

        c.copy_database("pymongo_test", "pymongo_test1")
        # copy_database() didn't accidentally end the request
        self.assertTrue(c.in_request())

        self.assertTrue("pymongo_test1" in c.database_names())
        self.assertEqual("bar", c.pymongo_test1.test.find_one()["foo"])

        c.end_request()
        c.copy_database("pymongo_test", "pymongo_test2",
                        "%s:%d" % (self.host, self.port))
        # copy_database() didn't accidentally restart the request
        self.assertFalse(c.in_request())

        self.assertTrue("pymongo_test2" in c.database_names())
        self.assertEqual("bar", c.pymongo_test2.test.find_one()["foo"])

        if version.at_least(c, (1, 3, 3, 1)):
            c.drop_database("pymongo_test1")

            c.pymongo_test.add_user("mike", "password")

            self.assertRaises(OperationFailure,
                              c.copy_database,
                              "pymongo_test",
                              "pymongo_test1",
                              username="******",
                              password="******")
            if not server_is_master_with_slave(c):
                self.assertFalse("pymongo_test1" in c.database_names())

            self.assertRaises(OperationFailure,
                              c.copy_database,
                              "pymongo_test",
                              "pymongo_test1",
                              username="******",
                              password="******")

            if not server_is_master_with_slave(c):
                self.assertFalse("pymongo_test1" in c.database_names())

            if not is_mongos(c):
                # See SERVER-6427
                c.copy_database("pymongo_test",
                                "pymongo_test1",
                                username="******",
                                password="******")
                self.assertTrue("pymongo_test1" in c.database_names())
                self.assertEqual("bar", c.pymongo_test1.test.find_one()["foo"])
Ejemplo n.º 7
0
class PyMongo(object):
    """This class is used to control the pymongo integration with a Flask
    application. There are two usage modes which are similar.

    The first usage mode is to bind the instance to a specific application::

        app = Flask(__name__)
        db = PyMongo(app)

    The second usage mode is to initialize the extension and provide an
    application object later::

        db = PyMongo()

        def create_app():
          app = Flask(__name__)
          db.init_app(app)
          return app

    The latter of course has the benefit of avoiding all kinds of problems as
    described in the Flask documentation on the :ref:`~app-factories` pattern.

    During initialization, PyMongo takes another optional parameter `database`
    that can be used to set a the name of the default database to be used for
    all models that do not provide a `database` attribute themselves. This is
    often useful as one database is all that is used in many applications.

    This class also provides access to the pymongo constants for indexing and
    profiling.
    """
    def __init__(self, app=None, database=None, **kwargs):
        self.database = database
        self.Model = Model
        self.Model.query = self
        self.Query = Query
        self.Index = Index

        self._include_constants()

        if app is not None:
            self.init_app(app, **kwargs)
        else:
            self.app = None
            self.hosts = None

    def init_app(self, app, **kwargs):
        """Initializes `app`, a :class:`~flask.Flask` application, for use with
        the specified configuration variables. Keyword arguments passed to this
        override the configuration options.
        """
        options = {
            'max_pool_size': app.config.get('MONGO_MAX_POOL_SIZE', 10),
            'network_timeout': app.config.get('MONGO_NETWORK_TIMEOUT', None),
            'tz_aware': app.config.get('MONGO_TZ_AWARE', False),
            'slave_okay': app.config.get('MONGO_SLAVE_OKAY', False),
            'safe': app.config.get('MONGO_GETLASTERROR', False),
            'fsync': app.config.get('MONGO_GETLASTERROR_FSYNC', None),
            'j': app.config.get('MONGO_GETLASTERROR_J', None),
            'w': app.config.get('MONGO_GETLASTERROR_W', None),
            'wtimeout': app.config.get('MONGO_GETLASTERROR_W_TIMEOUT', None),
            'replicaset': app.config.get('MONGO_REPLICA_SET', None),
        }.update(kwargs)

        self.app = app
        self.hosts = app.config.get('MONGO_HOSTS', "mongodb://localhost:27017")
        self.connection = BaseConnection(self.hosts, options)

        @app.teardown_request
        def free_sockets(response):
            # release thread connection to pool so socket is reclaimed
            self.connection.end_request()
            return response

        for model, indices in _indices.iteritems():
            for index in indices:
                index.ensure(model.query)

    def _include_constants(self):
        self.ASCENDING = ASCENDING
        self.DESCENDING = DESCENDING
        self.GEO2D = GEO2D

    def __repr__(self):
        return "<%s connection=%s>" % (self.__class__.__name__, self.hosts)
Ejemplo n.º 8
0
class PyMongo(object):
    """This class is used to control the pymongo integration with a Flask
    application. There are two usage modes which are similar.

    The first usage mode is to bind the instance to a specific application::

        app = Flask(__name__)
        db = PyMongo(app)

    The second usage mode is to initialize the extension and provide an
    application object later::

        db = PyMongo()

        def create_app():
          app = Flask(__name__)
          db.init_app(app)
          return app

    The latter of course has the benefit of avoiding all kinds of problems as
    described in the Flask documentation on the :ref:`~app-factories` pattern.

    During initialization, PyMongo takes another optional parameter `database`
    that can be used to set a the name of the default database to be used for
    all models that do not provide a `database` attribute themselves. This is
    often useful as one database is all that is used in many applications.

    This class also provides access to the pymongo constants for indexing and
    profiling.
    """

    def __init__(self, app=None, database=None, **kwargs):
        self.database = database
        self.Model = Model
        self.Model.query = self
        self.Query = Query
        self.Index = Index

        self._include_constants()

        if app is not None:
            self.init_app(app, **kwargs)
        else:
            self.app = None
            self.hosts = None
    
    def init_app(self, app, **kwargs):
        """Initializes `app`, a :class:`~flask.Flask` application, for use with
        the specified configuration variables. Keyword arguments passed to this
        override the configuration options.
        """
        options = {
            'max_pool_size': app.config.get('MONGO_MAX_POOL_SIZE', 10),
            'network_timeout': app.config.get('MONGO_NETWORK_TIMEOUT', None),
            'tz_aware': app.config.get('MONGO_TZ_AWARE', False),
            'slave_okay': app.config.get('MONGO_SLAVE_OKAY', False),
            'safe': app.config.get('MONGO_GETLASTERROR', False),
            'fsync': app.config.get('MONGO_GETLASTERROR_FSYNC', None),
            'j': app.config.get('MONGO_GETLASTERROR_J', None),
            'w': app.config.get('MONGO_GETLASTERROR_W', None),
            'wtimeout': app.config.get('MONGO_GETLASTERROR_W_TIMEOUT', None),
            'replicaset': app.config.get('MONGO_REPLICA_SET', None),
        }.update(kwargs)

        self.app = app
        self.hosts = app.config.get('MONGO_HOSTS', "mongodb://localhost:27017")
        self.connection = BaseConnection(self.hosts, options)

        @app.teardown_request
        def free_sockets(response):
            # release thread connection to pool so socket is reclaimed
            self.connection.end_request()
            return response

        for model, indices in _indices.iteritems():
            for index in indices:
                index.ensure(model.query)

    def _include_constants(self):
        self.ASCENDING = ASCENDING
        self.DESCENDING = DESCENDING
        self.GEO2D = GEO2D

    def __repr__(self):
        return "<%s connection=%s>" % (self.__class__.__name__, self.hosts)