Exemple #1
0
def test_struct():
    from muffin.utils import Struct, LStruct

    data = Struct({'test': 42})
    assert data.test == 42

    data.test = 21
    assert data.test == 21

    settings = LStruct({'option': 'value'})
    assert settings.option == 'value'

    settings.option2 = 'value2'
    settings.freeze()
    settings.freeze()

    with pytest.raises(RuntimeError):
        settings.test = 42
Exemple #2
0
def test_struct():
    from muffin.utils import Struct, LStruct

    data = Struct({'test': 42})
    assert data.test == 42

    data.test = 21
    assert data.test == 21

    settings = LStruct({'option': 'value'})
    assert settings.option == 'value'

    settings.option2 = 'value2'
    settings.lock()
    settings.lock()

    with pytest.raises(RuntimeError):
        settings.test = 42
Exemple #3
0
class Plugin(BasePlugin):

    """Integrate Peewee to Muffin."""

    name = 'peewee'
    defaults = {

        # Connection params
        'connection': 'sqlite:///db.sqlite',
        'connection_params': {},

        # Manage connections manually
        'connection_manual': False,

        # Setup migration engine
        'migrations_enabled': True,
        'migrations_path': 'migrations',
    }

    Model = Model
    TModel = TModel

    def __init__(self, **options):
        """Initialize the plugin."""
        super().__init__(**options)

        self.database = peewee.Proxy()
        self.models = Struct()

    def setup(self, app):
        """Initialize the application."""
        super().setup(app)

        # Setup Database
        self.database.initialize(connect(
            self.cfg.connection, **self.cfg.connection_params))

        # Fix SQLite in-memory database
        if self.database.database == ':memory:':
            self.cfg.connection_manual = True

        if not self.cfg.migrations_enabled:
            return

        # Setup migration engine
        self.router = Router(self)
        self.register(MigrateHistory)

        # Register migration commands
        @self.app.manage.command
        def migrate(name: str=None):
            """Run application's migrations.

            :param name: Choose a migration' name
            """
            self.router.run(name)

        @self.app.manage.command
        def create(name: str):
            """Create a migration.

            :param name: Set name of migration [auto]
            """
            self.router.create(name)

        @self.app.manage.command
        def csv_dump(table: str, path: str='dump.csv'):
            """Dump DB table to CSV.

            :param table: Table name for dump data
            :param path: Path to file where data will be dumped
            """
            model = self.models.get(table)
            if model is None:
                raise MuffinException('Unknown db table: %s' % table)

            with open(path, 'w') as fh:
                dump_csv(model.select().order_by(model._meta.primary_key), fh)
                self.app.logger.info('Dumped to %s' % path)

        @self.app.manage.command
        def csv_load(table: str, path: str='dump.csv', pk_in_csv: bool=False):
            """Load CSV to DB table.

            :param table: Table name for load data
            :param path: Path to file which from data will be loaded
            :param pk_in_csv: Primary keys stored in CSV
            """
            model = self.models.get(table)
            if model is None:
                raise MuffinException('Unknown db table: %s' % table)

            load_csv(model, path)
            self.app.logger.info('Loaded from %s' % path)

    def start(self, app):
        """Register connection's middleware and prepare self database."""
        self.database.async_init(app.loop)
        if not self.cfg.connection_manual:
            app.middlewares.insert(0, peewee_middleware_factory)

    def finish(self, app):
        """Close all connections."""
        if hasattr(self.database.obj, 'close_all'):
            self.database.close_all()

    def register(self, model):
        """Register a model in self."""
        self.models[model._meta.db_table] = model
        model._meta.database = self.database
        return model

    @asyncio.coroutine
    def manage(self):
        """Manage a database connection."""
        cm = _ContextManager(self.database)
        if (self.database.obj, AIODatabase):
            cm.connection = yield from self.database.async_connect()

        else:
            cm.connection = self.database.connect()

        return cm
Exemple #4
0
    def __init__(self, **options):
        """Initialize the plugin."""
        super().__init__(**options)

        self.database = peewee.Proxy()
        self.models = Struct()
Exemple #5
0
 def load_many(self, request):
     return [
         Struct(id=1, name='test1'),
         Struct(id=2, name='test2'),
         Struct(id=3, name='test3'),
     ]