當前位置: 首頁>>代碼示例>>Python>>正文


Python requests.AuthorizedSession方法代碼示例

本文整理匯總了Python中google.auth.transport.requests.AuthorizedSession方法的典型用法代碼示例。如果您正苦於以下問題:Python requests.AuthorizedSession方法的具體用法?Python requests.AuthorizedSession怎麽用?Python requests.AuthorizedSession使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在google.auth.transport.requests的用法示例。


在下文中一共展示了requests.AuthorizedSession方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: sign_bytes

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import AuthorizedSession [as 別名]
def sign_bytes(self, message):

        iam_sign_endpoint = _IAM_SIGN_ENDPOINT.format(self._target_principal)

        body = {
            "payload": base64.b64encode(message).decode("utf-8"),
            "delegates": self._delegates,
        }

        headers = {"Content-Type": "application/json"}

        authed_session = AuthorizedSession(self._source_credentials)

        response = authed_session.post(
            url=iam_sign_endpoint, headers=headers, json=body
        )

        return base64.b64decode(response.json()["signedBlob"]) 
開發者ID:googleapis,項目名稱:google-auth-library-python,代碼行數:20,代碼來源:impersonated_credentials.py

示例2: get_session

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import AuthorizedSession [as 別名]
def get_session():
    """Creates an authorized Requests Session."""

    # Pass in the credentials and project ID. If none supplied, get them
    # from the environment.
    credentials = service_account.Credentials.from_service_account_file(
        os.environ["GOOGLE_APPLICATION_CREDENTIALS"]
    )
    scoped_credentials = credentials.with_scopes(
        ["https://www.googleapis.com/auth/cloud-platform"]
    )

    # Create a requests Session object with the credentials.
    session = requests.AuthorizedSession(scoped_credentials)

    return session
# [END healthcare_get_session]


# [START healthcare_create_resource] 
開發者ID:GoogleCloudPlatform,項目名稱:python-docs-samples,代碼行數:22,代碼來源:fhir_resources.py

示例3: __init__

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import AuthorizedSession [as 別名]
def __init__(self, credentials,
                 refresh_status_codes=transport.DEFAULT_REFRESH_STATUS_CODES,
                 max_refresh_attempts=transport.DEFAULT_MAX_REFRESH_ATTEMPTS,
                 refresh_timeout=None,
                 **kwargs):
        super(AuthorizedSession, self).__init__(**kwargs)
        self.credentials = credentials
        self._refresh_status_codes = refresh_status_codes
        self._max_refresh_attempts = max_refresh_attempts
        self._refresh_timeout = refresh_timeout

        auth_request_session = requests.Session()

        # Using an adapter to make HTTP requests robust to network errors.
        # This adapter retrys HTTP requests when network errors occur
        # and the requests seems safely retryable.
        retry_adapter = requests.adapters.HTTPAdapter(max_retries=3)
        auth_request_session.mount("https://", retry_adapter)

        # Request instance used by internal methods (for example,
        # credentials.refresh).
        # Do not pass `self` as the session here, as it can lead to infinite
        # recursion.
        self._auth_request = Request(auth_request_session) 
開發者ID:fniephaus,項目名稱:alfred-gmail,代碼行數:26,代碼來源:requests.py

示例4: sign_bytes

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import AuthorizedSession [as 別名]
def sign_bytes(self, message):

        iam_sign_endpoint = _IAM_SIGN_ENDPOINT.format(self._target_principal)

        body = {
            "payload": base64.b64encode(message),
            "delegates": self._delegates
        }

        headers = {
            'Content-Type': 'application/json',
        }

        authed_session = AuthorizedSession(self._source_credentials)

        response = authed_session.post(
            url=iam_sign_endpoint,
            headers=headers,
            json=body)

        return base64.b64decode(response.json()['signedBlob']) 
開發者ID:luci,項目名稱:luci-py,代碼行數:23,代碼來源:impersonated_credentials.py

示例5: run_query

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import AuthorizedSession [as 別名]
def run_query(baseurl, query, credentials=None):
    url = '{baseurl}&tq={query}'.format(
        baseurl=baseurl, query=parse.quote(query, safe='/()'))
    headers = {'X-DataSource-Auth': 'true'}

    if credentials:
        session = AuthorizedSession(credentials)
    else:
        session = Session()

    r = session.get(url, headers=headers)
    if r.encoding is None:
        r.encoding = 'utf-8'

    # raise any error messages
    if r.status_code != 200:
        raise ProgrammingError(r.text)

    if r.text.startswith(LEADING):
        result = json.loads(r.text[len(LEADING):])
    else:
        result = r.json()

    return result 
開發者ID:betodealmeida,項目名稱:gsheets-db-api,代碼行數:26,代碼來源:query.py

示例6: connect

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import AuthorizedSession [as 別名]
def connect(self, params):
        admin_user = params.get('admin_user')
        private_key = params.get('private_key').get('privateKey')
        auth = params
        auth['private_key'] = private_key
        auth['type'] = 'service_account'
        del auth['admin_user']
        self.project = auth['project_id']

        scopes = ['https://www.googleapis.com/auth/drive']

        if admin_user:
            self.logger.info("Connecting to {email} as {admin}".format(email=auth['client_email'],
                                                                       admin=admin_user))
        else:
            self.logger.info("Connection to {} as service account".format(auth['client_email']))

        # Fix escaping issues in private_key
        if '\\n' in auth['private_key']:
            auth['private_key'] = auth['private_key'].replace('\\n', "\n", -1)

        # Build a Google credentials object
        if admin_user:
            try:
                credentials = service_account.Credentials.from_service_account_info(auth,
                                                                                    scopes=scopes,
                                                                                    subject=admin_user)
            except ValueError as e:
                raise e

        else:
            try:
                credentials = service_account.Credentials.from_service_account_info(auth, scopes=scopes)
            except ValueError:
                raise ConnectionTestException.Preset.API_KEY

        self.google_client = gspread.Client(auth=credentials)
        self.google_client.session = AuthorizedSession(credentials) 
開發者ID:rapid7,項目名稱:insightconnect-plugins,代碼行數:40,代碼來源:connection.py

示例7: evaluate

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import AuthorizedSession [as 別名]
def evaluate(self):
        credentials, project = google.auth.default(scopes=['https://www.googleapis.com/auth/cloud-platform'])
        authed_session = AuthorizedSession(credentials)
        basename="https://automl.googleapis.com/v1beta1/"
        cmd = basename + self.operation_name
        response=authed_session.get(cmd)
        result=json.loads(response.content)
        self.ctx.log("Operation name: {}".format(result["name"]))

        if (("done" in result.keys()) and result["done"]):
            self.ctx.log("Model training complete.")
            self.model_name = result["response"]["name"]
            self.ctx.log("Model full name: {}".format(self.model_name))
            self.ctx.config.set('model_name', self.model_name)
            self.ctx.config.write()
            response = self.client.list_model_evaluations(self.model_name)
            self.ctx.log("List of model evaluations:")
            for evaluation in response:
                self.ctx.log("Model evaluation name: {}".format(evaluation.name))
                self.ctx.log("Model evaluation id: {}".format(evaluation.name.split("/")[-1]))
                self.ctx.log("Model evaluation example count: {}".format(
                    evaluation.evaluated_example_count))
                self.ctx.log("Model evaluation time: {} seconds".format(evaluation.create_time.seconds))
                self.ctx.log("Full model evaluation: {}".format(inspect.getmembers(evaluation) ))
                self.ctx.log("\n")
        else:
            self.ctx.log("Model still training...") 
開發者ID:augerai,項目名稱:a2ml,代碼行數:29,代碼來源:a2ml.py

示例8: set_session

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import AuthorizedSession [as 別名]
def set_session(self):
        # Try to load credentials from an auth file.
        # If it doesn't exist or is not valid then catch the 
        #  exception and reauthenticate.
        try:
            creds = Credentials.from_authorized_user_file(self.auth_file, self.scopes)
        except:
            try:
                flow = InstalledAppFlow.from_client_secrets_file(self.secrets_file, self.scopes)
                creds = flow.run_local_server()
                cred_dict = {
                    'token': creds.token,
                    'refresh_token': creds.refresh_token,
                    'id_token': creds.id_token,
                    'scopes': creds.scopes,
                    'token_uri': creds.token_uri,
                    'client_id': creds.client_id,
                    'client_secret': creds.client_secret
                }

                # Store the returned authentication tokens to the auth_file.
                with open(self.auth_file, 'w') as f:
                    f.write(json.dumps(cred_dict))
            except:
                return

        self.session = AuthorizedSession(creds)
        self.session.headers["Content-type"] = "application/octet-stream"
        self.session.headers["X-Goog-Upload-Protocol"] = "raw" 
開發者ID:jmathai,項目名稱:elodie,代碼行數:31,代碼來源:googlephotos.py

示例9: __init__

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import AuthorizedSession [as 別名]
def __init__(
        self,
        credentials,
        refresh_status_codes=transport.DEFAULT_REFRESH_STATUS_CODES,
        max_refresh_attempts=transport.DEFAULT_MAX_REFRESH_ATTEMPTS,
        refresh_timeout=None,
        auth_request=None,
    ):
        super(AuthorizedSession, self).__init__()
        self.credentials = credentials
        self._refresh_status_codes = refresh_status_codes
        self._max_refresh_attempts = max_refresh_attempts
        self._refresh_timeout = refresh_timeout
        self._is_mtls = False

        if auth_request is None:
            auth_request_session = requests.Session()

            # Using an adapter to make HTTP requests robust to network errors.
            # This adapter retrys HTTP requests when network errors occur
            # and the requests seems safely retryable.
            retry_adapter = requests.adapters.HTTPAdapter(max_retries=3)
            auth_request_session.mount("https://", retry_adapter)

            # Do not pass `self` as the session here, as it can lead to
            # infinite recursion.
            auth_request = Request(auth_request_session)

        # Request instance used by internal methods (for example,
        # credentials.refresh).
        self._auth_request = auth_request 
開發者ID:googleapis,項目名稱:google-auth-library-python,代碼行數:33,代碼來源:requests.py

示例10: refresh

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import AuthorizedSession [as 別名]
def refresh(self, request):

        iam_sign_endpoint = _IAM_IDTOKEN_ENDPOINT.format(
            self._target_credentials.signer_email
        )

        body = {
            "audience": self._target_audience,
            "delegates": self._target_credentials._delegates,
            "includeEmail": self._include_email,
        }

        headers = {"Content-Type": "application/json"}

        authed_session = AuthorizedSession(
            self._target_credentials._source_credentials, auth_request=request
        )

        response = authed_session.post(
            url=iam_sign_endpoint,
            headers=headers,
            data=json.dumps(body).encode("utf-8"),
        )

        id_token = response.json()["token"]
        self.token = id_token
        self.expiry = datetime.fromtimestamp(jwt.decode(id_token, verify=False)["exp"]) 
開發者ID:googleapis,項目名稱:google-auth-library-python,代碼行數:29,代碼來源:impersonated_credentials.py

示例11: authorized_transport

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import AuthorizedSession [as 別名]
def authorized_transport():
    credentials, _ = google.auth.default(scopes=(utils.GCS_RW_SCOPE,))
    yield tr_requests.AuthorizedSession(credentials) 
開發者ID:googleapis,項目名稱:google-resumable-media-python,代碼行數:5,代碼來源:conftest.py

示例12: request

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import AuthorizedSession [as 別名]
def request(self, method, url, data=None, headers=None, **kwargs):
        """Implementation of Requests' request."""
        response = tr_requests.AuthorizedSession.request(
            self, method, url, data=data, headers=headers, **kwargs
        )
        response.headers[download_mod._HASH_HEADER] = u"md5={}".format(self.EMPTY_HASH)
        return response 
開發者ID:googleapis,項目名稱:google-resumable-media-python,代碼行數:9,代碼來源:test_download.py

示例13: _get_session

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import AuthorizedSession [as 別名]
def _get_session():
    """Provides an authed requests session object."""
    creds, _ = google.auth.default(scopes=[_FIREBASE_SCOPES])
    authed_session = AuthorizedSession(creds)
    return authed_session 
開發者ID:GoogleCloudPlatform,項目名稱:python-docs-samples,代碼行數:7,代碼來源:firetactoe.py

示例14: _get_session

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import AuthorizedSession [as 別名]
def _get_session():
    """Provides an authed requests session object."""
    creds, _ = google.auth.default(scopes=[_FIREBASE_SCOPES])
    # Use application default credentials to make the Firebase calls
    # https://firebase.google.com/docs/reference/rest/database/user-auth
    authed_session = AuthorizedSession(creds)
    return authed_session 
開發者ID:GoogleCloudPlatform,項目名稱:python-docs-samples,代碼行數:9,代碼來源:rest_api.py

示例15: get_session

# 需要導入模塊: from google.auth.transport import requests [as 別名]
# 或者: from google.auth.transport.requests import AuthorizedSession [as 別名]
def get_session():
    """Creates an authorized Requests Session."""
    credentials = service_account.Credentials.from_service_account_file(
        filename=os.environ["GOOGLE_APPLICATION_CREDENTIALS"],
        scopes=["https://www.googleapis.com/auth/cloud-platform"],
    )

    # Create a requests Session object with the credentials.
    session = requests.AuthorizedSession(credentials)
    return session


# [START healthcare_dicomweb_store_instance] 
開發者ID:GoogleCloudPlatform,項目名稱:python-docs-samples,代碼行數:15,代碼來源:dicomweb.py


注:本文中的google.auth.transport.requests.AuthorizedSession方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。