def __init__(self, **kwargs):
        """Connection to a bucket.

        Normally it's initialized through :meth:`couchbase.Couchbase.connect`

        See :meth:`couchbase.Couchbase.connect` for constructor options
        """

        bucket = kwargs.get('bucket', None)
        host = kwargs.get('host', 'localhost')
        username = kwargs.get('username', None)
        password = kwargs.get('password', None)

        # We don't pass this to the actual constructor
        port = kwargs.pop('port', 8091)
        _no_connect_exceptions = kwargs.pop('_no_connect_exceptions', False)

        if not bucket:
            raise exceptions.ArgumentError("A bucket name must be given")

        kwargs['host'] = self._gen_host_string(host, port)
        kwargs['bucket'] = bucket

        if password and not username:
            kwargs['username'] = bucket

        # Internal parameters
        kwargs['_errors'] = deque(maxlen=1000)

        try:
            super(Connection, self).__init__(**kwargs)

        except exceptions.CouchbaseError as e:
            if not _no_connect_exceptions:
                raise
Beispiel #2
0
    def __init__(self, **kwargs):
        """Connection to a bucket.

        Normally it's initialized through :meth:`couchbase.Couchbase.connect`

        See :meth:`couchbase.Couchbase.connect` for constructor options
        """

        bucket = kwargs.get('bucket', None)
        host = kwargs.get('host', 'localhost')
        username = kwargs.get('username', None)
        password = kwargs.get('password', None)
        conncache = kwargs.get('conncache', None)
        quiet = kwargs.get('quiet', False)
        unlock_gil = kwargs.get('unlock_gil', False)
        timeout = kwargs.get('timeout', 2.5)
        transcoder = kwargs.get('transcoder', None)

        # We don't pass this to the actual constructor
        port = kwargs.pop('port', 8091)
        _no_connect_exceptions = kwargs.pop('_no_connect_exceptions', False)

        if not bucket:
            raise exceptions.ArgumentError("A bucket name must be given")

        if isinstance(host, (tuple, list)):
            hosts_tmp = []
            for curhost in host:
                cur_hname = None
                cur_hport = None
                if isinstance(curhost, (list, tuple)):
                    cur_hname, cur_hport = curhost
                else:
                    cur_hname = curhost
                    cur_hport = port

                hosts_tmp.append("{0}:{1}".format(cur_hname, cur_hport))

            host = ";".join(hosts_tmp)
        else:
            host = "{0}:{1}".format(host, port)

        kwargs['host'] = host
        kwargs['bucket'] = bucket

        if password and not username:
            kwargs['username'] = bucket

        kwargs['_errors'] = deque(maxlen=1000)
        kwargs['_flags'] = 0

        try:
            super(Connection, self).__init__(**kwargs)

        except exceptions.CouchbaseError as e:
            if not _no_connect_exceptions:
                raise
Beispiel #3
0
    def http_request(self,
                     path,
                     method='GET',
                     content=None,
                     content_type="application/json",
                     response_format=FMT_JSON):
        """
        Perform an administrative HTTP request. This request is sent out to
        the administrative API interface (i.e. the "Management/REST API")
        of the cluster.

        See <LINK?> for a list of available comments.

        Note that this is a fairly low level function. This class will with
        time contain more and more wrapper methods for common tasks such
        as bucket creation or node allocation, and this method should
        mostly be used if a wrapper is not available.

        :param string path: The path portion (not including the host) of the
          rest call to perform. This should also include any encoded arguments.

        :param string method: This is the HTTP method to perform. Currently
          supported values are `GET`, `POST`, `PUT`, and `DELETE`

        :param bytes content: Content to be passed along in the request body.
          This is only applicable on `PUT` and `POST` methods.

        :param string content_type: Value for the HTTP ``Content-Type`` header.
          Currently this is ``application-json``, and should probably not be
          set to something else.

        :param int response_format:
          Hint about how to format the response. This goes into the
          :attr:`~couchbase.libcouchbase.HttpResult.value` field of the
          :class:`~couchbase.libcouchbase.HttpResult` object. The default is
          :const:`~couchbase.libcouchbase.FMT_JSON`.

          Note that if the conversion fails, the content will be returned as
          ``bytes``

        :raise:

          :exc:`couchbase.exceptions.ArgumentError` if the method supplied was
            incorrect

          :exc:`couchbase.exceptions.ConnectError` if there was a problem
            establishing a connection.

          :exc:`couchbase.exceptions.HTTPError` if the server responded with a
            negative reply

        :return: a :class:`~couchbase.libcouchbase.HttpResult` object.
        """
        imeth = None
        try:
            imeth = METHMAP[method]
        except KeyError:
            raise E.ArgumentError({
                "message": "unknown HTTP method",
                "objextra": method
            })

        return self._http_request(type=LCB.LCB_HTTP_TYPE_MANAGEMENT,
                                  path=path,
                                  method=imeth,
                                  content_type=content_type,
                                  post_data=content,
                                  response_format=response_format)
Beispiel #4
0
    def user_upsert(self,
                    domain,
                    userid,
                    password=None,
                    roles=None,
                    name=None):
        """
        Upsert a user in the cluster

        :param AuthDomain domain: The authentication domain for the user.
        :param userid: The user ID
        :param password: The user password
        :param roles: A list of roles. A role can either be a simple string,
            or a list of `(role, bucket)` pairs.
        :param name: Human-readable name
        :raise: :exc:`couchbase.exceptions.HTTPError` if the request fails.
        :return: :class:`~.HttpResult`

        Creating a new read-only admin user ::

            adm.upsert_user(AuthDomain.Local, 'mark', 's3cr3t', ['ro_admin'])

        An example of using more complex roles ::

            adm.upsert_user(AuthDomain.Local, 'mark', 's3cr3t',
                                              [('data_reader', '*'),
                                               ('data_writer', 'inbox')])


        .. warning::

           Due to the asynchronous nature of Couchbase management APIs, it may
           take a few moments for the new user settings to take effect.
        """
        if not roles or not isinstance(roles, list):
            raise E.ArgumentError("Roles must be a non-empty list")

        if password and domain == AuthDomain.External:
            raise E.ArgumentError("External domains must not have passwords")
        tmplist = []
        for role in roles:
            if isinstance(role, basestring):
                tmplist.append(role)
            else:
                tmplist.append('{0}[{1}]'.format(*role))

        role_string = ','.join(tmplist)
        params = {
            'roles': role_string,
        }

        if password:
            params['password'] = password
        if name:
            params['name'] = name

        form = self._mk_formstr(params)
        path = self._get_management_path(domain, userid)
        return self.http_request(
            path=path,
            method='PUT',
            content_type='application/x-www-form-urlencoded',
            content=form)