当前位置: 首页>>代码示例>>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;未经允许,请勿转载。