Python requests.auth.HTTPBasicAuth() Examples

The following are 30 code examples of requests.auth.HTTPBasicAuth(). 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 also want to check out all available functions/classes of the module requests.auth , or try the search function .
Example #1
Source File: projectdb.py    From pyspider with Apache License 2.0 8 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 #2
Source File: bitcoin_processor.py    From SempoBlockchain with GNU General Public License v3.0 7 votes vote down vote up
def _send_blockchain_result_to_app(self, result, request_method):

        if result.get('credit_transfer_id') is None:
            print('########WARNING: No credit transfer id supplied########')

        result['is_bitcoin'] = True
        result['signing_address'] = self.key.address

        print('sending result:')
        print(str(result))

        r = request_method(config.APP_HOST + '/api/blockchain_transaction/',
                          json=result,
                          auth=HTTPBasicAuth(config.BASIC_AUTH_USERNAME,
                                             config.BASIC_AUTH_PASSWORD))

        if r.status_code >= 400:
            raise Exception("Error with sending result: {}".format(str(r.json())))

        return r 
Example #3
Source File: couchdbbase.py    From pyspider with Apache License 2.0 7 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 #4
Source File: __init__.py    From prometheus_couchbase_exporter with MIT License 7 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 #5
Source File: infinispan.py    From pywren-ibm-cloud with Apache License 2.0 7 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 #6
Source File: bitcoin_processor.py    From SempoBlockchain with GNU General Public License v3.0 7 votes vote down vote up
def create_address_only_credit_transfer_in_app(self,
                                                   sender_address,
                                                   recipient_address,
                                                   transaction_hash,
                                                   amount):

        converted_amount = self.native_amount_to_cents(amount)

        body = {
            'sender_blockchain_address': sender_address,
            'recipient_blockchain_address': recipient_address,
            'blockchain_transaction_hash': transaction_hash,
            'transfer_amount': converted_amount
        }

        r = requests.post(config.APP_HOST + '/api/credit_transfer/internal/',
                          json=body,
                          auth=HTTPBasicAuth(config.BASIC_AUTH_USERNAME,
                                             config.BASIC_AUTH_PASSWORD))

        return r 
Example #7
Source File: __init__.py    From SempoBlockchain with GNU General Public License v3.0 7 votes vote down vote up
def register_tokens_from_app(host_address, auth_username, auth_password):
    token_req = requests.get(host_address + '/api/token', auth=HTTPBasicAuth(auth_username, auth_password))

    if token_req.status_code == 200:

        for token in token_req.json()['data']['tokens']:
            try:
                blockchain_processor.registry.register_contract(token['address'], dai_abi.abi)
            except BadFunctionCallOutput as e:
                # It's probably a contract on a different chain
                if not config.IS_PRODUCTION:
                    pass
                else:
                    raise e

        return True

    else:
        return False 
Example #8
Source File: taskdb.py    From pyspider with Apache License 2.0 7 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 #9
Source File: HTTP.py    From watchdog with Apache License 2.0 7 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 #10
Source File: HTTP.py    From watchdog with Apache License 2.0 7 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 #11
Source File: rpc_client.py    From python_course with Apache License 2.0 7 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 #12
Source File: connection.py    From openeo-python-client with Apache License 2.0 7 votes vote down vote up
def authenticate_basic(self, username: str, password: str) -> 'Connection':
        """
        Authenticate a user to the backend using basic username and password.

        :param username: User name
        :param password: User passphrase
        """
        resp = self.get(
            '/credentials/basic',
            # /credentials/basic is the only endpoint that expects a Basic HTTP auth
            auth=HTTPBasicAuth(username, password)
        ).json()
        # Switch to bearer based authentication in further requests.
        if self._api_version.at_least("1.0.0"):
            self.auth = BearerAuth(bearer='basic//{t}'.format(t=resp["access_token"]))
        else:
            self.auth = BearerAuth(bearer=resp["access_token"])
        return self 
Example #13
Source File: oauth2.py    From accesslink-example-python with MIT License 7 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 #14
Source File: odl.py    From sdn-loadbalancing with GNU General Public License v3.0 7 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 #15
Source File: couchbase_utils.py    From full-stack-fastapi-couchbase with MIT License 7 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 #16
Source File: connection.py    From insightconnect-plugins with MIT License 7 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
Source File: auth.py    From atomic-reactor with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def _get_token(self, auth_info, repo):
        bearer_info = parse_dict_header(self.BEARER_PATTERN.sub('', auth_info, count=1))
        # If repo could not be determined, do not set scope - implies global access
        if repo:
            bearer_info['scope'] = 'repository:{}:{}'.format(repo, ','.join(self.access))
        realm = bearer_info.pop('realm')

        realm_auth = None
        if self.auth_b64:
            realm_auth = HTTPBasicAuthWithB64(self.auth_b64)
        elif self.username and self.password:
            realm_auth = HTTPBasicAuth(self.username, self.password)

        realm_response = self._retry_session.get(realm, params=bearer_info, verify=self.verify,
                                                 auth=realm_auth)
        realm_response.raise_for_status()
        return realm_response.json()['token'] 
Example #18
Source File: connection.py    From insightconnect-plugins with MIT License 7 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 #19
Source File: projectdb.py    From pyspider with Apache License 2.0 6 votes vote down vote up
def __init__(self, url, database='projectdb', username='username', password='password'):
        self.username = username
        self.password = password
        self.url = url + self.__collection_name__ + "_" + database + "/"
        self.database = database
        self.insert('', {})

        # Create the db
        res = requests.put(self.url,
                           headers={"Content-Type": "application/json"},
                           auth=HTTPBasicAuth(self.username, self.password)).json()
        if 'error' in res and res['error'] == 'unauthorized':
            raise Exception(
                "Supplied credentials are incorrect. Reason: {} for User: {} Password: {}".format(res['reason'],
                                                                                                  self.username,
                                                                                                  self.password))
        # create index
        payload = {
            'index': {
                'fields': ['name']
            },
            'name': self.__collection_name__ + "_" + database
        }
        res = requests.post(self.url+"_index", data=json.dumps(payload),
                            headers={"Content-Type": "application/json"},
                            auth=HTTPBasicAuth(self.username, self.password)).json()
        self.index = res['id'] 
Example #20
Source File: couchdbbase.py    From pyspider with Apache License 2.0 6 votes vote down vote up
def delete(self, url):
        return requests.delete(url,
                               headers={"Content-Type": "application/json"},
                               auth=HTTPBasicAuth(self.username, self.password)).json() 
Example #21
Source File: couchdbbase.py    From pyspider with Apache License 2.0 6 votes vote down vote up
def insert_doc(self, db_name, doc_id, doc):
        url = self.base_url + db_name + "/" + doc_id
        return requests.put(url,
                            data=json.dumps(doc),
                            headers={"Content-Type": "application/json"},
                            auth=HTTPBasicAuth(self.username, self.password)).json() 
Example #22
Source File: couchdbbase.py    From pyspider with Apache License 2.0 6 votes vote down vote up
def get_doc(self, db_name, doc_id):
        url = self.base_url + db_name + "/" + doc_id
        res = requests.get(url,
                           headers={"Content-Type": "application/json"},
                           auth=HTTPBasicAuth(self.username, self.password)).json()
        if "error" in res and res["error"] == "not_found":
            return None
        return res 
Example #23
Source File: couchdbbase.py    From pyspider with Apache License 2.0 6 votes vote down vote up
def update_doc(self, db_name, doc_id, new_doc):
        doc = self.get_doc(db_name, doc_id)
        if doc is None:
            return self.insert_doc(db_name, doc_id, new_doc)
        for key in new_doc:
            doc[key] = new_doc[key]
        url = self.base_url + db_name + "/" + doc_id
        return requests.put(url,
                            data=json.dumps(doc),
                            headers={"Content-Type": "application/json"},
                            auth=HTTPBasicAuth(self.username, self.password)).json() 
Example #24
Source File: couchdbbase.py    From pyspider with Apache License 2.0 6 votes vote down vote up
def get_docs(self, db_name, selector):
        url = self.base_url + db_name + "/_find"
        selector['use_index'] = self.index
        res = requests.post(url,
                            data=json.dumps(selector),
                            headers={"Content-Type": "application/json"},
                            auth=HTTPBasicAuth(self.username, self.password)).json()
        if 'error' in res and res['error'] == 'not_found':
            return []
        return res['docs'] 
Example #25
Source File: test_run.py    From pyspider with Apache License 2.0 6 votes vote down vote up
def test_60a_docker_couchdb(self):
        try:
            # create a test admin user
            import requests
            requests.put('http://localhost:5984/_node/_local/_config/admins/test',
                         data='"password"')
            os.environ['COUCHDB_NAME'] = 'couchdb'
            os.environ['COUCHDB_PORT_5984_TCP_ADDR'] = 'localhost'
            os.environ['COUCHDB_PORT_5984_TCP_PORT'] = '5984'
            os.environ["COUCHDB_USER"] = "test"
            os.environ["COUCHDB_PASSWORD"] = "password"
            ctx = run.cli.make_context('test', [], None,
                                       obj=dict(testing_mode=True))
            ctx = run.cli.invoke(ctx)
            ctx.obj.resultdb
        except Exception as e:
            self.assertIsNone(e)
        finally:
            # 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_NAME']
            del os.environ['COUCHDB_PORT_5984_TCP_ADDR']
            del os.environ['COUCHDB_PORT_5984_TCP_PORT']
            del os.environ["COUCHDB_USER"]
            del os.environ["COUCHDB_PASSWORD"] 
Example #26
Source File: test_database.py    From pyspider with Apache License 2.0 6 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.taskdb.drop_database() 
Example #27
Source File: test_database.py    From pyspider with Apache License 2.0 6 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() 
Example #28
Source File: test_database.py    From pyspider with Apache License 2.0 6 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 #29
Source File: client.py    From rets with MIT License 6 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 #30
Source File: projectdb.py    From pyspider with Apache License 2.0 6 votes vote down vote up
def insert(self, name, obj={}):
        url = self.url + name
        obj = dict(obj)
        obj['name'] = name
        obj['updatetime'] = time.time()
        res = requests.put(url,
                           data = json.dumps(obj),
                           headers = {"Content-Type": "application/json"},
                           auth=HTTPBasicAuth(self.username, self.password)).json()
        return res