Python sqlalchemy.pool.StaticPool() Examples

The following are 20 code examples of sqlalchemy.pool.StaticPool(). 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 sqlalchemy.pool , or try the search function .
Example #1
Source File: test_console.py    From hiku with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_query():
    sa_engine = create_engine(
        'sqlite://',
        connect_args={'check_same_thread': False},
        poolclass=StaticPool,
    )
    setup_db(sa_engine)

    app = ConsoleApplication(GRAPH, engine, {SA_ENGINE_KEY: sa_engine},
                             debug=True)
    query = b'[{:bar_list [:name :type {:foo_s [:name :count]}]}]'

    status, headers, content = request(app, 'POST', '/', payload=query)
    assert status == '200 OK'
    assert ('Content-Type', 'application/json') in headers
    result = json.loads(content.decode('utf-8'))
    assert 'bar_list' in result 
Example #2
Source File: datastore.py    From eventsourcing with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setup_connection(self) -> None:
        assert isinstance(self.settings, SQLAlchemySettings), self.settings
        if self._engine is None:

            # Create SQLAlchemy engine.
            if self.is_sqlite():
                kwargs: Dict[str, Any] = {"connect_args": {"check_same_thread": False}}
            elif self.settings.pool_size == 1:
                kwargs = {"poolclass": StaticPool}
            else:
                kwargs = {"pool_size": self.settings.pool_size}

            self._engine = create_engine(
                self.settings.uri,
                strategy=self._connection_strategy,
                # echo=True,
                **kwargs
            )
            assert self._engine 
Example #3
Source File: model.py    From pychess with GNU General Public License v3.0 6 votes vote down vote up
def get_engine(path=None, dialect="sqlite", echo=False):
    if path is None:
        # In memory database
        url = "sqlite://"
    elif dialect == "sqlite":
        url = "%s:///%s" % (dialect, path)

    if url in engines and os.path.isfile(path) and os.path.getsize(path) > 0:
        return engines[url]
    else:
        if path is None:
            engine = create_engine(url, connect_args={'check_same_thread': False},
                                   echo=echo, poolclass=StaticPool)
        else:
            if path != empty_db and (not os.path.isfile(path) or os.path.getsize(path) == 0):
                shutil.copyfile(empty_db, path)
            engine = create_engine(url, echo=echo)

        if path != empty_db and (path is None or get_schema_version(engine) != SCHEMA_VERSION):
            metadata.drop_all(engine)
            metadata.create_all(engine)
            ini_schema_version(engine)

        engines[url] = engine
        return engine 
Example #4
Source File: test_pool.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_no_connect_on_recreate(self):
        def creator():
            raise Exception("no creates allowed")

        for cls in (
            pool.SingletonThreadPool,
            pool.StaticPool,
            pool.QueuePool,
            pool.NullPool,
            pool.AssertionPool,
        ):
            p = cls(creator=creator)
            p.dispose()
            p2 = p.recreate()
            assert p2.__class__ is cls

            mock_dbapi = MockDBAPI()
            p = cls(creator=mock_dbapi.connect)
            conn = p.connect()
            conn.close()
            mock_dbapi.connect.side_effect = Exception("error!")
            p.dispose()
            p.recreate() 
Example #5
Source File: test_source_sqlalchemy.py    From hiku with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def check(self, src, value):
        sa_engine = create_engine(
            'sqlite://',
            connect_args={'check_same_thread': False},
            poolclass=StaticPool,
        )
        setup_db(sa_engine)

        engine = Engine(ThreadsExecutor(thread_pool))
        result = engine.execute(self.graph, read(src),
                                {SA_ENGINE_KEY: sa_engine})
        check_result(result, value) 
Example #6
Source File: test_reflection.py    From android_universal with MIT License 5 votes vote down vote up
def setup_bind(cls):
        if config.requirements.independent_connections.enabled:
            from sqlalchemy import pool
            return engines.testing_engine(
                options=dict(poolclass=pool.StaticPool))
        else:
            return config.db 
Example #7
Source File: test_reflection.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def setup_bind(cls):
        if config.requirements.independent_connections.enabled:
            from sqlalchemy import pool
            return engines.testing_engine(
                options=dict(poolclass=pool.StaticPool))
        else:
            return config.db 
Example #8
Source File: box.py    From box-python-sdk with Apache License 2.0 5 votes vote down vote up
def reset_filesystem(self, users=(), applications=()):
        """
        Create in-memory DB that can be accessed by multiple threads.
        Set up auth requests, the rate limit bucket, and the request log.
        """
        self._db_engine = sqlalchemy.create_engine(
            'sqlite:///:memory:',
            connect_args={'check_same_thread': False},
            poolclass=StaticPool,
        )
        DbModel.metadata.create_all(self._db_engine)
        self._db_session_maker = sessionmaker(bind=self._db_engine, autoflush=True)
        self._db_session = self._db_session_maker()
        self._db_session.add(FolderModel(folder_id=0))
        self._db_session.commit()
        self._rate_limit_bucket = (self.RATE_LIMIT_THRESHOLD, datetime.utcnow())
        self._request_log = []
        self._oauth_behavior = OAuth2Behavior(self._db_session)
        self._file_behavior = FileBehavior(self._db_session)
        self._folder_behavior = FolderBehavior(self._db_session)
        self._event_behavior = EventBehavior(self._db_session)
        self._user_behavior = UserBehavior(self._db_session)
        user_ids = []
        for user_info in users:
            user_name, user_login = user_info
            user_id = self.add_user(user_name, user_login)
            user_ids.append(user_id)
        for app_info in applications:
            client_id, client_secret, user_index = app_info
            self.add_application(client_id, client_secret, user_ids[user_index]) 
Example #9
Source File: test_pool.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_recreate(self):
        dbapi = MockDBAPI()

        def creator():
            return dbapi.connect("foo.db")

        p = pool.StaticPool(creator)
        p2 = p.recreate()
        assert p._creator is p2._creator 
Example #10
Source File: test_pool.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_static_pool(self):
        self._do_test(pool.StaticPool, ["R", "R"]) 
Example #11
Source File: test_reflection.py    From sqlalchemy with MIT License 5 votes vote down vote up
def setup_bind(cls):
        if config.requirements.independent_connections.enabled:
            from sqlalchemy import pool

            return engines.testing_engine(
                options=dict(poolclass=pool.StaticPool)
            )
        else:
            return config.db 
Example #12
Source File: single_inserts.py    From sqlalchemy with MIT License 5 votes vote down vote up
def setup_database(dburl, echo, num):
    global engine
    engine = create_engine(dburl, echo=echo)
    if engine.dialect.name == "sqlite":
        engine.pool = pool.StaticPool(creator=engine.pool._creator)
    Base.metadata.drop_all(engine)
    Base.metadata.create_all(engine) 
Example #13
Source File: engines.py    From oslo.db with Apache License 2.0 5 votes vote down vote up
def _init_connection_args(url, engine_args, **kw):
    pool_class = url.get_dialect().get_pool_class(url)
    # singletonthreadpool is used for :memory: connections;
    # replace it with StaticPool.
    if issubclass(pool_class, pool.SingletonThreadPool):
        engine_args["poolclass"] = pool.StaticPool
        engine_args['connect_args']['check_same_thread'] = False 
Example #14
Source File: test_reflection.py    From pyRevit with GNU General Public License v3.0 5 votes vote down vote up
def setup_bind(cls):
        if config.requirements.independent_connections.enabled:
            from sqlalchemy import pool
            return engines.testing_engine(
                options=dict(poolclass=pool.StaticPool))
        else:
            return config.db 
Example #15
Source File: sqldb.py    From activitypub with Mozilla Public License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__()
        args = list(args)
        if args[0].endswith(":memory:"):
            args[0] = args[0].replace(":memory:", "")
        if args[0] == "sqlite://": # in-memory
            kwargs.update({
                "connect_args": {'check_same_thread': False},
                "poolclass": StaticPool,
            })
            self.engine = create_engine(*args, **kwargs)
            self.session = sessionmaker(bind=self.engine)()
        else:
            self.engine = create_engine(*args, **kwargs)
            self.session = scoped_session(sessionmaker(bind=self.engine)) 
Example #16
Source File: test_reflection.py    From planespotter with MIT License 5 votes vote down vote up
def setup_bind(cls):
        if config.requirements.independent_connections.enabled:
            from sqlalchemy import pool
            return engines.testing_engine(
                options=dict(poolclass=pool.StaticPool))
        else:
            return config.db 
Example #17
Source File: postgres_database.py    From open-raadsinformatie with MIT License 5 votes vote down vote up
def __init__(self, serializer):
        self.serializer = serializer
        self.connection_string = 'postgresql://%s:%s@%s/%s' % (
                                    settings.POSTGRES_USERNAME,
                                    settings.POSTGRES_PASSWORD,
                                    settings.POSTGRES_HOST,
                                    settings.POSTGRES_DATABASE)
        self.engine = create_engine(self.connection_string, poolclass=StaticPool)
        self.Session = sessionmaker(bind=self.engine) 
Example #18
Source File: test_reflection.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def setup_bind(cls):
        if config.requirements.independent_connections.enabled:
            from sqlalchemy import pool
            return engines.testing_engine(
                options=dict(poolclass=pool.StaticPool))
        else:
            return config.db 
Example #19
Source File: test_reflection.py    From jbox with MIT License 5 votes vote down vote up
def setup_bind(cls):
        if config.requirements.independent_connections.enabled:
            from sqlalchemy import pool
            return engines.testing_engine(
                options=dict(poolclass=pool.StaticPool))
        else:
            return config.db 
Example #20
Source File: __init__.py    From stdm with GNU General Public License v2.0 4 votes vote down vote up
def construct_engine(engine, **opts):
    """.. versionadded:: 0.5.4

    Constructs and returns SQLAlchemy engine.

    Currently, there are 2 ways to pass create_engine options to :mod:`migrate.versioning.api` functions:

    :param engine: connection string or a existing engine
    :param engine_dict: python dictionary of options to pass to `create_engine`
    :param engine_arg_*: keyword parameters to pass to `create_engine` (evaluated with :func:`migrate.versioning.util.guess_obj_type`)
    :type engine_dict: dict
    :type engine: string or Engine instance
    :type engine_arg_*: string
    :returns: SQLAlchemy Engine

    .. note::

        keyword parameters override ``engine_dict`` values.

    """
    if isinstance(engine, Engine):
        return engine
    elif not isinstance(engine, six.string_types):
        raise ValueError("you need to pass either an existing engine or a database uri")

    # get options for create_engine
    if opts.get('engine_dict') and isinstance(opts['engine_dict'], dict):
        kwargs = opts['engine_dict']
    else:
        kwargs = dict()

    # DEPRECATED: handle echo the old way
    echo = asbool(opts.get('echo', False))
    if echo:
        warnings.warn('echo=True parameter is deprecated, pass '
            'engine_arg_echo=True or engine_dict={"echo": True}',
            exceptions.MigrateDeprecationWarning)
        kwargs['echo'] = echo

    # parse keyword arguments
    for key, value in six.iteritems(opts):
        if key.startswith('engine_arg_'):
            kwargs[key[11:]] = guess_obj_type(value)

    log.debug('Constructing engine')
    # TODO: return create_engine(engine, poolclass=StaticPool, **kwargs)
    # seems like 0.5.x branch does not work with engine.dispose and staticpool
    return create_engine(engine, **kwargs)