本文整理汇总了Python中edx_rest_api_client.client.EdxRestApiClient类的典型用法代码示例。如果您正苦于以下问题:Python EdxRestApiClient类的具体用法?Python EdxRestApiClient怎么用?Python EdxRestApiClient使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了EdxRestApiClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: refresh_all
def refresh_all(cls, access_token):
"""
Refresh all course data.
Args:
access_token (str): OAuth access token
Returns:
None
"""
client = EdxRestApiClient(settings.ECOMMERCE_API_URL, oauth_access_token=access_token)
logger.info('Refreshing course data from %s....', settings.ECOMMERCE_API_URL)
count = None
page = 1
while page:
response = client.courses().get(include_products=True, page=page, page_size=50)
count = response['count']
results = response['results']
logger.info('Retrieved %d courses...', len(results))
if response['next']:
page += 1
else:
page = None
for body in results:
Course(body['id'], body).save()
logger.info('Retrieved %d courses.', count)
示例2: is_eligible_for_credit
def is_eligible_for_credit(self, course_key):
"""
Check if a user is eligible for a credit course.
Calls the LMS eligibility API endpoint and sends the username and course key
query parameters and returns eligibility details for the user and course combination.
Args:
course_key (string): The course key for which the eligibility is checked for.
Returns:
A list that contains eligibility information, or empty if user is not eligible.
Raises:
ConnectionError, SlumberBaseException and Timeout for failures in establishing a
connection with the LMS eligibility API endpoint.
"""
query_strings = {
'username': self.username,
'course_key': course_key
}
try:
api = EdxRestApiClient(
get_lms_url('api/credit/v1/'),
oauth_access_token=self.access_token
)
response = api.eligibility().get(**query_strings)
except (ConnectionError, SlumberBaseException, Timeout): # pragma: no cover
log.exception(
'Failed to retrieve eligibility details for [%s] in course [%s]',
self.username,
course_key
)
raise
return response
示例3: account_details
def account_details(self, request):
""" Returns the account details from LMS.
Args:
request (WSGIRequest): The request from which the LMS account API endpoint is created.
Returns:
A dictionary of account details.
Raises:
ConnectionError, SlumberBaseException and Timeout for failures in establishing a
connection with the LMS account API endpoint.
"""
try:
api = EdxRestApiClient(
request.site.siteconfiguration.build_lms_url('/api/user/v1'),
append_slash=False,
jwt=request.site.siteconfiguration.access_token
)
response = api.accounts(self.username).get()
return response
except (ConnectionError, SlumberBaseException, Timeout):
log.exception(
'Failed to retrieve account details for [%s]',
self.username
)
raise
示例4: get_context_data
def get_context_data(self, **kwargs):
context = super(CouponOfferView, self).get_context_data(**kwargs)
code = self.request.GET.get('code', None)
if code is not None:
voucher, product = get_voucher(code=code)
valid_voucher, msg = voucher_is_valid(voucher, product, self.request)
if valid_voucher:
api = EdxRestApiClient(
get_lms_url('api/courses/v1/'),
)
try:
course = api.courses(product.course_id).get()
except SlumberHttpBaseException as e:
logger.exception('Could not get course information. [%s]', e)
return {
'error': _('Could not get course information. [{error}]'.format(error=e))
}
course['image_url'] = get_lms_url(course['media']['course_image']['uri'])
stock_records = voucher.offers.first().benefit.range.catalog.stock_records.first()
context.update({
'course': course,
'code': code,
'price': stock_records.price_excl_tax,
'verified': (product.attr.certificate_type is 'verified')
})
return context
return {
'error': msg
}
return {
'error': _('This coupon code is invalid.')
}
示例5: refresh_all_course_api_data
def refresh_all_course_api_data(cls, access_token):
course_api_url = settings.COURSES_API_URL
client = EdxRestApiClient(course_api_url, oauth_access_token=access_token)
count = None
page = 1
logger.info('Refreshing course api data from %s....', course_api_url)
while page:
# TODO Update API to not require username?
response = client.courses().get(page=page, page_size=50, username='ecommerce_worker')
count = response['pagination']['count']
results = response['results']
logger.info('Retrieved %d courses...', len(results))
if response['pagination']['next']:
page += 1
else:
page = None
for body in results:
Course(body['id']).update(body)
logger.info('Retrieved %d courses from %s.', count, course_api_url)
示例6: _delete_program
def _delete_program(self, program_id, jwt_token):
""" With the JWT token, hit the program details URL with the patch to set the
program status to "deleted". This is the delete program step """
url = '{0}/api/v1/'.format(PROGRAMS_URL_ROOT)
delete_client = EdxRestApiClient(url, jwt=jwt_token)
deleted_program = delete_client.programs(program_id).patch({'status': 'deleted'})
# tell the caller wither the delete is successful or not.
return deleted_program['status'] == 'deleted'
示例7: get
def get(self, request):
partner = get_partner_for_site(request)
sku = request.GET.get('sku', None)
code = request.GET.get('code', None)
if not sku:
return HttpResponseBadRequest(_('No SKU provided.'))
if code:
voucher, __ = get_voucher_from_code(code=code)
else:
voucher = None
try:
product = StockRecord.objects.get(partner=partner, partner_sku=sku).product
course_key = product.attr.course_key
api = EdxRestApiClient(
get_lms_enrollment_base_api_url(),
oauth_access_token=request.user.access_token,
append_slash=False
)
logger.debug(
'Getting enrollment information for [%s] in [%s].',
request.user.username,
course_key
)
status = api.enrollment(','.join([request.user.username, course_key])).get()
username = request.user.username
seat_type = mode_for_seat(product)
if status and status.get('mode') == seat_type and status.get('is_active'):
logger.warning(
'User [%s] attempted to repurchase the [%s] seat of course [%s]',
username,
seat_type,
course_key
)
return HttpResponseBadRequest(_('You are already enrolled in {course}.').format(
course=product.course.name))
except StockRecord.DoesNotExist:
return HttpResponseBadRequest(_('SKU [{sku}] does not exist.').format(sku=sku))
except (ConnectionError, SlumberBaseException, Timeout) as ex:
logger.exception(
'Failed to retrieve enrollment details for [%s] in course [%s], Because of [%s]',
request.user.username,
course_key,
ex,
)
return HttpResponseBadRequest(_('An error occurred while retrieving enrollment details. Please try again.'))
purchase_info = request.strategy.fetch_for_product(product)
if not purchase_info.availability.is_available_to_buy:
return HttpResponseBadRequest(_('Product [{product}] not available to buy.').format(product=product.title))
prepare_basket(request, product, voucher)
return HttpResponseRedirect(reverse('basket:summary'), status=303)
示例8: get_course_info_from_lms
def get_course_info_from_lms(course_key):
""" Get course information from LMS via the course api and cache """
api = EdxRestApiClient(get_lms_url('api/courses/v1/'))
cache_key = 'courses_api_detail_{}'.format(course_key)
cache_hash = hashlib.md5(cache_key).hexdigest()
course = cache.get(cache_hash)
if not course: # pragma: no cover
course = api.courses(course_key).get()
cache.set(cache_hash, course, settings.COURSES_API_CACHE_TIMEOUT)
return course
示例9: get_context_data
def get_context_data(self, **kwargs):
context = super(CouponOfferView, self).get_context_data(**kwargs)
footer = get_lms_footer()
code = self.request.GET.get('code', None)
if code is not None:
voucher, product = get_voucher_from_code(code=code)
valid_voucher, msg = voucher_is_valid(voucher, product, self.request)
if valid_voucher:
api = EdxRestApiClient(
get_lms_url('api/courses/v1/'),
)
try:
course = api.courses(product.course_id).get()
except SlumberHttpBaseException as e:
logger.exception('Could not get course information. [%s]', e)
return {
'error': _('Could not get course information. [{error}]'.format(error=e)),
'footer': footer
}
course['image_url'] = get_lms_url(course['media']['course_image']['uri'])
benefit = voucher.offers.first().benefit
stock_record = benefit.range.catalog.stock_records.first()
price = stock_record.price_excl_tax
context.update(get_voucher_discount_info(benefit, price))
if benefit.type == 'Percentage':
new_price = price - (price * (benefit.value / 100))
else:
new_price = price - benefit.value
if new_price < 0:
new_price = Decimal(0)
context.update({
'benefit': benefit,
'course': course,
'code': code,
'is_discount_value_percentage': benefit.type == 'Percentage',
'is_enrollment_code': benefit.type == Benefit.PERCENTAGE and benefit.value == 100.00,
'discount_value': "%.2f" % (price - new_price),
'price': price,
'new_price': "%.2f" % new_price,
'verified': (product.attr.certificate_type == 'verified'),
'verification_deadline': product.course.verification_deadline,
'footer': footer
})
return context
return {
'error': msg,
'footer': footer
}
return {
'error': _('This coupon code is invalid.'),
'footer': footer
}
示例10: CatalogApiService
class CatalogApiService(object):
"""The service to interface with edX catalog API"""
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 = {}
def _get_resource_from_api(self, api_endpoint, page_size, **kwargs):
page = 0
results = []
while page >= 0:
response = api_endpoint.get(limit=page_size, offset=(page * page_size), **kwargs)
if response.get('next'):
page += 1
else:
page = -1
results.extend(response.get('results'))
return results
def get_courses(self):
logger.debug('Get Courses called')
return self._get_resource_from_api(self.api_client.courses(), COURSES_PAGE_SIZE, marketable=1)
def get_program_dictionary(self):
if not self._programs_dictionary:
program_array = self._get_resource_from_api(
self.api_client.programs(),
PROGRAMS_PAGE_SIZE,
marketable=1,
published_course_runs_only=1
)
for program in program_array:
self._programs_dictionary[program['uuid']] = program
return self._programs_dictionary
示例11: _publish_creditcourse
def _publish_creditcourse(self, course_id, access_token):
"""Creates or updates a CreditCourse object on the LMS."""
api = EdxRestApiClient(
get_lms_url('api/credit/v1/'),
oauth_access_token=access_token,
timeout=self.timeout
)
data = {
'course_key': course_id,
'enabled': True
}
api.courses(course_id).put(data)
示例12: _get_courses_enrollment_info
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
else:
raise
enrollment_info, next_page = _parse_response(response)
course_enrollments.update(enrollment_info)
return course_enrollments
示例13: DiscoveryApiClient
class DiscoveryApiClient(object):
"""
Class for interacting with the discovery service journals endpoint
"""
def __init__(self):
"""
Initialize an authenticated Discovery service API client by using the
provided user.
"""
catalog_integration = CatalogIntegration.current()
# Client can't be used if there is no catalog integration
if not (catalog_integration and catalog_integration.enabled):
LOGGER.error("Unable to create DiscoveryApiClient because catalog integration not set up or enabled")
return None
try:
user = catalog_integration.get_service_user()
except ObjectDoesNotExist:
LOGGER.error("Unable to retrieve catalog integration service user")
return None
jwt = JwtBuilder(user).build_token([])
base_url = configuration_helpers.get_value('COURSE_CATALOG_URL_BASE', settings.COURSE_CATALOG_URL_BASE)
self.client = EdxRestApiClient(
'{base_url}{journals_path}'.format(base_url=base_url, journals_path=JOURNALS_API_PATH),
jwt=jwt
)
def get_journals(self, orgs):
"""
get_journals from discovery, filter on orgs is supplied
"""
try:
if orgs:
response = self.client.journals.get(orgs=','.join(orgs), status='active')
else:
response = self.client.journals.get(status='active')
LOGGER.debug('response is type=%s', type(response))
return response.get('results')
except (HttpClientError, HttpServerError) as err:
LOGGER.exception(
'Failed to get journals from discovery-service [%s]',
err.content
)
return []
def get_journal_bundles(self, uuid=''):
"""
get_journal_bundles from discovery on the base of uuid (optional)
"""
try:
response = self.client.journal_bundles(uuid).get()
except (HttpClientError, HttpServerError) as err:
LOGGER.exception(
'Failed to get journal bundles from discovery-service [%s]',
err.content
)
return []
return [response] if uuid else response.get('results')
示例14: access_token
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
示例15: refresh
def refresh(cls, course_id, access_token):
"""
Refresh the course data from the raw data sources.
Args:
course_id (str): Course ID
access_token (str): OAuth access token
Returns:
Course
"""
client = EdxRestApiClient(settings.ECOMMERCE_API_URL, oauth_access_token=access_token)
body = client.courses(course_id).get(include_products=True)
course = Course(course_id, body)
course.save()
return course