<commit_before>#!/usr/bin/env python
# Copyright (c) 2015 IBM. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Top level API module that maps to a Cloudant or CouchDB
client connection instance.
"""
import base64
import json
import posixpath
import requests
import sys

from .database import CloudantDatabase, CouchDatabase
from .changes import Feed
from .errors import CloudantException

_USER_AGENT = 'python-cloudant/{0} (Python, Version {1}.{2}.{3})'.format(
    sys.modules['cloudant'].__version__,
    sys.version_info[0],
    sys.version_info[1],
    sys.version_info[2])

class CouchDB(dict):
    """
    Encapsulates a CouchDB client, handling top level user API calls having to
    do with session and database management.

    Maintains a requests.Session for working with the
    instance specified in the constructor.

    Parameters can be passed in to control behavior:

    :param str user: Username used to connect to CouchDB.
    :param str auth_token: Authentication token used to connect to CouchDB.
    :param str url: URL for CouchDB server.
    :param str encoder: Optional json Encoder object used to encode
        documents for storage.  Defaults to json.JSONEncoder.
    """
    _DATABASE_CLASS = CouchDatabase

    def __init__(self, user, auth_token, **kwargs):
        super(CouchDB, self).__init__()
        self._cloudant_user = user
        self._cloudant_token = auth_token
        self._cloudant_session = None
        self.cloudant_url = kwargs.get('url')
        self._cloudant_user_header = None
        self.encoder = kwargs.get('encoder') or json.JSONEncoder
        self.r_session = None

    def connect(self):
        """
        Starts up an authentication session for the client using cookie
        authentication.
        """
        self.r_session = requests.Session()
        self.r_session.auth = (self._cloudant_user, self._cloudant_token)
        if self._cloudant_user_header is not None:
            self.r_session.headers.update(self._cloudant_user_header)
        self.session_login(self._cloudant_user, self._cloudant_token)
        self._cloudant_session = self.session()

    def disconnect(self):
        """
        Ends a client authentication session, performs a logout and a clean up.
        """
        self.session_logout()
        self.r_session = None
        self.clear()

    def session(self):
        """
        Retrieves information about the current login session
        to verify data related to sign in.

        :returns: Dictionary of session info for the current session.
        """
        sess_url = posixpath.join(self.cloudant_url, '_session')
        resp = self.r_session.get(sess_url)
        resp.raise_for_status()
        sess_data = resp.json()
        return sess_data

    def session_cookie(self):
        """
        Retrieves the current session cookie.

        :returns: Session cookie for the current session
        """
        return self.r_session.cookies.get('AuthSession')

    def session_login(self, user, passwd):
        """
        Performs a session login by posting the auth information
        to the _session endpoint.

        :param str user: Username used to connect.
        :param str passwd: Passcode used to connect.
        """
        sess_url = posixpath.join(self.cloudant_url, '_session')
        resp = self.r_session.post(
            sess_url,
            data={
                'name': user,
                'password': <PASSWORD>
            },
            headers={'Content-Type': 'application/x-www-form-urlencoded'}
        )
        resp.raise_for_status()

    def session_logout(self):
        """
        Performs a session logout and clears the current session by
        sending a delete request to the cloudant _session endpoint.
        """
        sess_url = posixpath.join(self.cloudant_url, '_session')
        resp = self.r_session.delete(
            sess_url
        )
        resp.raise_for_status()

    def basic_auth_str(self):
        """
        Composes a basic http auth string, suitable for use with the
        _replicator database, and other places that need it.

        :returns: Basic http authentication string
        """

        # TODO: I'm not a huge fan of doing basic auth -- need to
        # research and see if there's a better way to do this.
        hash_ = base64.urlsafe_b64encode("{username}:{password}".format(
            username=self._cloudant_user,
            password=self._cloudant_token
        ))
        return "Basic {0}".format(hash_)

    def all_dbs(self):
        """
        Retrieves a list of all database names for the current client.

        :returns: List of database names for the client
        """
        url = posixpath.join(self.cloudant_url, '_all_dbs')
        resp = self.r_session.get(url)
        resp.raise_for_status()
        return resp.json()
<commit_msg>Refactor account.py based on pylint findings.<commit_after>#!/usr/bin/env python
# Copyright (c) 2015 IBM. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Top level API module that maps to a Cloudant or CouchDB
client connection instance.
"""
import base64
import json
import posixpath
import sys
import requests

from .database import CloudantDatabase, CouchDatabase
from .changes import Feed
from .errors import CloudantException

_USER_AGENT = 'python-cloudant/{0} (Python, Version {1}.{2}.{3})'.format(
    sys.modules['cloudant'].__version__,
    sys.version_info[0],
    sys.version_info[1],
    sys.version_info[2])

class CouchDB(dict):
    """
    Encapsulates a CouchDB client, handling top level user API calls having to
    do with session and database management.

    Maintains a requests.Session for working with the
    instance specified in the constructor.

    Parameters can be passed in to control behavior:

    :param str user: Username used to connect to CouchDB.
    :param str auth_token: Authentication token used to connect to CouchDB.
    :param str url: URL for CouchDB server.
    :param str encoder: Optional json Encoder object used to encode
        documents for storage.  Defaults to json.JSONEncoder.
    """
    _DATABASE_CLASS = CouchDatabase

    def __init__(self, user, auth_token, **kwargs):
        super(CouchDB, self).__init__()
        self._cloudant_user = user
        self._cloudant_token = auth_token
        self._cloudant_session = None
        self.cloudant_url = kwargs.get('url')
        self._cloudant_user_header = None
        self.encoder = kwargs.get('encoder') or json.JSONEncoder
        self.r_session = None

    def connect(self):
        """
        Starts up an authentication session for the client using cookie
        authentication.
        """
        self.r_session = requests.Session()
        self.r_session.auth = (self._cloudant_user, self._cloudant_token)
        if self._cloudant_user_header is not None:
            self.r_session.headers.update(self._cloudant_user_header)
        self.session_login(self._cloudant_user, self._cloudant_token)
        self._cloudant_session = self.session()

    def disconnect(self):
        """
        Ends a client authentication session, performs a logout and a clean up.
        """
        self.session_logout()
        self.r_session = None
        self.clear()

    def session(self):
        """
        Retrieves information about the current login session
        to verify data related to sign in.

        :returns: Dictionary of session info for the current session.
        """
        sess_url = posixpath.join(self.cloudant_url, '_session')
        resp = self.r_session.get(sess_url)
        resp.raise_for_status()
        sess_data = resp.json()
        return sess_data

    def session_cookie(self):
        """
        Retrieves the current session cookie.

        :returns: Session cookie for the current session
        """
        return self.r_session.cookies.get('AuthSession')

    def session_login(self, user, passwd):
        """
        Performs a session login by posting the auth information
        to the _session endpoint.

        :param str user: Username used to connect.
        :param str passwd: Passcode used to connect.
        """
        sess_url = posixpath.join(self.cloudant_url, '_session')
        resp = self.r_session.post(
            sess_url,
            data={
                'name': user,
                'password': <PASSWORD>
            },
            headers={'Content-Type': 'application/x-www-form-urlencoded'}
        )
        resp.raise_for_status()

    def session_logout(self):
        """
        Performs a session logout and clears the current session by
        sending a delete request to the cloudant _session endpoint.
        """
        sess_url = posixpath.join(self.cloudant_url, '_session')
        resp = self.r_session.delete(
            sess_url
        )
        resp.raise_for_status()

    def basic_auth_str(self):
        """
        Composes a basic http auth string, suitable for use with the
        _replicator database, and other places that need it.

        :returns: Basic http authentication string
        """
        hash_ = base64.urlsafe_b64encode("{username}:{password}".format(
            username=self._cloudant_user,
            password=self._cloudant_token
        ))
        return "Basic {0}".format(hash_)

    def all_dbs(self):
        """
        Retrieves a list of all database names for the current client.

        :returns: List of database names for the client
        """
        url = posixpath.join(self.cloudant_url, '_all_dbs')
        resp = self.r_session.get(url)
        resp.raise_for_status()
        return resp.json()

{'fraction_non_alphanumeric': 0.08285019637179727, 'fraction_numerical': 0.004114456704694221, 'mean_word_length': 2.5367063492063493, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6476390', 'n_tokens_mistral': 2970, 'n_tokens_neox': 2909, 'n_words': 972}