Пример #1
0
    def __init__(self,
                 database_name=None,
                 config_file=None,
                 database_type=None):
        # Get the configuration
        self.config = MagpyConfigParser(config_file)

        # Get the database engine type
        if not database_type:
            database_type = self.config.databases['default']['ENGINE']

        # Get the client class
        if database_type == 'ainodb':
            from ainodb import Client
            from ainodb.errors import ConnectionFailure
        else:
            try:
                from pymongo import MongoClient as Client
            except ImportError:
                from pymongo import Connection as Client
            from pymongo.errors import ConnectionFailure

        # Make a connection
        try:
            self.connection = Client(tz_aware=True)
        except ConnectionFailure:
            print("Could not connect to the database.")
            print("Are you sure it is installed and is running?")
            print("The exception is shown below.")
            print("")

            raise

        # Get the database
        if not database_name:

            if DEFAULT_DATABASE:
                database_name = DEFAULT_DATABASE
            else:
                database_name = self.config.databases['default']['NAME']

        self._database_name = database_name
        self.database = self.connection[database_name]
Пример #2
0
class Database(object):
    """Simple database connection for use in serverside scripts etc."""
    def __init__(self,
                 database_name=None,
                 config_file=None,
                 database_type=None):
        # Get the configuration
        self.config = MagpyConfigParser(config_file)

        # Get the database engine type
        if not database_type:
            database_type = self.config.databases['default']['ENGINE']

        # Get the client class
        if database_type == 'ainodb':
            from ainodb import Client
            from ainodb.errors import ConnectionFailure
        else:
            try:
                from pymongo import MongoClient as Client
            except ImportError:
                from pymongo import Connection as Client
            from pymongo.errors import ConnectionFailure

        # Make a connection
        try:
            self.connection = Client(tz_aware=True)
        except ConnectionFailure:
            print("Could not connect to the database.")
            print("Are you sure it is installed and is running?")
            print("The exception is shown below.")
            print("")

            raise

        # Get the database
        if not database_name:

            if DEFAULT_DATABASE:
                database_name = DEFAULT_DATABASE
            else:
                database_name = self.config.databases['default']['NAME']

        self._database_name = database_name
        self.database = self.connection[database_name]

    def drop_database(self):
        """Drop the whole database."""
        self.connection.drop_database(self.database)
        self.database = self.connection[self._database_name]

    def get_collection(self, collection):
        """Get a collection by name."""
        return self.database[collection]

    def drop_collection(self, collection):
        """Drop a collection by name."""
        self.database.drop_collection(collection)

    def drop_collections(self, collections):
        """Drop a named tuple or list of collections."""
        for collection in collections:
            self.drop_collection(collection)

    def get_setting_category(self, category):
        """Get a setting category from the database."""
        settings = self.get_collection('_settings')
        return settings.find_one({'_id': category})

    def get_setting(self, category, setting):
        """Get a setting from the database."""
        category = self.get_setting_category(category)
        if not category:
            return None
        try:
            return category[setting]
        except KeyError:
            return None

    def add_setting(self, category, setting, value):
        """Add a setting to the database."""
        category_instance = self.get_setting_category(category)
        if category_instance:
            category_instance[setting] = value
        else:
            category_instance = {'_id': category,
                                 setting: value}
        settings = self.get_collection('_settings')
        settings.save(category_instance)

    def remove_setting(self, category, setting):
        """Remove a setting from the database."""
        category_instance = self.get_setting_category(category)
        if not category_instance:
            return
        if not setting in category_instance:
            return
        del category_instance[setting]
        settings = self.get_collection('_settings')

        if len(category_instance.keys()) == 1:
            settings.remove(category_instance['_id'])
        else:
            settings.update(category_instance)

    def add_list_setting(self, category, setting, value):
        """Add a value to a list setting."""
        category_instance = self.get_setting_category(category)
        if category_instance:
            if not setting in category_instance:
                category_instance['setting'] = []
        else:
            category_instance = {'_id': category,
                                 setting: []}
        if value not in category_instance[setting]:
            category_instance[setting].append(value)
            settings = self.get_collection('_settings')
            settings.save(category_instance)
        else:
            print("Already set, skipping.")

    def remove_list_setting(self, category, setting, value):
        """Add a value to a list setting."""
        category_instance = self.get_setting_category(category)

        # To remove the value from the setting, the setting must exist
        if not category_instance:
            return
        if not setting in category_instance:
            return

        # Now lets try to remove the named setting
        try:
            category_instance[setting].remove(value)
        except ValueError:
            # It was not in the list.
            return

        settings = self.get_collection('_settings')
        settings.save(category_instance)
        return

    def get_app_list(self):
        """Get the list of installed applications from the database."""
        return self.get_setting('applications', 'installed_apps')

    def add_app(self, app_name):
        """Add an app name to the list of installed applications."""
        self.add_list_setting('applications', 'installed_apps', app_name)

    def remove_app(self, app_name):
        """Remove an app name from the list of installed applications."""
        self.remove_list_setting('applications', 'installed_apps',
                                 app_name)

    def get_model(self, model_name):
        """Get a model."""
        models = self.get_collection('_model')
        return models.find_one({'_id': model_name})

    def index(self, model_name, field_name, force=False):
        """Create an index for the field,
        (if the index does not already exist)."""
        model = self.get_model(model_name)
        field = model[field_name]
        if 'index' in field:
            if field['index'] is False and force is False:
                raise ModelIndexError(
                    "Field definition has index: False. "
                    "Use force=True to override.")
        collection = self.get_collection(model_name)
        collection.ensure_index(field_name)

    def add_instance(self, instance,
                     skip_validation=False,
                     handle_none=False):
        """Add an instance to the db."""
        model_name = instance['_model']

        if not skip_validation:
            model = self.get_model(model_name)

            try:
                validate_model_instance(model,
                                        instance,
                                        handle_none=handle_none)
            except ValidationError:
                print("Died on instance:")
                print(instance)
                raise

        # We got this far, yay!
        instance_collection = self.get_collection(model_name)
        instance_collection.save(instance)
        sys.stdout.write(model_name[0])

    def add_instances(self, instances,
                      skip_validation=False,
                      handle_none=False):
        """All several instances to the db."""
        for instance in instances:
            self.add_instance(instance, skip_validation, handle_none)