當前位置: 首頁>>代碼示例>>Python>>正文


Python lock.Lock方法代碼示例

本文整理匯總了Python中redis.lock.Lock方法的典型用法代碼示例。如果您正苦於以下問題:Python lock.Lock方法的具體用法?Python lock.Lock怎麽用?Python lock.Lock使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在redis.lock的用法示例。


在下文中一共展示了lock.Lock方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: raise_or_lock

# 需要導入模塊: from redis import lock [as 別名]
# 或者: from redis.lock import Lock [as 別名]
def raise_or_lock(self, key, timeout):
        """
        Checks if the task is locked and raises an exception, else locks
        the task. By default, the tasks and the key expire after 60 minutes.
        (meaning it will not be executed and the lock will clear).
        """
        acquired = Lock(
            self.redis,
            key,
            timeout=timeout,
            blocking=self.blocking,
            blocking_timeout=self.blocking_timeout
        ).acquire()

        if not acquired:
            # Time remaining in milliseconds
            # https://redis.io/commands/pttl
            ttl = self.redis.pttl(key)
            raise AlreadyQueued(ttl / 1000.) 
開發者ID:cameronmaske,項目名稱:celery-once,代碼行數:21,代碼來源:redis.py

示例2: __init__

# 需要導入模塊: from redis import lock [as 別名]
# 或者: from redis.lock import Lock [as 別名]
def __init__(self, unique_id=uuid4(), redis_server=None, *args, **kwargs):
        """
        :param unique_id:
            An identifier for this auth object. Auth instances which wish to share tokens must use the same ID.
        :type unique_id:
            `unicode`
        :param redis_server:
            An instance of a Redis server, configured to talk to Redis.
        :type redis_server:
            :class:`Redis`
        """
        # pylint:disable=keyword-arg-before-vararg
        self._unique_id = unique_id
        self._redis_server = redis_server or StrictRedis()
        refresh_lock = Lock(redis=self._redis_server, name='{0}_lock'.format(self._unique_id))
        super(RedisManagedOAuth2Mixin, self).__init__(*args, refresh_lock=refresh_lock, **kwargs)
        if self._access_token is None:
            self._get_and_update_current_tokens() 
開發者ID:box,項目名稱:box-python-sdk,代碼行數:20,代碼來源:redis_managed_oauth2.py

示例3: _get_lock

# 需要導入模塊: from redis import lock [as 別名]
# 或者: from redis.lock import Lock [as 別名]
def _get_lock(lock_name, expiration):
    """
    Creates a new redis LuaLock

    Args:
        lock_name (str): The name of the lock
        expiration (datetime.datetime): The expiration datetime

    Returns:
        redis.lock.Lock: a redis lua-based lock
    """
    timeout = int((expiration - now_in_utc()).total_seconds())

    # this is a StrictRedis instance, we need this for the script installation that LuaLock uses
    redis = caches['redis'].client.get_client()
    # don't block acquiring the lock, the task will need to try again later
    return LuaLock(redis, lock_name, timeout=timeout, blocking=False, thread_local=False) 
開發者ID:mitodl,項目名稱:micromasters,代碼行數:19,代碼來源:locks.py

示例4: release_lock

# 需要導入模塊: from redis import lock [as 別名]
# 或者: from redis.lock import Lock [as 別名]
def release_lock(lock_name, token):
    """
    Release a lock

    Args:
        lock_name (str): The lock key in redis
        token (bytes): The unique id used

    Returns:
        bool: True if the lock was successfully released
    """
    # this is a StrictRedis instance, we need this for the script installation that LuaLock uses
    redis = caches['redis'].client.get_client()
    lock = LuaLock(redis, lock_name)
    try:
        lock.do_release(token)
    except LockError:
        # If the lock is expired we don't want to raise an error
        pass 
開發者ID:mitodl,項目名稱:micromasters,代碼行數:21,代碼來源:locks.py

示例5: test_delay_expired

# 需要導入模塊: from redis import lock [as 別名]
# 或者: from redis.lock import Lock [as 別名]
def test_delay_expired(redis):
    lock = RedisLock(redis, "qo_example_a-1", timeout=1)
    lock.acquire()

    assert redis.get("qo_example_a-1") is not None

    time.sleep(1)
    example.delay(1)

    assert redis.get("qo_example_a-1") is None 
開發者ID:cameronmaske,項目名稱:celery-once,代碼行數:12,代碼來源:test_redis.py

示例6: test_apply_async_expired

# 需要導入模塊: from redis import lock [as 別名]
# 或者: from redis.lock import Lock [as 別名]
def test_apply_async_expired(redis):
    lock = RedisLock(redis, "qo_example_a-1", timeout=1)
    lock.acquire()

    assert redis.get("qo_example_a-1") is not None

    time.sleep(1)
    example.apply_async(args=(1, ))

    assert redis.get("qo_example_a-1") is None 
開發者ID:cameronmaske,項目名稱:celery-once,代碼行數:12,代碼來源:test_redis.py

示例7: test_redis_raise_or_lock_locked

# 需要導入模塊: from redis import lock [as 別名]
# 或者: from redis.lock import Lock [as 別名]
def test_redis_raise_or_lock_locked(redis, backend):
    # Set to expire in 30 seconds!
    lock = RedisLock(redis, "test", timeout=30)
    lock.acquire()

    with pytest.raises(AlreadyQueued) as e:
        backend.raise_or_lock(key="test", timeout=60)

    assert e.value.countdown == approx(30.0, rel=0.1)
    assert "Expires in" in e.value.message 
開發者ID:cameronmaske,項目名稱:celery-once,代碼行數:12,代碼來源:test_redis.py

示例8: test_redis_raise_or_lock_locked_and_expired

# 需要導入模塊: from redis import lock [as 別名]
# 或者: from redis.lock import Lock [as 別名]
def test_redis_raise_or_lock_locked_and_expired(redis, backend):
    lock = RedisLock(redis, "test", timeout=1)
    lock.acquire()
    time.sleep(1)  # wait for lock to expire

    backend.raise_or_lock(key="test", timeout=60)
    assert redis.get("test") is not None 
開發者ID:cameronmaske,項目名稱:celery-once,代碼行數:9,代碼來源:test_redis.py

示例9: lock

# 需要導入模塊: from redis import lock [as 別名]
# 或者: from redis.lock import Lock [as 別名]
def lock(self, name, timeout=None, sleep=0.1, blocking_timeout=None,
             lock_class=None, thread_local=True):
        """
        Return a new Lock object using key ``name`` that mimics
        the behavior of threading.Lock.

        If specified, ``timeout`` indicates a maximum life for the lock.
        By default, it will remain locked until release() is called.

        ``sleep`` indicates the amount of time to sleep per loop iteration
        when the lock is in blocking mode and another client is currently
        holding the lock.

        ``blocking_timeout`` indicates the maximum amount of time in seconds to
        spend trying to acquire the lock. A value of ``None`` indicates
        continue trying forever. ``blocking_timeout`` can be specified as a
        float or integer, both representing the number of seconds to wait.

        ``lock_class`` forces the specified lock implementation.

        ``thread_local`` indicates whether the lock token is placed in
        thread-local storage. By default, the token is placed in thread local
        storage so that a thread only sees its token, not a token set by
        another thread. Consider the following timeline:

            time: 0, thread-1 acquires `my-lock`, with a timeout of 5 seconds.
                     thread-1 sets the token to "abc"
            time: 1, thread-2 blocks trying to acquire `my-lock` using the
                     Lock instance.
            time: 5, thread-1 has not yet completed. redis expires the lock
                     key.
            time: 5, thread-2 acquired `my-lock` now that it's available.
                     thread-2 sets the token to "xyz"
            time: 6, thread-1 finishes its work and calls release(). if the
                     token is *not* stored in thread local storage, then
                     thread-1 would see the token value as "xyz" and would be
                     able to successfully release the thread-2's lock.

        In some use cases it's necessary to disable thread local storage. For
        example, if you have code where one thread acquires a lock and passes
        that lock instance to a worker thread to release later. If thread
        local storage isn't disabled in this case, the worker thread won't see
        the token set by the thread that acquired the lock. Our assumption
        is that these cases aren't common and as such default to using
        thread local storage.        """
        if lock_class is None:
            if self._use_lua_lock is None:
                # the first time .lock() is called, determine if we can use
                # Lua by attempting to register the necessary scripts
                try:
                    LuaLock.register_scripts(self)
                    self._use_lua_lock = True
                except ResponseError:
                    self._use_lua_lock = False
            lock_class = self._use_lua_lock and LuaLock or Lock
        return lock_class(self, name, timeout=timeout, sleep=sleep,
                          blocking_timeout=blocking_timeout,
                          thread_local=thread_local) 
開發者ID:leancloud,項目名稱:satori,代碼行數:60,代碼來源:client.py

示例10: lock

# 需要導入模塊: from redis import lock [as 別名]
# 或者: from redis.lock import Lock [as 別名]
def lock(self, name, timeout=None, sleep=0.1, blocking_timeout=None,
             lock_class=None, thread_local=True):
        """
        Return a new Lock object using key ``name`` that mimics
        the behavior of threading.Lock.

        If specified, ``timeout`` indicates a maximum life for the lock.
        By default, it will remain locked until release() is called.

        ``sleep`` indicates the amount of time to sleep per loop iteration
        when the lock is in blocking mode and another client is currently
        holding the lock.

        ``blocking_timeout`` indicates the maximum amount of time in seconds to
        spend trying to acquire the lock. A value of ``None`` indicates
        continue trying forever. ``blocking_timeout`` can be specified as a
        float or integer, both representing the number of seconds to wait.

        ``lock_class`` forces the specified lock implementation.

        ``thread_local`` indicates whether the lock token is placed in
        thread-local storage. By default, the token is placed in thread local
        storage so that a thread only sees its token, not a token set by
        another thread. Consider the following timeline:

            time: 0, thread-1 acquires `my-lock`, with a timeout of 5 seconds.
                     thread-1 sets the token to "abc"
            time: 1, thread-2 blocks trying to acquire `my-lock` using the
                     Lock instance.
            time: 5, thread-1 has not yet completed. redis expires the lock
                     key.
            time: 5, thread-2 acquired `my-lock` now that it's available.
                     thread-2 sets the token to "xyz"
            time: 6, thread-1 finishes its work and calls release(). if the
                     token is *not* stored in thread local storage, then
                     thread-1 would see the token value as "xyz" and would be
                     able to successfully release the thread-2's lock.

        In some use cases it's necessary to disable thread local storage. For
        example, if you have code where one thread acquires a lock and passes
        that lock instance to a worker thread to release later. If thread
        local storage isn't disabled in this case, the worker thread won't see
        the token set by the thread that acquired the lock. Our assumption
        is that these cases aren't common and as such default to using
        thread local storage.        """
        if lock_class is None:
            lock_class = Lock
        return lock_class(self, name, timeout=timeout, sleep=sleep,
                          blocking_timeout=blocking_timeout,
                          thread_local=thread_local) 
開發者ID:wistbean,項目名稱:learn_python3_spider,代碼行數:52,代碼來源:client.py


注:本文中的redis.lock.Lock方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。