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


Python EdxRestApiClient.get_oauth_access_token方法代碼示例

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


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

示例1: access_token

# 需要導入模塊: from edx_rest_api_client.client import EdxRestApiClient [as 別名]
# 或者: from edx_rest_api_client.client.EdxRestApiClient import get_oauth_access_token [as 別名]
    def access_token(self):
        """ Returns an access token for this site's service user.

        The access token is retrieved using the current site's OAuth credentials and the client credentials grant.
        The token is cached for the lifetime of the token, as specified by the OAuth provider's response. The token
        type is JWT.

        Returns:
            str: JWT access token
        """
        key = 'siteconfiguration_access_token_{}'.format(self.id)
        access_token = cache.get(key)

        # pylint: disable=unsubscriptable-object
        if not access_token:
            url = '{root}/access_token'.format(root=self.oauth2_provider_url)
            access_token, expiration_datetime = EdxRestApiClient.get_oauth_access_token(
                url,
                self.oauth_settings['SOCIAL_AUTH_EDX_OIDC_KEY'],
                self.oauth_settings['SOCIAL_AUTH_EDX_OIDC_SECRET'],
                token_type='jwt'
            )

            expires = (expiration_datetime - datetime.datetime.utcnow()).seconds
            cache.set(key, access_token, expires)

        return access_token
開發者ID:open-craft,項目名稱:ecommerce,代碼行數:29,代碼來源:models.py

示例2: handle

# 需要導入模塊: from edx_rest_api_client.client import EdxRestApiClient [as 別名]
# 或者: from edx_rest_api_client.client.EdxRestApiClient import get_oauth_access_token [as 別名]
    def handle(self, *args, **options):
        # For each partner defined...
        partners = Partner.objects.all()

        # If a specific partner was indicated, filter down the set
        partner_code = options.get('partner_code')
        if partner_code:
            partners = partners.filter(short_code=partner_code)

        if not partners:
            raise CommandError('No partners available!')

        for partner in partners:

            access_token = options.get('access_token')
            token_type = options.get('token_type')

            if access_token and not token_type:
                raise CommandError('The token_type must be specified when passing in an access token!')

            if not access_token:
                logger.info('No access token provided. Retrieving access token using client_credential flow...')
                token_type = 'JWT'

                try:
                    access_token, __ = EdxRestApiClient.get_oauth_access_token(
                        '{root}/access_token'.format(root=partner.oidc_url_root.strip('/')),
                        partner.oidc_key,
                        partner.oidc_secret,
                        token_type=token_type
                    )
                except Exception:
                    logger.exception('No access token provided or acquired through client_credential flow.')
                    raise

            loaders = []

            if partner.organizations_api_url:
                loaders.append(OrganizationsApiDataLoader)
            if partner.courses_api_url:
                loaders.append(CoursesApiDataLoader)
            if partner.ecommerce_api_url:
                loaders.append(EcommerceApiDataLoader)
            if partner.marketing_site_api_url:
                loaders.append(DrupalApiDataLoader)
            if partner.programs_api_url:
                loaders.append(ProgramsApiDataLoader)

            if loaders:
                for loader_class in loaders:
                    try:
                        loader_class(partner, access_token, token_type).ingest()
                    except Exception:  # pylint: disable=broad-except
                        logger.exception('%s failed!', loader_class.__name__)
開發者ID:kumarsandeep91,項目名稱:course-discovery,代碼行數:56,代碼來源:refresh_course_metadata.py

示例3: get_access_token

# 需要導入模塊: from edx_rest_api_client.client import EdxRestApiClient [as 別名]
# 或者: from edx_rest_api_client.client.EdxRestApiClient import get_oauth_access_token [as 別名]
 def get_access_token():
     """ Returns an access token and expiration date from the OAuth
     provider.
     Returns:
         (str, datetime):Tuple containing access token and expiration date.
     """
     return EdxRestApiClient.get_oauth_access_token(
         OAUTH_ACCESS_TOKEN_URL,
         OAUTH_CLIENT_ID,
         OAUTH_CLIENT_SECRET,
         token_type='jwt'
     )
開發者ID:edx,項目名稱:edx-e2e-tests,代碼行數:14,代碼來源:api_clients.py

示例4: test_get_client_credential_access_token_success

# 需要導入模塊: from edx_rest_api_client.client import EdxRestApiClient [as 別名]
# 或者: from edx_rest_api_client.client.EdxRestApiClient import get_oauth_access_token [as 別名]
    def test_get_client_credential_access_token_success(self):
        """ Test that the get access token method handles 200 responses and returns the access token. """
        code = 200
        body = {"access_token": "my-token", "expires_in": 1000}
        now = datetime.datetime.utcnow()

        expected_return = ("my-token", now + datetime.timedelta(seconds=1000))

        with freeze_time(now):
            self._mock_auth_api(URL, code, body=body)
            self.assertEqual(
                EdxRestApiClient.get_oauth_access_token(URL, "client_id", "client_secret"),
                expected_return
            )
開發者ID:edx,項目名稱:edx-rest-api-client,代碼行數:16,代碼來源:test_client.py

示例5: __init__

# 需要導入模塊: from edx_rest_api_client.client import EdxRestApiClient [as 別名]
# 或者: from edx_rest_api_client.client.EdxRestApiClient import get_oauth_access_token [as 別名]
    def __init__(self, access_token, oauth_host, oauth_key, oauth_secret, api_url_root):
        self.access_token = access_token
        if not access_token:
            logger.info('No access token provided. Retrieving access token using client_credential flow...')
            try:
                self.access_token, expires = EdxRestApiClient.get_oauth_access_token(
                    '{root}/access_token'.format(root=oauth_host),
                    oauth_key,
                    oauth_secret, token_type='jwt'
                )
            except Exception:
                logger.exception('No access token provided or acquired through client_credential flow.')
                raise

            logger.info('Token retrieved: %s', access_token)

        self.api_client = EdxRestApiClient(api_url_root, jwt=self.access_token)
        self._programs_dictionary = {}
開發者ID:edx,項目名稱:ecommerce-scripts,代碼行數:20,代碼來源:catalog_api_service.py

示例6: handle

# 需要導入模塊: from edx_rest_api_client.client import EdxRestApiClient [as 別名]
# 或者: from edx_rest_api_client.client.EdxRestApiClient import get_oauth_access_token [as 別名]
    def handle(self, *args, **options):
        access_token = options.get('access_token')
        commit = options.get('commit')

        if access_token is None:
            try:
                access_token_url = '{}/access_token'.format(
                    settings.SOCIAL_AUTH_EDX_OIDC_URL_ROOT.strip('/')
                )
                client_id = settings.SOCIAL_AUTH_EDX_OIDC_KEY
                client_secret = settings.SOCIAL_AUTH_EDX_OIDC_SECRET

                access_token, __ = EdxRestApiClient.get_oauth_access_token(
                    access_token_url,
                    client_id,
                    client_secret
                )
            except:  # pylint: disable=bare-except
                logger.exception('Unable to exchange client credentials grant for an access token.')
                return

        self.client = EdxRestApiClient(settings.ORGANIZATIONS_API_URL_ROOT, oauth_access_token=access_token)

        logger.info('Retrieving organization data from %s.', settings.ORGANIZATIONS_API_URL_ROOT)

        try:
            with transaction.atomic():
                self._get_data()

                logger.info(
                    'Retrieved %d organizations from %s, %d of which were new.',
                    self.org_count,
                    settings.ORGANIZATIONS_API_URL_ROOT,
                    self.new_org_count
                )

                if not commit:
                    raise ForcedRollback('No data has been saved. To save data, pass the -c or --commit flags.')
        except ForcedRollback as e:
            logger.info(e)
開發者ID:dadasoz,項目名稱:programs,代碼行數:42,代碼來源:sync_orgs.py

示例7: get_course_catalog_api_client

# 需要導入模塊: from edx_rest_api_client.client import EdxRestApiClient [as 別名]
# 或者: from edx_rest_api_client.client.EdxRestApiClient import get_oauth_access_token [as 別名]
def get_course_catalog_api_client(site):
    """
    Returns an API client to access the Course Catalog service.

    Arguments:
        site (Site): The site for which to retrieve settings.

    Returns:
        EdxRestApiClient: The client to access the Course Catalog service.
    """

    access_token, __ = EdxRestApiClient.get_oauth_access_token(
        '{root}/access_token'.format(root=get_oauth2_provider_url()),
        site.siteconfiguration.oauth_settings['SOCIAL_AUTH_EDX_OIDC_KEY'],
        site.siteconfiguration.oauth_settings['SOCIAL_AUTH_EDX_OIDC_SECRET'],
        token_type='jwt'
    )
    course_catalog_client = EdxRestApiClient(
        settings.COURSE_CATALOG_API_URL,
        jwt=access_token
    )
    return course_catalog_client
開發者ID:digideskio,項目名稱:ecommerce-2,代碼行數:24,代碼來源:url_utils.py

示例8: test_get_client_credential_access_token_failure

# 需要導入模塊: from edx_rest_api_client.client import EdxRestApiClient [as 別名]
# 或者: from edx_rest_api_client.client.EdxRestApiClient import get_oauth_access_token [as 別名]
 def test_get_client_credential_access_token_failure(self, code, body):
     """ Test that the get access token method handles failure responses. """
     with self.assertRaises(requests.RequestException):
         self._mock_auth_api(URL, code, body=body)
         EdxRestApiClient.get_oauth_access_token(URL, "client_id", "client_secret")
開發者ID:edx,項目名稱:edx-rest-api-client,代碼行數:7,代碼來源:test_client.py

示例9: handle

# 需要導入模塊: from edx_rest_api_client.client import EdxRestApiClient [as 別名]
# 或者: from edx_rest_api_client.client.EdxRestApiClient import get_oauth_access_token [as 別名]
    def handle(self, *args, **options):
        max_workers = options.get('max_workers')

        # For each partner defined...
        partners = Partner.objects.all()

        # If a specific partner was indicated, filter down the set
        partner_code = options.get('partner_code')
        if partner_code:
            partners = partners.filter(short_code=partner_code)

        if not partners:
            raise CommandError('No partners available!')

        token_type = 'JWT'
        for partner in partners:
            logger.info('Retrieving access token for partner [{}]'.format(partner_code))

            try:
                access_token, __ = EdxRestApiClient.get_oauth_access_token(
                    '{root}/access_token'.format(root=partner.oidc_url_root.strip('/')),
                    partner.oidc_key,
                    partner.oidc_secret,
                    token_type=token_type
                )
            except Exception:
                logger.exception('No access token acquired through client_credential flow.')
                raise
            username = jwt.decode(access_token, verify=False)['preferred_username']
            kwargs = {'username': username} if username else {}

            # The Linux kernel implements copy-on-write when fork() is called to create a new
            # process. Pages that the parent and child processes share, such as the database
            # connection, are marked read-only. If a write is performed on a read-only page
            # (e.g., closing the connection), it is then copied, since the memory is no longer
            # identical between the two processes. This leads to the following behavior:
            #
            # 1) Newly forked process
            #       parent
            #              -> connection (Django open, MySQL open)
            #       child
            #
            # 2) Child process closes the connection
            #       parent -> connection (*Django open, MySQL closed*)
            #       child  -> connection (Django closed, MySQL closed)
            #
            # Calling connection.close() from a child process causes the MySQL server to
            # close a connection which the parent process thinks is still usable. Since
            # the parent process thinks the connection is still open, Django won't attempt
            # to open a new one, and the parent ends up running a query on a closed connection.
            # This results in a 'MySQL server has gone away' error.
            #
            # To resolve this, we force Django to reconnect to the database before running any queries.
            connection.connect()

            # If no courses exist for this partner, this command is likely being run on a
            # new catalog installation. In that case, we don't want multiple threads racing
            # to create courses. If courses do exist, this command is likely being run
            # as an update, significantly lowering the probability of race conditions.
            courses_exist = Course.objects.filter(partner=partner).exists()
            is_threadsafe = courses_exist and waffle.switch_is_active('threaded_metadata_write')

            logger.info(
                'Command is{negation} using threads to write data.'.format(negation='' if is_threadsafe else ' not')
            )

            pipeline = (
                (
                    (SubjectMarketingSiteDataLoader, partner.marketing_site_url_root, None),
                    (SchoolMarketingSiteDataLoader, partner.marketing_site_url_root, None),
                    (SponsorMarketingSiteDataLoader, partner.marketing_site_url_root, None),
                    (PersonMarketingSiteDataLoader, partner.marketing_site_url_root, None),
                ),
                (
                    (CourseMarketingSiteDataLoader, partner.marketing_site_url_root, None),
                    (OrganizationsApiDataLoader, partner.organizations_api_url, None),
                ),
                (
                    (CoursesApiDataLoader, partner.courses_api_url, None),
                ),
                (
                    (EcommerceApiDataLoader, partner.ecommerce_api_url, 1),
                    (ProgramsApiDataLoader, partner.programs_api_url, None),
                ),
                (
                    (XSeriesMarketingSiteDataLoader, partner.marketing_site_url_root, None),
                ),
            )

            if waffle.switch_is_active('parallel_refresh_pipeline'):
                for stage in pipeline:
                    with concurrent.futures.ProcessPoolExecutor() as executor:
                        for loader_class, api_url, max_workers_override in stage:
                            if api_url:
                                executor.submit(
                                    execute_parallel_loader,
                                    loader_class,
                                    partner,
                                    api_url,
                                    access_token,
#.........這裏部分代碼省略.........
開發者ID:edx,項目名稱:course-discovery,代碼行數:103,代碼來源:refresh_course_metadata.py


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