本文整理汇总了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
示例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__)
示例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'
)
示例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
)
示例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 = {}
示例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)
示例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
示例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")
示例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,
#.........这里部分代码省略.........