Exemplo n.º 1
0
    def transaction(self, autocommit=True, rollback=False):
        with self.connect() as conn:
            logger.debug('[%s] Starting transaction', get_ident())
            trans = conn.begin_nested()
            try:

                # Yield the connection object, as it is
                # needed for actually running queries.
                # The transaction will be automatically committed upon
                # success, or rolled back if an exception is raised.
                yield conn

                if autocommit:
                    logger.debug('[%s] Committing transaction', get_ident())
                    trans.commit()

                if rollback:
                    logger.debug('[%s] Rolling back transaction', get_ident())
                    trans.rollback()

            except Exception:
                logger.debug('[%s] Rolling back transaction (exception)',
                             get_ident())
                trans.rollback()
                raise
Exemplo n.º 2
0
 def _new_connection_context(self):
     logger.debug('[%s] Getting new connection from pool', get_ident())
     conn = self._engine.connect()
     self._local.connection = conn
     yield conn
     logger.debug('[%s] Releasing connection to pool', get_ident())
     self._local.connection = None
     release_local(self._local)
     conn.close()
Exemplo n.º 3
0
def test_local_stack():
    ident = local.get_ident()

    ls = local.LocalStack()
    assert ident not in ls._local.__storage__
    assert ls.top is None
    ls.push(42)
    assert ident in ls._local.__storage__
    assert ls.top == 42
    ls.push(23)
    assert ls.top == 23
    ls.pop()
    assert ls.top == 42
    ls.pop()
    assert ls.top is None
    assert ls.pop() is None
    assert ls.pop() is None

    proxy = ls()
    ls.push([1, 2])
    assert proxy == [1, 2]
    ls.push((1, 2))
    assert proxy == (1, 2)
    ls.pop()
    ls.pop()
    assert repr(proxy) == '<LocalProxy unbound>'

    assert ident not in ls._local.__storage__
Exemplo n.º 4
0
def test_local_stack():
    ident = local.get_ident()

    ls = local.LocalStack()
    assert ident not in ls._local.__storage__
    assert ls.top is None
    ls.push(42)
    assert ident in ls._local.__storage__
    assert ls.top == 42
    ls.push(23)
    assert ls.top == 23
    ls.pop()
    assert ls.top == 42
    ls.pop()
    assert ls.top is None
    assert ls.pop() is None
    assert ls.pop() is None

    proxy = ls()
    ls.push([1, 2])
    assert proxy == [1, 2]
    ls.push((1, 2))
    assert proxy == (1, 2)
    ls.pop()
    ls.pop()
    assert repr(proxy) == '<LocalProxy unbound>'

    assert ident not in ls._local.__storage__
Exemplo n.º 5
0
 def get_parent_id(cls):
     '''
     Retorna el padre del id del proceso actual, tal cual recibe
     `register_child` por parámetro.
     '''
     current = get_ident()
     return cls._threads.get(current, current)
Exemplo n.º 6
0
def thread_local():
    """A context manager for safely creating and deleting the thread-local
    necessary for :class:`~cosmic.globals.ThreadLocalDict`.

    .. code::

        g = ThreadLocalDict()

        with thread_local():
            # g is only accessible within this context
            g['foo'] = 1

    """
    ident = get_ident()
    storage[ident] = local = {}
    yield local
    del storage[ident]
Exemplo n.º 7
0
def git_cat_file(app_or_request, object_name):
    app = getattr(app_or_request, 'app', app_or_request)
    me = get_ident()

    if not hasattr(app, '_git_cat_processes'):
        app._git_cat_processes = {}
    proc = app._git_cat_processes

    if (me not in proc) or (proc[me].poll() is not None):
        proc[me] = SP.Popen(['git', 'cat-file', '--batch'],
                            stdin=SP.PIPE, stdout=SP.PIPE,
                            cwd=app.settings.git_dir)

    proc[me].stdin.write(object_name + '\n')
    result = proc[me].stdout.readline()
    if result.endswith('missing\n'): return None
    hash, type, size = result.split()
    size = int(size)
    content = proc[me].stdout.read(size + 1)[:-1]
    return (hash, type, size, content)
Exemplo n.º 8
0
def git_cat_file(app_or_request, object_name):
    app = getattr(app_or_request, 'app', app_or_request)
    me = get_ident()

    if not hasattr(app, '_git_cat_processes'):
        app._git_cat_processes = {}
    proc = app._git_cat_processes

    if (me not in proc) or (proc[me].poll() is not None):
        proc[me] = SP.Popen(['git', 'cat-file', '--batch'],
                            stdin=SP.PIPE,
                            stdout=SP.PIPE,
                            cwd=app.settings.git_dir)

    proc[me].stdin.write(object_name + '\n')
    result = proc[me].stdout.readline()
    if result.endswith('missing\n'): return None
    hash, type, size = result.split()
    size = int(size)
    content = proc[me].stdout.read(size + 1)[:-1]
    return (hash, type, size, content)
Exemplo n.º 9
0
def ensure_thread_local():
    if get_ident() in storage:
        yield
    else:
        with thread_local():
            yield
Exemplo n.º 10
0
 def data(self):
     try:
         local = storage[get_ident()]
     except KeyError:
         raise ThreadLocalMissing()
     return local.setdefault(id(self), {})
Exemplo n.º 11
0
 def __repr__(self):
     if get_ident() in storage:
         return repr(self.data)
     else:
         return '<unbound ThreadLocalDict>'
Exemplo n.º 12
0
 def unregister_child(cls):
     '''
     Borra el proceso actual del listado de hijos.
     '''
     del cls._threads[get_ident()]
Exemplo n.º 13
0
 def register_child(cls, parent_id):
     '''
     Registra el proceso actual como hijo del padre con id dado, para
     acceder a su contexto.
     '''
     cls._threads[get_ident()] = parent_id
Exemplo n.º 14
0
 def _reuse_connection_context(self):
     logger.debug('[%s] Reusing connection', get_ident())
     yield self._local.connection
     logger.debug('[%s] Finished using connection', get_ident())