Python源码示例:edx.EdxRestApiClient()

示例1
def _query_course_structure_api(self):
        """Get course name from the Course Structure API."""
        api_client = EdxRestApiClient(
            self.site_configuration.build_lms_url('/api/course_structure/v0/'),
            jwt=self.site_configuration.access_token
        )
        data = api_client.courses(self.course.id).get()
        logger.debug(data)

        course_name = data.get('name')
        if course_name is None:
            message = 'Aborting migration. No name is available for {}.'.format(self.course.id)
            logger.error(message)
            raise Exception(message)

        # A course without entries in the LMS CourseModes table must be an honor course, meaning
        # it has no verification deadline.
        course_verification_deadline = None

        return course_name.strip(), course_verification_deadline 
示例2
def _add_dynamic_discount_to_request(self, basket):
        # TODO: Remove as a part of REVMI-124 as this is a hacky solution
        # The problem is that orders are being created after payment processing, and the discount is not
        # saved in the database, so it needs to be calculated again in order to save the correct info to the
        # order. REVMI-124 will create the order before payment processing, when we have the discount context.
        if waffle.flag_is_active(self.request, DYNAMIC_DISCOUNT_FLAG) and basket.lines.count() == 1:
            discount_lms_url = get_lms_url('/api/discounts/')
            lms_discount_client = EdxRestApiClient(discount_lms_url,
                                                   jwt=self.request.site.siteconfiguration.access_token)
            ck = basket.lines.first().product.course_id
            user_id = basket.owner.lms_user_id
            try:
                response = lms_discount_client.user(user_id).course(ck).get()
                self.request.GET = self.request.GET.copy()
                self.request.GET['discount_jwt'] = response.get('jwt')
            except (SlumberHttpBaseException, Timeout) as error:
                logger.warning(
                    'Failed to get discount jwt from LMS. [%s] returned [%s]',
                    discount_lms_url,
                    error.response)
            # END TODO 
示例3
def __init__(self, site):
        self.client = EdxRestApiClient(site.partner.lms_url, jwt=site.partner.access_token) 
示例4
def credential_api_client(self):
        try:
            api_client = EdxRestApiClient(config.CREDENTIALS_API_URL, oauth_access_token=config.ACCESS_TOKEN)
        except Exception:  # pylint: disable=broad-except
            log.exception("Failed to initialize the API client with url '%s'.", config.CREDENTIALS_API_URL)
            return
        return api_client 
示例5
def revoke_line(self, line):
        try:
            logger.info('Attempting to revoke fulfillment of Line [%d]...', line.id)

            UUID = line.product.attr.UUID
            entitlement_option = Option.objects.get(code='course_entitlement')
            course_entitlement_uuid = line.attributes.get(option=entitlement_option).value

            entitlement_api_client = EdxRestApiClient(
                get_lms_entitlement_api_url(),
                jwt=line.order.site.siteconfiguration.access_token
            )

            # DELETE to the Entitlement API.
            entitlement_api_client.entitlements(course_entitlement_uuid).delete()

            audit_log(
                'line_revoked',
                order_line_id=line.id,
                order_number=line.order.number,
                product_class=line.product.get_product_class().name,
                UUID=UUID,
                certificate_type=getattr(line.product.attr, 'certificate_type', ''),
                user_id=line.order.user.id
            )

            return True
        except Exception:  # pylint: disable=broad-except
            logger.exception('Failed to revoke fulfillment of Line [%d].', line.id)

        return False 
示例6
def _add_dynamic_discount_to_request(self, basket):
        # TODO: Remove as a part of REVMI-124 as this is a hacky solution
        # The problem is that orders are being created after payment processing, and the discount is not
        # saved in the database, so it needs to be calculated again in order to save the correct info to the
        # order. REVMI-124 will create the order before payment processing, when we have the discount context.
        if waffle.flag_is_active(self.request, DYNAMIC_DISCOUNT_FLAG) and basket.lines.count() == 1:  # pragma: no cover  pylint: disable=line-too-long
            discount_lms_url = get_lms_url('/api/discounts/')
            lms_discount_client = EdxRestApiClient(discount_lms_url,
                                                   jwt=self.request.site.siteconfiguration.access_token)
            ck = basket.lines.first().product.course_id
            user_id = basket.owner.lms_user_id
            try:
                response = lms_discount_client.user(user_id).course(ck).get()
                self.request.POST = self.request.POST.copy()
                self.request.POST['discount_jwt'] = response.get('jwt')
                logger.info(
                    """Received discount jwt from LMS with
                    url: [%s],
                    user_id: [%s],
                    course_id: [%s],
                    and basket_id: [%s]
                    returned [%s]""",
                    discount_lms_url,
                    str(user_id),
                    ck,
                    basket.id,
                    response)
            except (SlumberHttpBaseException, requests.exceptions.Timeout) as error:
                logger.warning(
                    """Failed to receive discount jwt from LMS with
                    url: [%s],
                    user_id: [%s],
                    course_id: [%s],
                    and basket_id: [%s]
                    returned [%s]""",
                    discount_lms_url,
                    str(user_id),
                    ck,
                    basket.id,
                    vars(error.response) if hasattr(error, 'response') else '')
            # End TODO 
示例7
def get_enterprise_api_client(site):
    """
    Constructs a REST client for to communicate with the Open edX Enterprise Service
    """
    return EdxRestApiClient(
        site.siteconfiguration.enterprise_api_url,
        jwt=site.siteconfiguration.access_token
    ) 
示例8
def _hubspot_endpoint(self, hubspot_object, api_url, method, body=None, **kwargs):
        """
        This function is responsible for all the calls of hubspot.
        """
        client = EdxRestApiClient('/'.join([HUBSPOT_API_BASE_URL, api_url]))
        if method == "GET":
            return getattr(client, hubspot_object).get(**kwargs)
        if method == "POST":
            return getattr(client, hubspot_object).post(**kwargs)
        if method == "PUT":
            return getattr(client, hubspot_object).put(body, **kwargs)
        raise ValueError("Unexpected method {}".format(method)) 
示例9
def __init__(self):
        """
        Create an E-Commerce client.
        """
        self.client = EdxRestApiClient(self.API_BASE_URL, append_slash=self.APPEND_SLASH) 
示例10
def course_discovery_api_client(user, catalog_url):
    """
    Return a Course Discovery API client setup with authentication for the specified user.
    """
    if JwtBuilder is None:
        raise NotConnectedToOpenEdX(
            _("To get a Catalog API client, this package must be "
              "installed in an Open edX environment.")
        )

    jwt = JwtBuilder.create_jwt_for_user(user)
    return EdxRestApiClient(catalog_url, jwt=jwt) 
示例11
def __init__(self):
        """
        Create a course discovery client.
        """
        self.client = EdxRestApiClient(self.API_BASE_URL, append_slash=self.APPEND_SLASH) 
示例12
def __init__(self):
        """
        Create an enterprise catalog client.
        """
        self.client = EdxRestApiClient(self.API_BASE_URL, append_slash=self.APPEND_SLASH) 
示例13
def __init__(self):
        """
        Create an LMS API client.
        """
        self.client = EdxRestApiClient(self.API_BASE_URL, append_slash=self.APPEND_SLASH) 
示例14
def _get_courses_enrollment_info(self):
        """
        Retrieve the enrollment information for all the courses.

        Returns:
            Dictionary representing the key-value pair (course_key, enrollment_end) of course.
        """
        def _parse_response(api_response):
            response_data = api_response.get('results', [])

            # Map course_id with enrollment end date.
            courses_enrollment = dict(
                (course_info['course_id'], course_info['enrollment_end'])
                for course_info in response_data
            )
            return courses_enrollment, api_response['pagination'].get('next', None)

        querystring = {'page_size': 50}
        api = EdxRestApiClient(get_lms_url('api/courses/v1/'))
        course_enrollments = {}

        page = 0
        throttling_attempts = 0
        next_page = True
        while next_page:
            page += 1
            querystring['page'] = page
            try:
                response = api.courses().get(**querystring)
                throttling_attempts = 0
            except HttpClientError as exc:
                # this is a known limitation; If we get HTTP429, we need to pause execution for a few seconds
                # before re-requesting the data. raise any other errors
                if exc.response.status_code == 429 and throttling_attempts < self.max_tries:
                    logger.warning(
                        'API calls are being rate-limited. Waiting for [%d] seconds before retrying...',
                        self.pause_time
                    )
                    time.sleep(self.pause_time)
                    page -= 1
                    throttling_attempts += 1
                    logger.info('Retrying [%d]...', throttling_attempts)
                    continue
                raise
            enrollment_info, next_page = _parse_response(response)
            course_enrollments.update(enrollment_info)
        return course_enrollments