Пример #1
0
 def register_crypto_provider(self, name, provider):
     """
     Registers the crypto provider used to encrypt and decrypt document fields.
     :param name: The name of the provider.
     :param provider: The provider implementation. // reference LCB type?
     """
     _Base.register_crypto_provider(self, name, provider)
Пример #2
0
    def counter(self, key, delta=1, initial=None, ttl=0):
        """Increment or decrement the numeric value of an item.

        This method instructs the server to treat the item stored under
        the given key as a numeric counter.

        Counter operations require that the stored value
        exists as a string representation of a number (e.g. ``123``). If
        storing items using the :meth:`upsert` family of methods, and
        using the default :const:`couchbase_v2.FMT_JSON` then the value
        will conform to this constraint.

        :param string key: A key whose counter value is to be modified
        :param int delta: an amount by which the key should be modified.
            If the number is negative then this number will be
            *subtracted* from the current value.
        :param initial: The initial value for the key, if it does not
            exist. If the key does not exist, this value is used, and
            `delta` is ignored. If this parameter is `None` then no
            initial value is used
        :type initial: int or `None`
        :param int ttl: The lifetime for the key, after which it will
            expire
        :raise: :exc:`.NotFoundError` if the key does not exist on the
            bucket (and `initial` was `None`)
        :raise: :exc:`.DeltaBadvalError` if the key exists, but the
            existing value is not numeric
        :return: A :class:`.Result` object. The current value of the
            counter may be obtained by inspecting the return value's
            `value` attribute.

        Simple increment::

            rv = cb.counter("key")
            rv.value
            # 42

        Increment by 10::

            rv = cb.counter("key", delta=10)

        Decrement by 5::

            rv = cb.counter("key", delta=-5)

        Increment by 20, set initial value to 5 if it does not exist::

            rv = cb.counter("key", delta=20, initial=5)

        Increment three keys::

            kv = cb.counter_multi(["foo", "bar", "baz"])
            for key, result in kv.items():
                print "Key %s has value %d now" % (key, result.value)

        .. seealso:: :meth:`counter_multi`
        """
        return _Base.counter(self, key, delta=delta, initial=initial, ttl=ttl)
Пример #3
0
    def observe(self, key, master_only=False):
        """Return storage information for a key.

        It returns a :class:`.ValueResult` object with the ``value``
        field set to a list of :class:`~.ObserveInfo` objects. Each
        element in the list responds to the storage status for the key
        on the given node. The length of the list (and thus the number
        of :class:`~.ObserveInfo` objects) are equal to the number of
        online replicas plus the master for the given key.

        :param string key: The key to inspect
        :param bool master_only: Whether to only retrieve information
            from the master node.

        .. seealso:: :ref:`observe_info`
        """
        return _Base.observe(self, key, master_only=master_only)
Пример #4
0
    def unlock(self, key, cas):
        """Unlock a Locked Key in Couchbase.

        This unlocks an item previously locked by :meth:`lock`

        :param key: The key to unlock
        :param cas: The cas returned from :meth:`lock`'s
            :class:`.Result` object.

        See :meth:`lock` for an example.

        :raise: :exc:`.TemporaryFailError` if the CAS supplied does not
            match the CAS on the server (possibly because it was
            unlocked by previous call).

        .. seealso:: :meth:`lock` :meth:`unlock_multi`
        """
        return _Base.unlock(self, key, cas=cas)
Пример #5
0
 def encrypt_fields(self, document, fieldspec, prefix):
     """
     Encrypt a document using the registered encryption providers.
     :param document: The document body.
     :param fieldspec: A list of field specifications, each of which is
     a dictionary as follows:
         {
             'alg' : registered algorithm name,
             'kid' : key id to use to encrypt with,
             'name' : field name
         }
     :param prefix: Prefix for encrypted field names. Default is None.
     :return: Encrypted document.
     """
     json_encoded = json.dumps(document)
     encrypted_string = _Base.encrypt_fields(self, json_encoded, fieldspec,
                                             prefix)
     if not encrypted_string:
         raise couchbase_core.exceptions.CouchbaseError("Encryption failed")
     return json.loads(encrypted_string)
Пример #6
0
    def touch(self, key, ttl=0):
        """Update a key's expiration time

        :param string key: The key whose expiration time should be
            modified
        :param int ttl: The new expiration time. If the expiration time
            is `0` then the key never expires (and any existing
            expiration is removed)
        :return: :class:`.OperationResult`

        Update the expiration time of a key ::

            cb.upsert("key", ttl=100)
            # expires in 100 seconds
            cb.touch("key", ttl=0)
            # key should never expire now

        :raise: The same things that :meth:`get` does

        .. seealso:: :meth:`get` - which can be used to get *and* update the
            expiration, :meth:`touch_multi`
        """
        return _Base.touch(self, key, ttl=ttl)
Пример #7
0
    def remove(self, key, cas=0, quiet=None, persist_to=0, replicate_to=0):
        """Remove the key-value entry for a given key in Couchbase.

        :param key: A string which is the key to remove. The format and
            type of the key follows the same conventions as in
            :meth:`upsert`
        :type key: string, dict, or tuple/list

        :param int cas: The CAS to use for the removal operation.
            If specified, the key will only be removed from the server
            if it has the same CAS as specified. This is useful to
            remove a key only if its value has not been changed from the
            version currently visible to the client. If the CAS on the
            server does not match the one specified, an exception is
            thrown.
        :param boolean quiet:
            Follows the same semantics as `quiet` in :meth:`get`
        :param int persist_to: If set, wait for the item to be removed
            from the storage of at least these many nodes
        :param int replicate_to: If set, wait for the item to be removed
            from the cache of at least these many nodes
            (excluding the master)
        :raise: :exc:`.NotFoundError` if the key does not exist.
        :raise: :exc:`.KeyExistsError` if a CAS was specified, but
            the CAS on the server had changed
        :return: A :class:`~.Result` object.

        Simple remove::

            ok = cb.remove("key").success

        Don't complain if key does not exist::

            ok = cb.remove("key", quiet=True)

        Only remove if CAS matches our version::

            rv = cb.get("key")
            cb.remove("key", cas=rv.cas)

        Remove multiple keys::

            oks = cb.remove_multi(["key1", "key2", "key3"])

        Remove multiple keys with CAS::

            oks = cb.remove({
                "key1" : cas1,
                "key2" : cas2,
                "key3" : cas3
            })

        .. seealso:: :meth:`remove_multi`, :meth:`endure`
            for more information on the ``persist_to`` and
            ``replicate_to`` options.
        """
        return _Base.remove(self,
                            key,
                            cas=cas,
                            quiet=quiet,
                            persist_to=persist_to,
                            replicate_to=replicate_to)
Пример #8
0
    def lock(self, key, ttl=0):
        """Lock and retrieve a key-value entry in Couchbase.

        :param key: A string which is the key to lock.

        :param ttl: a TTL for which the lock should be valid.
            While the lock is active, attempts to access the key (via
            other :meth:`lock`, :meth:`upsert` or other mutation calls)
            will fail with an :exc:`.KeyExistsError`. Note that the
            value for this option is limited by the maximum allowable
            lock time determined by the server (currently, this is 30
            seconds). If passed a higher value, the server will silently
            lower this to its maximum limit.


        This function otherwise functions similarly to :meth:`get`;
        specifically, it will return the value upon success. Note the
        :attr:`~.Result.cas` value from the :class:`.Result` object.
        This will be needed to :meth:`unlock` the key.

        Note the lock will also be implicitly released if modified by
        one of the :meth:`upsert` family of functions when the valid CAS
        is supplied

        :raise: :exc:`.TemporaryFailError` if the key is already locked.
        :raise: See :meth:`get` for possible exceptions

        Lock a key ::

            rv = cb.lock("locked_key", ttl=5)
            # This key is now locked for the next 5 seconds.
            # attempts to access this key will fail until the lock
            # is released.

            # do important stuff...

            cb.unlock("locked_key", rv.cas)

        Lock a key, implicitly unlocking with :meth:`upsert` with CAS ::

            rv = self.cb.lock("locked_key", ttl=5)
            new_value = rv.value.upper()
            cb.upsert("locked_key", new_value, rv.cas)


        Poll and Lock ::

            rv = None
            begin_time = time.time()
            while time.time() - begin_time < 15:
                try:
                    rv = cb.lock("key", ttl=10)
                    break
                except TemporaryFailError:
                    print("Key is currently locked.. waiting")
                    time.sleep(1)

            if not rv:
                raise Exception("Waited too long..")

            # Do stuff..

            cb.unlock("key", rv.cas)


        .. seealso:: :meth:`get`, :meth:`lock_multi`, :meth:`unlock`
        """
        return _Base.lock(self, key, ttl=ttl)
Пример #9
0
    def get(
            self,  # type: Bucket
            key,  # type: str
            ttl=0,  # type: int
            quiet=None,  # type: bool
            replica=False,  # type: bool
            no_format=False  # type: bool
    ):
        # type: (...)->couchbase_v2.result.Result
        """Obtain an object stored in Couchbase by given key.

        :param string key: The key to fetch. The type of key is the same
            as mentioned in :meth:`upsert`

        :param int ttl: If specified, indicates that the key's expiration
            time should be *modified* when retrieving the value.

        :param boolean quiet: causes `get` to return None instead of
            raising an exception when the key is not found. It defaults
            to the value set by :attr:`~quiet` on the instance. In
            `quiet` mode, the error may still be obtained by inspecting
            the :attr:`~.Result.rc` attribute of the :class:`.Result`
            object, or checking :attr:`.Result.success`.

            Note that the default value is `None`, which means to use
            the :attr:`quiet`. If it is a boolean (i.e. `True` or
            `False`) it will override the `couchbase_v2.bucket.Bucket`-level
            :attr:`quiet` attribute.

        :param bool replica: Whether to fetch this key from a replica
            rather than querying the master server. This is primarily
            useful when operations with the master fail (possibly due to
            a configuration change). It should normally be used in an
            exception handler like so

            Using the ``replica`` option::

                try:
                    res = c.get("key", quiet=True) # suppress not-found errors
                catch CouchbaseError:
                    res = c.get("key", replica=True, quiet=True)

        :param bool no_format: If set to ``True``, then the value will
            always be delivered in the :class:`~couchbase_v2.result.Result`
            object as being of :data:`~couchbase_v2.FMT_BYTES`. This is a
            item-local equivalent of using the :attr:`data_passthrough`
            option

        :raise: :exc:`.NotFoundError` if the key does not exist
        :raise: :exc:`.CouchbaseNetworkError`
        :raise: :exc:`.ValueFormatError` if the value cannot be
            deserialized with chosen decoder, e.g. if you try to
            retreive an object stored with an unrecognized format
        :return: A :class:`~.Result` object

        Simple get::

            value = cb.get('key').value

        Get multiple values::

            cb.get_multi(['foo', 'bar'])
            # { 'foo' : <Result(...)>, 'bar' : <Result(...)> }

        Inspect the flags::

            rv = cb.get("key")
            value, flags, cas = rv.value, rv.flags, rv.cas

        Update the expiration time::

            rv = cb.get("key", ttl=10)
            # Expires in ten seconds

        .. seealso:: :meth:`get_multi`
        """

        return _Base.get(self,
                         key,
                         ttl=ttl,
                         quiet=quiet,
                         replica=replica,
                         no_format=no_format)
Пример #10
0
 def prepend(self, key, value, *args, **kwargs):
     return _Base.prepend(self, key, value, *args, **kwargs)
Пример #11
0
 def replace(self, key, value, *args, **kwargs):
     return _Base.replace(self, key, value, *args, **kwargs)
Пример #12
0
 def insert(self, key, value, *args, **kwargs):
     return _Base.insert(self, key, value, *args, **kwargs)
Пример #13
0
 def upsert(self, key, value, *args, **kwargs):
     return _Base.upsert(self, key, value, *args, **kwargs)
Пример #14
0
 def decrypt_fields_real(self, document, *args):
     json_decoded = json.dumps(document)
     decrypted_string = _Base.decrypt_fields(self, json_decoded, *args)
     if not decrypted_string:
         raise couchbase_core.exceptions.CouchbaseError("Decryption failed")
     return json.loads(decrypted_string)
Пример #15
0
 def unregister_crypto_provider(self, name):
     """
     Unregisters the crypto provider used to encrypt and decrypt document fields.
     :param name: The name of the provider.
     """
     _Base.unregister_crypto_provider(self, name)
Пример #16
0
 def append(self, key, value, *args, **kwargs):
     return _Base.append(self, key, value, *args, **kwargs)
Пример #17
0
 def add_bucket_creds(self, bucket, password):
     if not bucket or not password:
         raise ValueError('Bucket and password must be nonempty')
     return _Base._add_creds(self, bucket, password)