Python peewee.MySQLDatabase() Examples

The following are 8 code examples of peewee.MySQLDatabase(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module peewee , or try the search function .
Example #1
Source File: config.py    From sentinel with MIT License 5 votes vote down vote up
def get_db_conn():
    import peewee
    env = os.environ.get('SENTINEL_ENV', 'production')

    # default values should be used unless you need a different config for development
    db_host = sentinel_cfg.get('db_host', '127.0.0.1')
    db_port = sentinel_cfg.get('db_port', None)
    db_name = sentinel_cfg.get('db_name', 'sentinel')
    db_user = sentinel_cfg.get('db_user', 'sentinel')
    db_password = sentinel_cfg.get('db_password', 'sentinel')
    db_charset = sentinel_cfg.get('db_charset', 'utf8mb4')
    db_driver = sentinel_cfg.get('db_driver', 'sqlite')

    if (env == 'test'):
        if db_driver == 'sqlite':
            db_name = sqlite_test_db_name(db_name)
        else:
            db_name = "%s_test" % db_name

    peewee_drivers = {
        'mysql': peewee.MySQLDatabase,
        'postgres': peewee.PostgresqlDatabase,
        'sqlite': peewee.SqliteDatabase,
    }
    driver = peewee_drivers.get(db_driver)

    dbpfn = 'passwd' if db_driver == 'mysql' else 'password'
    db_conn = {
        'host': db_host,
        'user': db_user,
        dbpfn: db_password,
    }
    if db_port:
        db_conn['port'] = int(db_port)

    if driver == peewee.SqliteDatabase:
        db_conn = {}

    db = driver(db_name, **db_conn)

    return db 
Example #2
Source File: __init__.py    From pypi-server with MIT License 5 votes vote down vote up
def init_mysql(url):
    global DB

    db_name = url.path.strip("/")

    DB.initialize(MySQLDatabase(
        database=db_name,
        user=url.user or '',
        password=url.password or '',
        host=url.host,
        autocommit=bool(url.get('autocommit', True)),
        autorollback=bool(url.get('autorollback', True))
    ))
    log.info("Database initialized as '%s'. Checking migrations...", db_name)
    return DB, MySQLMigrator(DB) 
Example #3
Source File: schema.py    From taxadb with MIT License 5 votes vote down vote up
def get_database(self):
        """Returns the correct database driver

        Returns:
            :obj:`pw.Database`
        Raises:
            AttributeError: if `--username` or `--password` not passed
                (if `--dbtype [postgres|mysql]`)

        """
        if self.get('dbtype') == 'sqlite':
            return pw.SqliteDatabase(self.get('dbname'),
                                     pragmas={'journal_mode': 'wal',
                                              'cache_size': -1 * 64000})
        else:
            if self.get('username') is None or self.get('password') is None:
                raise AttributeError('[ERROR] dbtype %s requires username and'
                                     ' password.\n' % str(self.get('dbtype')))
            if self.get('hostname') is None:
                self.set('hostname', 'localhost')
            if self.get('dbtype') == 'mysql':
                if self.get('port') is None or self.get('port') == '':
                    self.set('port', str(3306))
                return pw.MySQLDatabase(
                    self.get('dbname'),
                    user=self.get('username'),
                    password=self.get('password'),
                    host=self.get('hostname'),
                    port=int(self.get('port')))
            elif self.get('dbtype') == 'postgres':
                if self.get('port') is None or self.get('port') == '':
                    self.set('port', str(5432))
                return pw.PostgresqlDatabase(
                    self.get('dbname'),
                    user=self.get('username'),
                    password=self.get('password'),
                    host=self.get('hostname'),
                    port=int(self.get('port'))) 
Example #4
Source File: peewee_async.py    From peewee-async with MIT License 5 votes vote down vote up
def _swap_database(self, query):
        """Swap database for query if swappable. Return **new query**
        with swapped database.

        This is experimental feature which allows us to have multiple
        managers configured against different databases for single model
        definition.

        The essential limitation though is that database backend have
        to be **the same type** for model and manager!
        """
        database = _query_db(query)

        if database == self.database:
            return query

        if self._subclassed(peewee.PostgresqlDatabase, database,
                            self.database):
            can_swap = True
        elif self._subclassed(peewee.MySQLDatabase, database,
                              self.database):
            can_swap = True
        else:
            can_swap = False

        if can_swap:
            # **Experimental** database swapping!
            query = query.clone()
            query._database = self.database
            return query

        assert False, (
            "Error, query's database and manager's database are "
            "different. Query: %s Manager: %s" % (database, self.database)
        )

        return None 
Example #5
Source File: peeweedbevolve.py    From peewee-db-evolve with GNU Lesser General Public License v3.0 5 votes vote down vote up
def is_mysql(db):
  return isinstance(db, pw.MySQLDatabase) 
Example #6
Source File: test.py    From peewee-db-evolve with GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
    os.system('echo "create database peeweedbevolve_test;" | mysql')
    self.db = pw.MySQLDatabase('peeweedbevolve_test')
    self.db.connect()
    peeweedbevolve.clear() 
Example #7
Source File: migrator.py    From PyPlanet with GNU General Public License v3.0 5 votes vote down vote up
def __get_migrator(self):
		if isinstance(self.db.engine, peewee.SqliteDatabase) or isinstance(self.db.engine, SqliteExtDatabase):
			return SqliteMigrator(self.db.engine)
		elif isinstance(self.db.engine, peewee.MySQLDatabase):
			return MySQLMigrator(self.db.engine)
		elif isinstance(self.db.engine, peewee.PostgresqlDatabase):
			return PostgresqlMigrator(self.db.engine)
		raise ImproperlyConfigured('Database engine doesn\'t support Migrations!') 
Example #8
Source File: base_model.py    From openrasp-iast with Apache License 2.0 4 votes vote down vote up
def __init__(self, table_prefix=None, use_async=True, create_table=True, multiplexing_conn=False):
        """
        初始化

        Parameters:
            table_prefix - 表名前缀,由扫描目标的 host + "_" + str(port) 组成
            use_async - 是否开启数据库连接的异步查询功能,默认为True
            create_table - 数据表不存在时是否创建,默认为True
            multiplexing_conn - 是否复用连接,为True时,相同的Model的实例会使用同一个连接, 为int时使用该int大小的连接池, 默认为False

        Raises:
            create_table为Fasle且目标数据表不存在时,引发exceptions.TableNotExist
        """
        self.use_async = use_async
        try:
            if multiplexing_conn:
                database = BaseModel.mul_database
            else:
                if self.use_async:
                    database = peewee_async.MySQLDatabase(**self.connect_para)
                else:
                    database = peewee.MySQLDatabase(**self.connect_para)
                database.connect()

            # table_prefix 为None则不建立数据表实例,仅用于调用基类方法
            if table_prefix is not None:
                self._model = self._create_model(database, table_prefix)
                if not self._model.table_exists():
                    if create_table:
                        try:
                            database.create_tables([self._model])
                            Logger().debug("Create table {}_{}".format(table_prefix, self.__class__.__name__))
                            if self.__class__.__name__ == "NewRequestModel":
                                Communicator().update_target_list_status()
                        except peewee.InternalError:
                            pass
                    else:
                        raise exceptions.TableNotExist

            self.database = database
        except exceptions.TableNotExist as e:
            self._handle_exception("Table with prefix {} not found!".format(table_prefix), e)
        except Exception as e:
            self._handle_exception("Mysql Connection Fail!", e)