Beispiel #1
0
def get_mongo_objs(host, port, dbname,
                   username=None, passwd=None):
    """
    :return: Database connection, database instance and collection instance.
    """
    connection = Connection(host=host, port=port,
                            read_preference=ReadPreference.NEAREST)
    connection.register([BenchmarkResult])
    benchresult = getattr(connection, dbname).benchresults.BenchmarkResult
    db = Database(connection, dbname)
    if username is not None:
        db.authenticate(username, password=passwd)
    return connection, db, benchresult
class MongoKit(object):
    """This class is used to integrate `MongoKit`_ into a Flask application.

    :param app: The Flask application will be bound to this MongoKit instance.
                If an app is not provided at initialization time than it
                must be provided later by calling :meth:`init_app` manually.

    .. _MongoKit: http://namlook.github.com/mongokit/
    """

    def __init__(self, app=None, database=None):
        #: :class:`list` of :class:`mongokit.Document`
        #: which will be automated registed at connection
        self.registered_documents = []
        self.mongokit_connection = None
        self.database = database

        if app is not None:
            self.app = app
            self.init_app(self.app)
        else:
            self.app = None

    def init_app(self, app):
        """Also it registers the
        :class:`flask.ext.mongokit.BSONObjectIdConverter`
        as a converter with the key word **ObjectId**.

        :param app: The Flask application will be bound to this MongoKit
                    instance.
        """
        app.config.setdefault('MONGODB_HOST', '127.0.0.1')
        app.config.setdefault('MONGODB_PORT', 27017)
        app.config.setdefault('MONGODB_DATABASE', 'flask')
        app.config.setdefault('MONGODB_SLAVE_OKAY', False)
        app.config.setdefault('MONGODB_USERNAME', None)
        app.config.setdefault('MONGODB_PASSWORD', None)
        app.config.setdefault('MONGODB_MAX_POOL_SIZE', 10)

        # register extension with app
        app.extensions = getattr(app, 'extensions', {})
        app.extensions['mongokit'] = self

        app.url_map.converters['ObjectId'] = BSONObjectIdConverter

        self.app = app

    def register(self, documents):
        """Register one or more :class:`mongokit.Document` instances to the
        connection.

        Can be also used as a decorator on documents:

        .. code-block:: python

            db = MongoKit(app)

            @db.register
            class Task(Document):
                structure = {
                   'title': unicode,
                   'text': unicode,
                   'creation': datetime,
                }

        :param documents: A :class:`list` of :class:`mongokit.Document`.
        """

        #enable decorator usage as in mongokit.Connection
        decorator = None
        if not isinstance(documents, (list, tuple, set, frozenset)):
            # we assume that the user used this as a decorator
            # using @register syntax or using db.register(SomeDoc)
            # we stock the class object in order to return it later
            decorator = documents
            documents = [documents]

        for document in documents:
            if document not in self.registered_documents:
                self.registered_documents.append(document)

        if decorator is None:
            return self.registered_documents
        else:
            return decorator

    def connect(self):
        """Connect to the MongoDB server and register the documents from
        :attr:`registered_documents`. If you set ``MONGODB_USERNAME`` and
        ``MONGODB_PASSWORD`` then you will be authenticated at the
        ``MONGODB_DATABASE``.
        """
        self.mongokit_connection = Connection(
            host=self.app.config.get('MONGODB_HOST'),
            port=self.app.config.get('MONGODB_PORT'),
            max_pool_size=self.app.config.get('MONGODB_MAX_POOL_SIZE'),
            slave_okay=self.app.config.get('MONGODB_SLAVE_OKAY')
        )
        self.mongokit_connection.register(self.registered_documents)
        if self.database:
            self.mongokit_db = Database(self.mongokit_connection, self.database)
        else:
            self.mongokit_db = Database(self.mongokit_connection, self.app.config.get('MONGODB_DATABASE'))
        if self.app.config.get('MONGODB_USERNAME') is not None:
            self.mongokit_db.authenticate(
                self.app.config.get('MONGODB_USERNAME'),
                self.app.config.get('MONGODB_PASSWORD')
            )

    @property
    def connected(self):
        """Connection status to your MongoDB."""
        return self.mongokit_connection is not None

    def disconnect(self):
        """Close the connection to your MongoDB."""
        if self.connected:
            self.mongokit_connection.disconnect()
            self.mongokit_connection = None
            del self.mongokit_db

    def __getattr__(self, name, **kwargs):
        if not self.connected:
            self.connect()
        return getattr(self.mongokit_db, name)
Beispiel #3
0
def word_validator(value):
    word = re.compile(r'^[-A-Za-z0-9_]+(?: +[-A-Za-z0-9_]+)*$')
    return bool(word.match(value))


class Word(Document):
    structure = {
        'word': basestring,
        'content': basestring,
        'related': basestring,
        'word_info': {
            'word_class': basestring,
            'phonetic': unicode,
            'definition': [{
                'explain': basestring,
                'example': [basestring],
            }],
        },
    }

    required = ['word']
    validators = {
        'word': word_validator,
    }

conn = Connection(host=settings.HOST, port=int(settings.PORT))
conn.register([Word])
db = Database(conn, 't')
db.authenticate('admin', 'fk5es-3PTd8c')
class MongoKit(object):
    """This class is used to integrate `MongoKit`_ into a Flask application.

    :param app: The Flask application will be bound to this MongoKit instance.
                If an app is not provided at initialization time than it
                must be provided later by calling :meth:`init_app` manually.

    .. _MongoKit: http://namlook.github.com/mongokit/
    """

    def __init__(self, app=None):
        #: :class:`list` of :class:`mongokit.Document`
        #: which will be automated registed at connection
        self.registered_documents = []

        if app is not None:
            self.app = app
            self.init_app(self.app)
        else:
            self.app = None

    def init_app(self, app):
        """This method connect your ``app`` with this extension. Flask-
        MongoKit will now take care about to open and close the connection to 
        your MongoDB.
        
        Also it registers the
        :class:`flask.ext.mongokit.BSONObjectIdConverter`
        as a converter with the key word **ObjectId**.

        :param app: The Flask application will be bound to this MongoKit
                    instance.
        """
        app.config.setdefault('MONGODB_HOST', '127.0.0.1')
        app.config.setdefault('MONGODB_PORT', 27017)
        app.config.setdefault('MONGODB_DATABASE', 'flask')
        app.config.setdefault('MONGODB_USERNAME', None)
        app.config.setdefault('MONGODB_PASSWORD', None)
        app.config.setdefault('MONGODB_URL', 'mongodb://127.0.0.1:27071/')
        app.config.setdefault('MONGODB_CONNECTION_OPTIONS', {
            'auto_start_request': False
        })

        app.before_first_request(self._before_first_request)

        # 0.9 and later
        # no coverage check because there is everytime only one
        if hasattr(app, 'teardown_appcontext'):  # pragma: no cover
            app.teardown_appcontext(self._teardown_request)
        # 0.7 to 0.8
        elif hasattr(app, 'teardown_request'):  # pragma: no cover
            app.teardown_request(self._teardown_request)
        # Older Flask versions
        else:  # pragma: no cover
            app.after_request(self._teardown_request)

        # register extension with app only to say "I'm here"
        app.extensions = getattr(app, 'extensions', {})
        app.extensions['mongokit'] = self

        app.url_map.converters['ObjectId'] = BSONObjectIdConverter

        self.app = app

        self.mongokit_connection = Connection(
            host=app.config.get('MONGODB_HOST'),
            port=app.config.get('MONGODB_PORT'),
            **app.config.get('MONGODB_CONNECTION_OPTIONS', {})
        )
        self.mongokit_database = Database(self.mongokit_connection, app.config.get('MONGODB_DATABASE'))
        if app.config.get('MONGODB_USERNAME') is not None:
            auth_success = self.mongokit_database.authenticate(
                app.config.get('MONGODB_USERNAME'),
                app.config.get('MONGODB_PASSWORD')
            )
            if not auth_success:
                raise AuthenticationIncorrect('Server authentication failed')

    @property
    def connected(self):
        """Connection status to your MongoDB."""
        ctx = ctx_stack.top
        return getattr(ctx, 'mongokit_connection', None) is not None

    def _before_first_request(self):
        self.mongokit_connection.start_request()

    def _teardown_request(self, response):
        self.mongokit_connection.end_request()
        return response

    def __getattr__(self, name, **kwargs):
        return getattr(self._get_mongo_database(), name)

    def __getitem__(self, name):
        return self._get_mongo_database()[name]

    def _get_mongo_database(self):
        return self.mongokit_database