Python requests.auth() Examples

The following are 30 code examples for showing how to use requests.auth(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module requests , or try the search function .

Example 1
Project: pywren-ibm-cloud   Author: pywren   File: infinispan.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, infinispan_config, **kwargs):
        logger.debug("Creating Infinispan client")
        self.infinispan_config = infinispan_config
        self.is_pywren_function = is_pywren_function()
        self.basicAuth = HTTPBasicAuth(infinispan_config.get('username'),
                                       infinispan_config.get('password'))
        self.endpoint = infinispan_config.get('endpoint')
        self.cache_manager = infinispan_config.get('cache_manager', 'default')
        self.cache_name = self.__generate_cache_name(kwargs['bucket'], kwargs['executor_id'])
        self.infinispan_client = requests.session()

        self.__is_server_version_supported()

        res = self.infinispan_client.head(self.endpoint + '/rest/v2/caches/' + self.cache_name,
                                          auth=self.basicAuth)
        if res.status_code == 404:
            logger.debug('going to create new Infinispan cache {}'.format(self.cache_name))
            res = self.infinispan_client.post(self.endpoint + '/rest/v2/caches/' + self.cache_name + '?template=org.infinispan.DIST_SYNC')
            logger.debug('New Infinispan cache {} created with status {}'.format(self.cache_name, res.status_code))

        logger.debug("Infinispan client created successfully") 
Example 2
Project: rets   Author: opendoor-labs   File: client.py    License: MIT License 6 votes vote down vote up
def _http_request(self, url: str, headers: dict = None, payload: dict = None) -> Response:
        if not self._session:
            raise RetsClientError('Session not instantiated. Call .login() first')

        request_headers = {
            **(headers or {}),
            'User-Agent': self.user_agent,
            'RETS-Version': self.rets_version,
            'RETS-UA-Authorization': self._rets_ua_authorization()
        }

        if self._use_get_method:
            if payload:
                url = '%s?%s' % (url, urlencode(payload))
            response = self._session.get(url, auth=self._http_auth, headers=request_headers)
        else:
            response = self._session.post(url, auth=self._http_auth, headers=request_headers, data=payload)

        response.raise_for_status()
        self._rets_session_id = self._session.cookies.get('RETS-Session-ID', '')
        return response 
Example 3
Project: prometheus_couchbase_exporter   Author: brunopsoares   File: __init__.py    License: MIT License 6 votes vote down vote up
def _request_data(self, url):
        try:
            if set(["COUCHBASE_USERNAME","COUCHBASE_PASSWORD"]).issubset(os.environ):
                response = requests.get(url, auth=HTTPBasicAuth(os.environ["COUCHBASE_USERNAME"], os.environ["COUCHBASE_PASSWORD"]))
            else:
                response = requests.get(url)
        except Exception as e:
            print('Failed to establish a new connection. Is {0} correct?'.format(self.BASE_URL))
            sys.exit(1)

        if response.status_code != requests.codes.ok:
            print('Response Status ({0}): {1}'.format(response.status_code, response.text))
            sys.exit(1)

        result = response.json()
        return result 
Example 4
Project: pyspider   Author: binux   File: couchdbbase.py    License: Apache License 2.0 6 votes vote down vote up
def _list_project(self):
        self._last_update_projects = time.time()
        self.projects = set()
        if self.collection_prefix:
            prefix = "%s." % self.collection_prefix
        else:
            prefix = ''

        url = self.base_url + "_all_dbs"
        res = requests.get(url,
                           data=json.dumps({}),
                           headers={"Content-Type": "application/json"},
                           auth=HTTPBasicAuth(self.username, self.password)).json()
        for each in res:
            if each.startswith('_'):
                continue
            if each.startswith(self.database):
                self.projects.add(each[len(self.database)+1+len(prefix):]) 
Example 5
Project: pyspider   Author: binux   File: projectdb.py    License: Apache License 2.0 6 votes vote down vote up
def get(self, name, fields=None):
        if fields is None:
            fields = []
        payload = {
            "selector": {"name": name},
            "fields": fields,
            "limit": 1,
            "use_index": self.index
        }
        url = self.url + "_find"
        res = requests.post(url,
                            data=json.dumps(payload),
                            headers={"Content-Type": "application/json"},
                            auth=HTTPBasicAuth(self.username, self.password)).json()
        if len(res['docs']) == 0:
            return None
        return self._default_fields(res['docs'][0]) 
Example 6
Project: pyspider   Author: binux   File: taskdb.py    License: Apache License 2.0 6 votes vote down vote up
def _create_project(self, project):
        collection_name = self._get_collection_name(project)
        self.create_database(collection_name)
        # create index
        payload = {
            'index': {
                'fields': ['status', 'taskid']
            },
            'name': collection_name
        }
        res = requests.post(self.base_url + collection_name + "/_index",
                            data=json.dumps(payload),
                            headers={"Content-Type": "application/json"},
                            auth=HTTPBasicAuth(self.username, self.password)).json()
        self.index = res['id']
        self._list_project() 
Example 7
Project: watchdog   Author: flipkart-incubator   File: HTTP.py    License: Apache License 2.0 6 votes vote down vote up
def setAuthMethod(self, auth_method):
        "Set the authentication method to use for the requests."
        self.auth_method = auth_method
        if len(self.auth_credentials) == 2:
            username, password = self.auth_credentials
            if self.auth_method == "basic":
                from requests.auth import HTTPBasicAuth
                self.h.auth = HTTPBasicAuth(username, password)
            elif self.auth_method == "digest":
                from requests.auth import HTTPDigestAuth
                self.h.auth = HTTPDigestAuth(username, password)
            elif self.auth_method == "ntlm":
                from requests_ntlm import HttpNtlmAuth
                self.h.auth = HttpNtlmAuth(username, password)
        elif self.auth_method == "kerberos":
            from requests_kerberos import HTTPKerberosAuth
            self.h.auth = HTTPKerberosAuth() 
Example 8
Project: watchdog   Author: flipkart-incubator   File: HTTP.py    License: Apache License 2.0 6 votes vote down vote up
def setAuthMethod(self, auth_method):
        "Set the authentication method to use for the requests."
        self.auth_method = auth_method
        if len(self.auth_credentials) == 2:
            username, password = self.auth_credentials
            if self.auth_method == "basic":
                from requests.auth import HTTPBasicAuth
                self.h.auth = HTTPBasicAuth(username, password)
            elif self.auth_method == "digest":
                from requests.auth import HTTPDigestAuth
                self.h.auth = HTTPDigestAuth(username, password)
            elif self.auth_method == "ntlm":
                from requests_ntlm import HttpNtlmAuth
                self.h.auth = HttpNtlmAuth(username, password)
        elif self.auth_method == "kerberos":
            from requests_kerberos import HTTPKerberosAuth
            self.h.auth = HTTPKerberosAuth() 
Example 9
Project: python_course   Author: ktbyers   File: rpc_client.py    License: Apache License 2.0 6 votes vote down vote up
def send_request(self, commands, method='cli', timeout=30):
        """
        Send a HTTP/HTTPS request containing the JSON-RPC payload, headers, and username/password.

        method = cli for structured data response
        method = cli_ascii for a string response (still in JSON-RPC dict, but in 'msg' key)
        """
        timeout = int(timeout)
        payload_list = self._build_payload(commands, method)
        response = requests.post(self.url,
                                 timeout=timeout,
                                 data=json.dumps(payload_list),
                                 headers=self.headers,
                                 auth=HTTPBasicAuth(self.username, self.password),
                                 verify=self.verify)
        response_list = json.loads(response.text)

        if isinstance(response_list, dict):
            response_list = [response_list]

        # Add the 'command' that was executed to the response dictionary
        for i, response_dict in enumerate(response_list):
            response_dict['command'] = commands[i]
        return response_list 
Example 10
Project: accesslink-example-python   Author: polarofficial   File: oauth2.py    License: MIT License 6 votes vote down vote up
def __build_auth_kwargs(self, **kwargs):
        """Setup authentication for requests

        If `access_token` is given, it is used in Authentication header.
        Otherwise basic auth is used with the client credentials.
        """

        if "access_token" in kwargs:
            headers = self.get_auth_headers(kwargs["access_token"])

            if "headers" in kwargs:
                headers.update(kwargs["headers"])

            kwargs["headers"] = headers
            del kwargs["access_token"]
        elif "auth" not in kwargs:
            kwargs["auth"] = HTTPBasicAuth(self.client_id, self.client_secret)

        return kwargs 
Example 11
Project: piapi   Author: HSRNetwork   File: piapi.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, url, username, password, verify=True, virtual_domain=None):
        """
        Constructor of the PIAPI class.
        """
        self.base_url = six.moves.urllib.parse.urljoin(url, DEFAULT_API_URI)
        self.verify = verify
        self.virtual_domain = virtual_domain
        self.cache = {}  # Caching is used for data resource with keys as checksum of resource's name+params from the request

        # Service resources holds all possible service resources with keys as service name
        # and hold the HTTP method + full url to request the service.
        self._service_resources = {}
        # Data resources holds all possible data resources with key as service name and value as full url access.
        self._data_resources = {}

        self.session = requests.Session()
        self.session.auth = requests.auth.HTTPBasicAuth(username, password)

        # Disable HTTP keep_alive as advised by the API documentation
        self.session.headers['connection'] = 'close'

        # Don't print warning message from request if not wanted
        if not self.verify:
            import warnings
            warnings.filterwarnings("ignore") 
Example 12
Project: pylips   Author: eslavnov   File: pylips.py    License: MIT License 6 votes vote down vote up
def pair_confirm(self, data, err_count=0):
        while err_count < 10:
            if err_count > 0:
                print("Resending pair confirm request")
            try:
                # print(data)
                r = session.post("https://" + str(self.config["TV"]["host"]) +":1926/"+str(self.config["TV"]["apiv"])+"/pair/grant", json=data, verify=False, auth=HTTPDigestAuth(self.config["TV"]["user"], self.config["TV"]["pass"]),timeout=2)
                print (r.request.headers)
                print (r.request.body)
                print("Username for subsequent calls is: " + str(self.config["TV"]["user"]))
                print("Password for subsequent calls is: " + str(self.config["TV"]["pass"]))
                return print("The credentials are saved in the settings.ini file.")
            except Exception:
                # try again
                err_count += 1
                continue
        else:
            return print("The API is unreachable. Try restarting your TV and pairing again")

    # sends a general GET request 
Example 13
Project: pylips   Author: eslavnov   File: pylips.py    License: MIT License 6 votes vote down vote up
def get(self, path, verbose=True, err_count=0):
        while err_count < int(self.config["DEFAULT"]["num_retries"]):
            if verbose:
                print("Sending GET request to", str(self.config["TV"]["protocol"]) + str(self.config["TV"]["host"]) + ":" + str(self.config["TV"]["port"]) + "/" + str(self.config["TV"]["apiv"]) + "/" + str(path))
            try:
                r = session.get(str(self.config["TV"]["protocol"]) + str(self.config["TV"]["host"]) + ":" + str(self.config["TV"]["port"]) + "/" + str(self.config["TV"]["apiv"]) + "/" + str(path), verify=False, auth=HTTPDigestAuth(str(self.config["TV"]["user"]), str(self.config["TV"]["pass"])), timeout=2)
            except Exception:
                err_count += 1
                continue
            if verbose:
                print("Request sent!")
            if len(r.text) > 0:
                print(r.text)
                return r.text
        else:
            if self.config["DEFAULT"]["mqtt_listen"].lower()=="true":
                self.mqtt_update_status({"powerstate":"Off", "volume":None, "muted":False, "cur_app":None, "ambilight":None, "ambihue":False})
            return json.dumps({"error":"Can not reach the API"})

    # sends a general POST request 
Example 14
Project: full-stack-fastapi-couchbase   Author: tiangolo   File: couchbase_utils.py    License: MIT License 6 votes vote down vote up
def setup_memory_quota(
    *,
    cluster_url,
    username,
    password,
    memory_quota_mb="256",
    index_memory_quota_mb="256",
    fts_memory_quota_mb="256",
):
    auth = HTTPBasicAuth(username, password)
    url = f"{cluster_url}/pools/default"
    r = requests.post(
        url,
        data={
            "memoryQuota": memory_quota_mb,
            "indexMemoryQuota": index_memory_quota_mb,
            "ftsMemoryQuota": fts_memory_quota_mb,
        },
        auth=auth,
    )
    return r.status_code == 200 
Example 15
Project: insightconnect-plugins   Author: rapid7   File: connection.py    License: MIT License 6 votes vote down vote up
def test(self):
        auth = HTTPBasicAuth(username=self.username,
                             password=self.password)

        response = requests.get(self.url, auth=auth)

        # https://developer.atlassian.com/cloud/jira/platform/rest/v2/?utm_source=%2Fcloud%2Fjira%2Fplatform%2Frest%2F&utm_medium=302#error-responses
        if response.status_code == 200:
            return True
        elif response.status_code == 401:
            raise ConnectionTestException(preset=ConnectionTestException.Preset.USERNAME_PASSWORD)
        elif response.status_code == 404:
            raise ConnectionTestException(cause=f"Unable to reach Jira instance at: {self.url}.",
                                          assistance="Verify the Jira server at the URL configured in your plugin "
                                                     "connection is correct.")
        else:
            self.logger.error(ConnectionTestException(cause=f"Unhandled error occurred: {response.content}"))
            raise ConnectionTestException(cause=f"Unhandled error occurred.",
                                          assistance=response.content) 
Example 16
Project: insightconnect-plugins   Author: rapid7   File: connection.py    License: MIT License 6 votes vote down vote up
def connect(self, params):
        self.logger.info("Connect: Connecting...")

        api_route = "api/now/"
        incident_table = "incident"

        base_url = params.get(Input.URL, "")

        if not base_url.endswith('/'):
            base_url = f'{base_url}/'

        username = params[Input.CLIENT_LOGIN].get("username", "")
        password = params[Input.CLIENT_LOGIN].get("password", "")

        self.session = requests.Session()
        self.session.auth = HTTPBasicAuth(username, password)
        self.request = RequestHelper(self.session, self.logger)

        self.table_url = f'{base_url}{api_route}table/'
        self.incident_url = f'{self.table_url}{incident_table}'
        self.attachment_url = f'{base_url}{api_route}attachment'
        self.timeout = params.get("timeout", 30) 
Example 17
Project: sdn-loadbalancing   Author: nayanseth   File: odl.py    License: GNU General Public License v3.0 6 votes vote down vote up
def getStats(data):
	print "\nCost Computation....\n"
	global cost
	txRate = 0
	for i in data["node-connector"]:
		tx = int(i["opendaylight-port-statistics:flow-capable-node-connector-statistics"]["packets"]["transmitted"])
		rx = int(i["opendaylight-port-statistics:flow-capable-node-connector-statistics"]["packets"]["received"])
		txRate = tx + rx
		#print txRate

	time.sleep(2)

	response = requests.get(stats, auth=HTTPBasicAuth('admin', 'admin'))
	tempJSON = ""
	if(response.ok):
		tempJSON = json.loads(response.content)

	for i in tempJSON["node-connector"]:
		tx = int(i["opendaylight-port-statistics:flow-capable-node-connector-statistics"]["packets"]["transmitted"])
		rx = int(i["opendaylight-port-statistics:flow-capable-node-connector-statistics"]["packets"]["received"])
		cost = cost + tx + rx - txRate

	#cost = cost + txRate
	#print cost 
Example 18
Project: openeo-python-client   Author: Open-EO   File: connection.py    License: Apache License 2.0 6 votes vote down vote up
def _authenticate_oidc(self, authenticator: OidcAuthenticator, provider_id: str) -> 'Connection':
        """
        Authenticate through OIDC and set up bearer token (based on OIDC access_token) for further requests.
        """
        tokens = authenticator.get_tokens()
        _log.info("Obtained tokens: {t}".format(t=[k for k, v in tokens._asdict().items() if v]))
        if tokens.refresh_token:
            # TODO: option to not store refresh token? Or opt-in to store refresh token?
            try:
                RefreshTokenStore().set(
                    issuer=authenticator._client_info.provider.issuer,
                    client_id=authenticator.client_id,
                    refresh_token=tokens.refresh_token
                )
            except Exception as e:
                _log.warning("Failed to store refresh token: {e!r}".format(e=e))
        token = tokens.access_token if not self.oidc_auth_user_id_token_as_bearer else tokens.id_token
        if self._api_version.at_least("1.0.0"):
            self.auth = BearerAuth(bearer='oidc/{p}/{t}'.format(p=provider_id, t=token))
        else:
            self.auth = BearerAuth(bearer=token)
        return self 
Example 19
Project: hubic-wrapper-to-swift   Author: puzzle1536   File: hubic.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get(self, hubic_api):

        hubic_api_url = 'https://api.hubic.com/1.0%s' % hubic_api

        if self.access_token:

            if options.verbose:
                print "-- GET request to hubic API : %s" % hubic_api

            if self.token_expire <= time():
                print "-- Access token has expired, trying to renew it"
                self.refresh()

            bearer_auth = HTTPBearerAuth(self.access_token)
            r = requests.get(hubic_api_url, auth=bearer_auth)

            try:
                # Check if token is still valid
                if r.status_code == 401 and r.json()['error'] == 'invalid_token' and r.json()['error_description'] == 'expired':
                    # Try to renew if possible
                    print "-- Access token has expired, trying to renew it"
                    self.refresh()
                    r = requests.get(hubic_api_url, auth=bearer_auth)
                if r.status_code == 404 or r.status_code == 500:
                    print "%s : %s" % (r.json()['code'], r.json()['message'])
                    return

                if r.status_code != 200:
                    print "%s : %s" % (r.json()['error'], r.json()['error_description'])
                    return

            except:
                print "Something wrong has happened when accessing hubic API (GET request)"
                sys.exit(10)

            for keys in r.json():
                print "%s : %s" % (keys,r.json()[keys]) 
Example 20
Project: hubic-wrapper-to-swift   Author: puzzle1536   File: hubic.py    License: GNU General Public License v3.0 5 votes vote down vote up
def post(self, hubic_api, data):

        hubic_api_url = 'https://api.hubic.com/1.0%s' % hubic_api

        if self.access_token:

            if options.verbose:
                print "-- POST request to hubic API : %s" % hubic_api

            if self.token_expire <= time():
                print "-- Access token has expired, trying to renew it"
                self.refresh()

            headers = {'content-type': 'application/x-www-form-urlencoded'}

            bearer_auth = HTTPBearerAuth(self.access_token)
            r = requests.post(hubic_api_url, data=data, headers=headers, auth=bearer_auth)

            try:
                # Check if token is still valid
                if r.status_code == 401 and r.json()['error'] == 'invalid_token' and r.json()['error_description'] == 'expired':
                    # Try to renew if possible
                    print "-- Access token has expired, trying to renew it"
                    self.refresh()
                    r = requests.post(hubic_api_url, auth=bearer_auth)

                if r.status_code == 404 or r.status_code == 500:
                    print "%s : %s" % (r.json()['code'], r.json()['message'])
                    return

                if r.status_code != 200:
                    print "%s : %s" % (r.json()['error'], r.json()['error_description'])
                    return

            except:
                print "Something wrong has happened when accessing hubic API (POST request)"
                sys.exit(10)

            for keys in r.json():
                print "%s : %s" % (keys,r.json()[keys]) 
Example 21
Project: TradzQAI   Author: kkuette   File: authenticated_client.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, key, b64secret, passphrase,
                 api_url="https://api.pro.coinbase.com"):
        """ Create an instance of the AuthenticatedClient class.

        Args:
            key (str): Your API key.
            b64secret (str): The secret key matching your API key.
            passphrase (str): Passphrase chosen when setting up key.
            api_url (Optional[str]): API URL. Defaults to cbpro API.
        """
        super(AuthenticatedClient, self).__init__(api_url)
        self.auth = CBProAuth(key, b64secret, passphrase)
        self.session = requests.Session() 
Example 22
Project: pywren-ibm-cloud   Author: pywren   File: infinispan.py    License: Apache License 2.0 5 votes vote down vote up
def __is_server_version_supported(self):
        res = self.infinispan_client.get(self.endpoint + '/rest/v2/cache-managers/' + self.cache_manager,
                                         auth=self.basicAuth)
        json_resp = json.loads(res.content.decode('utf-8'))
        server_version = json_resp['version'].split('.')
        if (int(server_version[0]) < 10 or (int(server_version[0]) == 10 and int(server_version[1]) < 1)):
            raise Exception('Infinispan versions 10.1 and up supported') 
Example 23
Project: pywren-ibm-cloud   Author: pywren   File: infinispan.py    License: Apache License 2.0 5 votes vote down vote up
def put_object(self, bucket_name, key, data):
        """
        Put an object in Infinispan. Override the object if the key already exists.
        :param key: key of the object.
        :param data: data of the object
        :type data: str/bytes
        :return: None
        """
        headers = {"Content-Type": "application/octet-stream",
                   'Key-Content-Type': "application/octet-stream;encoding=base64"}
        resp = self.infinispan_client.put(self.__key_url(key), data = data,
                auth=self.basicAuth, headers = headers )
        print (resp) 
Example 24
Project: pywren-ibm-cloud   Author: pywren   File: infinispan.py    License: Apache License 2.0 5 votes vote down vote up
def get_object(self, bucket_name, key, stream=False, extra_get_args={}):
        """
        Get object from COS with a key. Throws StorageNoSuchKeyError if the given key does not exist.
        :param key: key of the object
        :return: Data of the object
        :rtype: str/bytes
        """
        headers = {"Content-Type": "application/octet-stream",
                   'Key-Content-Type': "application/octet-stream;encoding=base64"}

        res = self.infinispan_client.get(self.__key_url(key), headers = headers,
                                         auth=self.basicAuth)
        data = res.content
        return data 
Example 25
Project: pywren-ibm-cloud   Author: pywren   File: infinispan.py    License: Apache License 2.0 5 votes vote down vote up
def head_object(self, bucket_name, key):
        """
        Head object from COS with a key. Throws StorageNoSuchKeyError if the given key does not exist.
        :param key: key of the object
        :return: Data of the object
        :rtype: str/bytes
        """
        res = self.infinispan_client.head(self.endpoint + '/rest/v2/caches/default/' + bucket_name + '/' + key,
                                   auth=self.basicAuth)
        return res.status_code 
Example 26
Project: pywren-ibm-cloud   Author: pywren   File: infinispan.py    License: Apache License 2.0 5 votes vote down vote up
def list_objects(self, bucket_name, prefix=None):
        """
        Return a list of objects for the given bucket and prefix.
        :param bucket_name: Name of the bucket.
        :param prefix: Prefix to filter object names.
        :return: List of objects in bucket that match the given prefix.
        :rtype: list of str
        """
        res = self.infinispan_client.get(self.endpoint + '/rest/v2/caches/' + self.cache_name + '?action=keys', auth=self.basicAuth)
        data = res.content
        return data 
Example 27
Project: pywren-ibm-cloud   Author: pywren   File: infinispan.py    License: Apache License 2.0 5 votes vote down vote up
def list_keys(self, bucket_name, prefix=None):
        """
        Return a list of keys for the given prefix.
        :param bucket_name: Name of the bucket.
        :param prefix: Prefix to filter object names.
        :return: List of keys in bucket that match the given prefix.
        :rtype: list of str
        """
        res = self.infinispan_client.get(self.endpoint + '/rest/v2/caches/' + self.cache_name + '?action=keys', auth=self.basicAuth)
        data = res.content
        return data 
Example 28
Project: rets   Author: opendoor-labs   File: client.py    License: MIT License 5 votes vote down vote up
def _get_http_auth(username: str, password: str, auth_type: str) -> AuthBase:
    if auth_type == 'basic':
        return HTTPBasicAuth(username, password)
    if auth_type == 'digest':
        return HTTPDigestAuth(username, password)
    raise RetsClientError('unknown auth type %s' % auth_type) 
Example 29
Project: pyspider   Author: binux   File: test_database.py    License: Apache License 2.0 5 votes vote down vote up
def tearDownClass(self):
        # remove the test admin user
        import requests
        from requests.auth import HTTPBasicAuth
        requests.delete('http://localhost:5984/_node/_local/_config/admins/test',
                        auth=HTTPBasicAuth('test', 'password'))
        del os.environ["COUCHDB_USER"]
        del os.environ["COUCHDB_PASSWORD"]
        self.projectdb.drop_database() 
Example 30
Project: pyspider   Author: binux   File: test_database.py    License: Apache License 2.0 5 votes vote down vote up
def tearDownClass(self):
        # remove the test admin user
        import requests
        from requests.auth import HTTPBasicAuth
        requests.delete('http://localhost:5984/_node/_local/_config/admins/test',
                        auth=HTTPBasicAuth('test', 'password'))
        del os.environ["COUCHDB_USER"]
        del os.environ["COUCHDB_PASSWORD"]
        self.resultdb.drop_database()