docstring
stringlengths 52
499
| function
stringlengths 67
35.2k
| __index_level_0__
int64 52.6k
1.16M
|
|---|---|---|
Returns a WPToolsRequest object.
Arguments:
- [proxy]: <str> HTTP proxy to use
- [silent]: <bool> silent if True
- [timeout]: <int> connection timeout (0=wait forever)
- [verbose]: <bool> verbose if True
|
def __init__(self, silent=False, verbose=False, proxy=None, timeout=None):
self.silent = silent
self.verbose = verbose
self.curl_setup(proxy, timeout)
| 433,076
|
Returns a WPToolsQuery object
Arguments:
- [lang=en]: <str> Mediawiki language code
- [variant=None]: <str> language variant
- [wiki=None]: <str> alternative wiki site
- [endpoint=None]: <str> alternative API endoint
|
def __init__(self, lang='en', variant=None, wiki=None, endpoint=None):
self.lang = lang
self.variant = variant
self.wiki = wiki or "%s.wikipedia.org" % self.lang
self.domain = domain_name(self.wiki)
self.endpoint = endpoint or self.DEFAULT_ENDPOINT
self.uri = self.wiki_uri(self.wiki)
| 433,081
|
Constructor.
Args:
channel: A grpc.Channel.
|
def __init__(self, channel):
self.GetStepNames = channel.unary_unary(
'/gauge.messages.lspService/GetStepNames',
request_serializer=messages__pb2.StepNamesRequest.SerializeToString,
response_deserializer=messages__pb2.StepNamesResponse.FromString,
)
self.CacheFile = channel.unary_unary(
'/gauge.messages.lspService/CacheFile',
request_serializer=messages__pb2.CacheFileRequest.SerializeToString,
response_deserializer=lsp__pb2.Empty.FromString,
)
self.GetStepPositions = channel.unary_unary(
'/gauge.messages.lspService/GetStepPositions',
request_serializer=messages__pb2.StepPositionsRequest.SerializeToString,
response_deserializer=messages__pb2.StepPositionsResponse.FromString,
)
self.GetImplementationFiles = channel.unary_unary(
'/gauge.messages.lspService/GetImplementationFiles',
request_serializer=lsp__pb2.Empty.SerializeToString,
response_deserializer=messages__pb2.ImplementationFileListResponse.FromString,
)
self.ImplementStub = channel.unary_unary(
'/gauge.messages.lspService/ImplementStub',
request_serializer=messages__pb2.StubImplementationCodeRequest.SerializeToString,
response_deserializer=messages__pb2.FileDiff.FromString,
)
self.ValidateStep = channel.unary_unary(
'/gauge.messages.lspService/ValidateStep',
request_serializer=messages__pb2.StepValidateRequest.SerializeToString,
response_deserializer=messages__pb2.StepValidateResponse.FromString,
)
self.Refactor = channel.unary_unary(
'/gauge.messages.lspService/Refactor',
request_serializer=messages__pb2.RefactorRequest.SerializeToString,
response_deserializer=messages__pb2.RefactorResponse.FromString,
)
self.GetStepName = channel.unary_unary(
'/gauge.messages.lspService/GetStepName',
request_serializer=messages__pb2.StepNameRequest.SerializeToString,
response_deserializer=messages__pb2.StepNameResponse.FromString,
)
self.GetGlobPatterns = channel.unary_unary(
'/gauge.messages.lspService/GetGlobPatterns',
request_serializer=lsp__pb2.Empty.SerializeToString,
response_deserializer=messages__pb2.ImplementationFileGlobPatternResponse.FromString,
)
self.KillProcess = channel.unary_unary(
'/gauge.messages.lspService/KillProcess',
request_serializer=messages__pb2.KillProcessRequest.SerializeToString,
response_deserializer=lsp__pb2.Empty.FromString,
)
| 433,171
|
Delete a team membership, by ID.
Args:
membershipId(basestring): The team membership ID.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
|
def delete(self, membershipId):
check_type(membershipId, basestring, may_be_none=False)
# API request
self._session.delete(API_ENDPOINT + '/' + membershipId)
| 433,430
|
Delete a membership, by ID.
Args:
membershipId(basestring): The membership ID.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
|
def delete(self, membershipId):
check_type(membershipId, basestring)
# API request
self._session.delete(API_ENDPOINT + '/' + membershipId)
| 433,434
|
Object is an instance of one of the acceptable types or None.
Args:
o: The object to be inspected.
acceptable_types: A type or tuple of acceptable types.
may_be_none(bool): Whether or not the object may be None.
Raises:
TypeError: If the object is None and may_be_none=False, or if the
object is not an instance of one of the acceptable types.
|
def check_type(o, acceptable_types, may_be_none=True):
if not isinstance(acceptable_types, tuple):
acceptable_types = (acceptable_types,)
if may_be_none and o is None:
# Object is None, and that is OK!
pass
elif isinstance(o, acceptable_types):
# Object is an instance of an acceptable type.
pass
else:
# Object is something else.
error_message = (
"We were expecting to receive an instance of one of the following "
"types: {types}{none}; but instead we received {o} which is a "
"{o_type}.".format(
types=", ".join([repr(t.__name__) for t in acceptable_types]),
none="or 'None'" if may_be_none else "",
o=o,
o_type=repr(type(o).__name__)
)
)
raise TypeError(error_message)
| 433,441
|
Creates a dict with the inputted items; pruning any that are `None`.
Args:
*dictionaries(dict): Dictionaries of items to be pruned and included.
**items: Items to be pruned and included.
Returns:
dict: A dictionary containing all of the items with a 'non-None' value.
|
def dict_from_items_with_values(*dictionaries, **items):
dict_list = list(dictionaries)
dict_list.append(items)
result = {}
for d in dict_list:
for key, value in d.items():
if value is not None:
result[key] = value
return result
| 433,442
|
Given a dictionary or JSON string; return a dictionary.
Args:
json_data(dict, str): Input JSON object.
Returns:
A Python dictionary with the contents of the JSON object.
Raises:
TypeError: If the input object is not a dictionary or string.
|
def json_dict(json_data):
if isinstance(json_data, dict):
return json_data
elif isinstance(json_data, basestring):
return json.loads(json_data, object_hook=OrderedDict)
else:
raise TypeError(
"'json_data' must be a dictionary or valid JSON string; "
"received: {!r}".format(json_data)
)
| 433,444
|
Initialize a new RoomsAPI object with the provided RestSession.
Args:
session(RestSession): The RESTful session object to be used for
API calls to the Webex Teams service.
Raises:
TypeError: If the parameter types are incorrect.
|
def __init__(self, session, object_factory):
check_type(session, RestSession, may_be_none=False)
super(RoomsAPI, self).__init__()
self._session = session
self._object_factory = object_factory
| 433,447
|
Delete a room.
Args:
roomId(basestring): The ID of the room to be deleted.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
|
def delete(self, roomId):
check_type(roomId, basestring, may_be_none=False)
# API request
self._session.delete(API_ENDPOINT + '/' + roomId)
| 433,451
|
Function Decorator: Containerize calls to a generator function.
Args:
generator_function(func): The generator function being containerized.
Returns:
func: A wrapper function that containerizes the calls to the generator
function.
|
def generator_container(generator_function):
@functools.wraps(generator_function)
def generator_container_wrapper(*args, **kwargs):
return GeneratorContainer(generator_function, *args, **kwargs)
return generator_container_wrapper
| 433,454
|
Init a new GeneratorContainer.
Args:
generator_function(func): The generator function.
*args: The arguments passed to the generator function.
**kwargs: The keyword arguments passed to the generator function.
|
def __init__(self, generator_function, *args, **kwargs):
if not inspect.isgeneratorfunction(generator_function):
raise TypeError("generator_function must be a generator function.")
self.generator_function = generator_function
if sys.version_info[0] < 3:
self.arguments = inspect.getcallargs(
self.generator_function,
*args,
**kwargs
)
else:
signature = inspect.signature(self.generator_function)
bound_arguments = signature.bind(*args, **kwargs)
self.arguments = bound_arguments.arguments
| 433,455
|
Delete a webhook, by ID.
Args:
webhookId(basestring): The ID of the webhook to be deleted.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
|
def delete(self, webhookId):
check_type(webhookId, basestring, may_be_none=False)
# API request
self._session.delete(API_ENDPOINT + '/' + webhookId)
| 433,462
|
Update the HTTP headers used for requests in this session.
Note: Updates provided by the dictionary passed as the `headers`
parameter to this method are merged into the session headers by adding
new key-value pairs and/or updating the values of existing keys. The
session headers are not replaced by the provided dictionary.
Args:
headers(dict): Updates to the current session headers.
|
def update_headers(self, headers):
check_type(headers, dict, may_be_none=False)
self._req_session.headers.update(headers)
| 433,467
|
Given a relative or absolute URL; return an absolute URL.
Args:
url(basestring): A relative or absolute URL.
Returns:
str: An absolute URL.
|
def abs_url(self, url):
parsed_url = urllib.parse.urlparse(url)
if not parsed_url.scheme and not parsed_url.netloc:
# url is a relative URL; combine with base_url
return urllib.parse.urljoin(str(self.base_url), str(url))
else:
# url is already an absolute URL; return as is
return url
| 433,468
|
Sends a GET request.
Args:
url(basestring): The URL of the API endpoint.
params(dict): The parameters for the HTTP GET request.
**kwargs:
erc(int): The expected (success) response code for the request.
others: Passed on to the requests package.
Raises:
ApiError: If anything other than the expected response code is
returned by the Webex Teams API endpoint.
|
def get(self, url, params=None, **kwargs):
check_type(url, basestring, may_be_none=False)
check_type(params, dict)
# Expected response code
erc = kwargs.pop('erc', EXPECTED_RESPONSE_CODE['GET'])
response = self.request('GET', url, erc, params=params, **kwargs)
return extract_and_parse_json(response)
| 433,470
|
Sends a DELETE request.
Args:
url(basestring): The URL of the API endpoint.
**kwargs:
erc(int): The expected (success) response code for the request.
others: Passed on to the requests package.
Raises:
ApiError: If anything other than the expected response code is
returned by the Webex Teams API endpoint.
|
def delete(self, url, **kwargs):
check_type(url, basestring, may_be_none=False)
# Expected response code
erc = kwargs.pop('erc', EXPECTED_RESPONSE_CODE['DELETE'])
self.request('DELETE', url, erc, **kwargs)
| 433,474
|
Delete a message.
Args:
messageId(basestring): The ID of the message to be deleted.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
|
def delete(self, messageId):
check_type(messageId, basestring, may_be_none=False)
# API request
self._session.delete(API_ENDPOINT + '/' + messageId)
| 433,478
|
Initialize a new PeopleAPI object with the provided RestSession.
Args:
session(RestSession): The RESTful session object to be used for
API calls to the Webex Teams service.
Raises:
TypeError: If the parameter types are incorrect.
|
def __init__(self, session, object_factory):
check_type(session, RestSession)
super(PeopleAPI, self).__init__()
self._session = session
self._object_factory = object_factory
| 433,479
|
Get a person's details, by ID.
Args:
personId(basestring): The ID of the person to be retrieved.
Returns:
Person: A Person object with the details of the requested person.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
|
def get(self, personId):
check_type(personId, basestring, may_be_none=False)
# API request
json_data = self._session.get(API_ENDPOINT + '/' + personId)
# Return a person object created from the response JSON data
return self._object_factory(OBJECT_TYPE, json_data)
| 433,482
|
Remove a person from the system.
Only an admin can remove a person.
Args:
personId(basestring): The ID of the person to be deleted.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
|
def delete(self, personId):
check_type(personId, basestring, may_be_none=False)
# API request
self._session.delete(API_ENDPOINT + '/' + personId)
| 433,484
|
Init a new SimpleDataModel object from a dictionary or JSON string.
Args:
json_data(dict, basestring): Input JSON string or dictionary.
Raises:
TypeError: If the input object is not a dictionary or string.
|
def __init__(self, json_data):
super(SimpleDataModel, self).__init__()
for attribute, value in json_dict(json_data).items():
setattr(self, attribute, value)
| 433,486
|
List all roles.
Args:
**request_parameters: Additional request parameters (provides
support for parameters that may be added in the future).
Returns:
GeneratorContainer: A GeneratorContainer which, when iterated,
yields the roles returned by the Webex Teams query.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
|
def list(self, **request_parameters):
# API request - get items
items = self._session.get_items(
API_ENDPOINT,
params=request_parameters
)
# Yield role objects created from the returned JSON objects
for item in items:
yield self._object_factory(OBJECT_TYPE, item)
| 433,490
|
Delete a team.
Args:
teamId(basestring): The ID of the team to be deleted.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
|
def delete(self, teamId):
check_type(teamId, basestring, may_be_none=False)
# API request
self._session.delete(API_ENDPOINT + '/' + teamId)
| 433,494
|
Init a new ImmutableData object from a dictionary or JSON string.
Args:
json_data(dict, basestring): Input JSON string or dictionary.
Raises:
TypeError: If the input object is not a dictionary or string.
|
def __init__(self, json_data):
super(ImmutableData, self).__init__()
self._json_data = json_dict(json_data)
| 433,496
|
Initialize an AccessTokensAPI object with the provided RestSession.
Args:
base_url(basestring): The base URL the API endpoints.
single_request_timeout(int): Timeout in seconds for the API
requests.
Raises:
TypeError: If the parameter types are incorrect.
|
def __init__(self, base_url, object_factory, single_request_timeout=None):
check_type(base_url, basestring, may_be_none=False)
check_type(single_request_timeout, int)
super(AccessTokensAPI, self).__init__()
self._base_url = str(validate_base_url(base_url))
self._single_request_timeout = single_request_timeout
self._endpoint_url = urllib.parse.urljoin(self.base_url, API_ENDPOINT)
self._request_kwargs = {"timeout": single_request_timeout}
self._object_factory = object_factory
| 433,502
|
Called implicitly before a packet is sent to compute and place IGMPv3 checksum.
Parameters:
self The instantiation of an IGMPv3 class
p The IGMPv3 message in hex in network byte order
pay Additional payload for the IGMPv3 message
|
def post_build(self, p, pay):
p += pay
if self.type in [0, 0x31, 0x32, 0x22]: # for these, field is reserved (0)
p = p[:1]+chr(0)+p[2:]
if self.chksum is None:
ck = checksum(p[:2]+p[4:])
p = p[:2]+ck.to_bytes(2, 'big')+p[4:]
return p
| 433,513
|
Creates a Requests Session for use. Accepts a bearer token
for premiums users and will override username and password information if
present.
Args:
username (str): username for the session
password (str): password for the user
bearer_token (str): token for a premium API user.
|
def make_session(username=None, password=None, bearer_token=None, extra_headers_dict=None):
if password is None and bearer_token is None:
logger.error("No authentication information provided; "
"please check your object")
raise KeyError
session = requests.Session()
session.trust_env = False
headers = {'Accept-encoding': 'gzip',
'User-Agent': 'twitterdev-search-tweets-python/' + VERSION}
if bearer_token:
logger.info("using bearer token for authentication")
headers['Authorization'] = "Bearer {}".format(bearer_token)
session.headers = headers
else:
logger.info("using username and password for authentication")
session.auth = username, password
session.headers = headers
if extra_headers_dict:
headers.update(extra_headers_dict)
return session
| 434,381
|
Decorator to handle API retries and exceptions. Defaults to three retries.
Args:
func (function): function for decoration
Returns:
decorated function
|
def retry(func):
def retried_func(*args, **kwargs):
max_tries = 3
tries = 0
while True:
try:
resp = func(*args, **kwargs)
except requests.exceptions.ConnectionError as exc:
exc.msg = "Connection error for session; exiting"
raise exc
except requests.exceptions.HTTPError as exc:
exc.msg = "HTTP error for session; exiting"
raise exc
if resp.status_code != 200 and tries < max_tries:
logger.warning("retrying request; current status code: {}"
.format(resp.status_code))
tries += 1
# mini exponential backoff here.
time.sleep(tries ** 2)
continue
break
if resp.status_code != 200:
error_message = resp.json()["error"]["message"]
logger.error("HTTP Error code: {}: {}".format(resp.status_code, error_message))
logger.error("Rule payload: {}".format(kwargs["rule_payload"]))
raise requests.exceptions.HTTPError
return resp
return retried_func
| 434,382
|
Executes a request with the given payload and arguments.
Args:
session (requests.Session): the valid session object
url (str): Valid API endpoint
rule_payload (str or dict): rule package for the POST. If you pass a
dictionary, it will be converted into JSON.
|
def request(session, url, rule_payload, **kwargs):
if isinstance(rule_payload, dict):
rule_payload = json.dumps(rule_payload)
logger.debug("sending request")
result = session.post(url, data=rule_payload, **kwargs)
return result
| 434,383
|
Utility function to change a normal endpoint to a ``count`` api
endpoint. Returns the same endpoint if it's already a valid count endpoint.
Args:
endpoint (str): your api endpoint
Returns:
str: the modified endpoint for a count endpoint.
|
def change_to_count_endpoint(endpoint):
tokens = filter(lambda x: x != '', re.split("[/:]", endpoint))
filt_tokens = list(filter(lambda x: x != "https", tokens))
last = filt_tokens[-1].split('.')[0] # removes .json on the endpoint
filt_tokens[-1] = last # changes from *.json -> '' for changing input
if last == 'counts':
return endpoint
else:
return "https://" + '/'.join(filt_tokens) + '/' + "counts.json"
| 434,392
|
Parse a received datetime into a timezone-aware, Python datetime object.
Arguments:
datetime_string: A string to be parsed.
datetime_format: A datetime format string to be used for parsing
|
def parse_lms_api_datetime(datetime_string, datetime_format=LMS_API_DATETIME_FORMAT):
if isinstance(datetime_string, datetime.datetime):
date_time = datetime_string
else:
try:
date_time = datetime.datetime.strptime(datetime_string, datetime_format)
except ValueError:
date_time = datetime.datetime.strptime(datetime_string, LMS_API_DATETIME_FORMAT_WITHOUT_TIMEZONE)
# If the datetime format didn't include a timezone, then set to UTC.
# Note that if we're using the default LMS_API_DATETIME_FORMAT, it ends in 'Z',
# which denotes UTC for ISO-8661.
if date_time.tzinfo is None:
date_time = date_time.replace(tzinfo=timezone.utc)
return date_time
| 434,485
|
Query the Enrollment API for the course details of the given course_id.
Args:
course_id (str): The string value of the course's unique identifier
Returns:
dict: A dictionary containing details about the course, in an enrollment context (allowed modes, etc.)
|
def get_course_details(self, course_id):
try:
return self.client.course(course_id).get()
except (SlumberBaseException, ConnectionError, Timeout) as exc:
LOGGER.exception(
'Failed to retrieve course enrollment details for course [%s] due to: [%s]',
course_id, str(exc)
)
return {}
| 434,491
|
Sort the course mode dictionaries by slug according to the COURSE_MODE_SORT_ORDER constant.
Arguments:
modes (list): A list of course mode dictionaries.
Returns:
list: A list with the course modes dictionaries sorted by slug.
|
def _sort_course_modes(self, modes):
def slug_weight(mode):
sorting_slugs = COURSE_MODE_SORT_ORDER
sorting_slugs_size = len(sorting_slugs)
if mode['slug'] in sorting_slugs:
return sorting_slugs_size - sorting_slugs.index(mode['slug'])
return 0
# Sort slug weights in descending order
return sorted(modes, key=slug_weight, reverse=True)
| 434,492
|
Query the Enrollment API for the specific course modes that are available for the given course_id.
Arguments:
course_id (str): The string value of the course's unique identifier
Returns:
list: A list of course mode dictionaries.
|
def get_course_modes(self, course_id):
details = self.get_course_details(course_id)
modes = details.get('course_modes', [])
return self._sort_course_modes([mode for mode in modes if mode['slug'] not in EXCLUDED_COURSE_MODES])
| 434,493
|
Query the Enrollment API to see whether a course run has a given course mode available.
Arguments:
course_run_id (str): The string value of the course run's unique identifier
Returns:
bool: Whether the course run has the given mode avaialble for enrollment.
|
def has_course_mode(self, course_run_id, mode):
course_modes = self.get_course_modes(course_run_id)
return any(course_mode for course_mode in course_modes if course_mode['slug'] == mode)
| 434,494
|
Call the enrollment API to unenroll the user in the course specified by course_id.
Args:
username (str): The username by which the user goes on the OpenEdx platform
course_id (str): The string value of the course's unique identifier
Returns:
bool: Whether the unenrollment succeeded
|
def unenroll_user_from_course(self, username, course_id):
enrollment = self.get_course_enrollment(username, course_id)
if enrollment and enrollment['is_active']:
response = self.client.enrollment.post({
'user': username,
'course_details': {'course_id': course_id},
'is_active': False,
'mode': enrollment['mode']
})
return not response['is_active']
return False
| 434,496
|
Query the enrollment API to get information about a single course enrollment.
Args:
username (str): The username by which the user goes on the OpenEdX platform
course_id (str): The string value of the course's unique identifier
Returns:
dict: A dictionary containing details of the enrollment, including course details, mode, username, etc.
|
def get_course_enrollment(self, username, course_id):
endpoint = getattr(
self.client.enrollment,
'{username},{course_id}'.format(username=username, course_id=course_id)
)
try:
result = endpoint.get()
except HttpNotFoundError:
# This enrollment data endpoint returns a 404 if either the username or course_id specified isn't valid
LOGGER.error(
'Course enrollment details not found for invalid username or course; username=[%s], course=[%s]',
username,
course_id
)
return None
# This enrollment data endpoint returns an empty string if the username and course_id is valid, but there's
# no matching enrollment found
if not result:
LOGGER.info('Failed to find course enrollment details for user [%s] and course [%s]', username, course_id)
return None
return result
| 434,497
|
Query the enrollment API and determine if a learner is enrolled in a course run.
Args:
username (str): The username by which the user goes on the OpenEdX platform
course_run_id (str): The string value of the course's unique identifier
Returns:
bool: Indicating whether the user is enrolled in the course run. Returns False under any errors.
|
def is_enrolled(self, username, course_run_id):
enrollment = self.get_course_enrollment(username, course_run_id)
return enrollment is not None and enrollment.get('is_active', False)
| 434,498
|
Traverse a paginated API response and extracts and concatenates "results" returned by API.
Arguments:
response (dict): API response object.
endpoint (Slumber.Resource): API endpoint object.
content_filter_query (dict): query parameters used to filter catalog results.
query_params (dict): query parameters used to paginate results.
Returns:
list: all the results returned by the API.
|
def traverse_pagination(response, endpoint, content_filter_query, query_params):
results = response.get('results', [])
page = 1
while response.get('next'):
page += 1
response = endpoint().post(content_filter_query, **dict(query_params, page=page))
results += response.get('results', [])
return results
| 434,504
|
Return results from the discovery service's search/all endpoint.
Arguments:
content_filter_query (dict): query parameters used to filter catalog results.
query_params (dict): query parameters used to paginate results.
traverse_pagination (bool): True to return all results, False to return the paginated response.
Defaults to False.
Returns:
dict: Paginated response or all the records.
|
def get_catalog_results(self, content_filter_query, query_params=None, traverse_pagination=False):
query_params = query_params or {}
try:
endpoint = getattr(self.client, self.SEARCH_ALL_ENDPOINT)
response = endpoint().post(data=content_filter_query, **query_params)
if traverse_pagination:
response['results'] = self.traverse_pagination(response, endpoint, content_filter_query, query_params)
response['next'] = response['previous'] = None
except Exception as ex: # pylint: disable=broad-except
LOGGER.exception(
'Attempted to call course-discovery search/all/ endpoint with the following parameters: '
'content_filter_query: %s, query_params: %s, traverse_pagination: %s. '
'Failed to retrieve data from the catalog API. content -- [%s]',
content_filter_query,
query_params,
traverse_pagination,
getattr(ex, 'content', '')
)
# We need to bubble up failures when we encounter them instead of masking them!
raise ex
return response
| 434,505
|
Return the courses included in a single course catalog by ID.
Args:
catalog_id (int): The catalog ID we want to retrieve.
Returns:
list: Courses of the catalog in question
|
def get_catalog_courses(self, catalog_id):
return self._load_data(
self.CATALOGS_COURSES_ENDPOINT.format(catalog_id),
default=[]
)
| 434,509
|
Return the course and course run metadata for the given course run ID.
Arguments:
course_run_id (str): The course run ID.
Returns:
tuple: The course metadata and the course run metadata.
|
def get_course_and_course_run(self, course_run_id):
# Parse the course ID from the course run ID.
course_id = parse_course_key(course_run_id)
# Retrieve the course metadata from the catalog service.
course = self.get_course_details(course_id)
course_run = None
if course:
# Find the specified course run.
course_run = None
course_runs = [course_run for course_run in course['course_runs'] if course_run['key'] == course_run_id]
if course_runs:
course_run = course_runs[0]
return course, course_run
| 434,510
|
Return the details of a single course by id - not a course run id.
Args:
course_id (str): The unique id for the course in question.
Returns:
dict: Details of the course in question.
|
def get_course_details(self, course_id):
return self._load_data(
self.COURSES_ENDPOINT,
resource_id=course_id,
many=False
)
| 434,511
|
Return single program by name, or None if not found.
Arguments:
program_title(string): Program title as seen by students and in Course Catalog Admin
Returns:
dict: Program data provided by Course Catalog API
|
def get_program_by_title(self, program_title):
all_programs = self._load_data(self.PROGRAMS_ENDPOINT, default=[])
matching_programs = [program for program in all_programs if program.get('title') == program_title]
if len(matching_programs) > 1:
raise MultipleProgramMatchError(len(matching_programs))
elif len(matching_programs) == 1:
return matching_programs[0]
else:
return None
| 434,512
|
Return single program by UUID, or None if not found.
Arguments:
program_uuid(string): Program UUID in string form
Returns:
dict: Program data provided by Course Catalog API
|
def get_program_by_uuid(self, program_uuid):
return self._load_data(
self.PROGRAMS_ENDPOINT,
resource_id=program_uuid,
default=None
)
| 434,513
|
Get a list of the course IDs (not course run IDs) contained in the program.
Arguments:
program_uuid (str): Program UUID in string form
Returns:
list(str): List of course keys in string form that are included in the program
|
def get_program_course_keys(self, program_uuid):
program_details = self.get_program_by_uuid(program_uuid)
if not program_details:
return []
return [course['key'] for course in program_details.get('courses', [])]
| 434,514
|
Get a program type by its slug.
Arguments:
slug (str): The slug to identify the program type.
Returns:
dict: A program type object.
|
def get_program_type_by_slug(self, slug):
return self._load_data(
self.PROGRAM_TYPES_ENDPOINT,
resource_id=slug,
default=None,
)
| 434,515
|
Determine if the given course or course run ID is contained in the catalog with the given ID.
Args:
catalog_id (int): The ID of the catalog
course_id (str): The ID of the course or course run
Returns:
bool: Whether the course or course run is contained in the given catalog
|
def is_course_in_catalog(self, catalog_id, course_id):
try:
# Determine if we have a course run ID, rather than a plain course ID
course_run_id = str(CourseKey.from_string(course_id))
except InvalidKeyError:
course_run_id = None
endpoint = self.client.catalogs(catalog_id).contains
if course_run_id:
resp = endpoint.get(course_run_id=course_run_id)
else:
resp = endpoint.get(course_id=course_id)
return resp.get('courses', {}).get(course_id, False)
| 434,517
|
Load data from API client.
Arguments:
resource(string): type of resource to load
default(any): value to return if API query returned empty result. Sensible values: [], {}, None etc.
Returns:
dict: Deserialized response from Course Catalog API
|
def _load_data(self, resource, default=DEFAULT_VALUE_SAFEGUARD, **kwargs):
default_val = default if default != self.DEFAULT_VALUE_SAFEGUARD else {}
try:
return get_edx_api_data(
api_config=CatalogIntegration.current(),
resource=resource,
api=self.client,
**kwargs
) or default_val
except (SlumberBaseException, ConnectionError, Timeout) as exc:
LOGGER.exception(
'Failed to load data from resource [%s] with kwargs [%s] due to: [%s]',
resource, kwargs, str(exc)
)
return default_val
| 434,518
|
Return all content metadata contained in the catalogs associated with the EnterpriseCustomer.
Arguments:
enterprise_customer (EnterpriseCustomer): The EnterpriseCustomer to return content metadata for.
Returns:
list: List of dicts containing content metadata.
|
def get_content_metadata(self, enterprise_customer):
content_metadata = OrderedDict()
# TODO: This if block can be removed when we get rid of discovery service-based catalogs.
if enterprise_customer.catalog:
response = self._load_data(
self.ENTERPRISE_CUSTOMER_ENDPOINT,
detail_resource='courses',
resource_id=str(enterprise_customer.uuid),
traverse_pagination=True,
)
for course in response['results']:
for course_run in course['course_runs']:
course_run['content_type'] = 'courserun' # Make this look like a search endpoint result.
content_metadata[course_run['key']] = course_run
for enterprise_customer_catalog in enterprise_customer.enterprise_customer_catalogs.all():
response = self._load_data(
self.ENTERPRISE_CUSTOMER_CATALOGS_ENDPOINT,
resource_id=str(enterprise_customer_catalog.uuid),
traverse_pagination=True,
querystring={'page_size': 1000},
)
for item in response['results']:
content_id = utils.get_content_metadata_item_id(item)
content_metadata[content_id] = item
return content_metadata.values()
| 434,520
|
Serialize the EnterpriseCustomerCatalog object.
Arguments:
instance (EnterpriseCustomerCatalog): The EnterpriseCustomerCatalog to serialize.
Returns:
dict: The EnterpriseCustomerCatalog converted to a dict.
|
def to_representation(self, instance):
request = self.context['request']
enterprise_customer = instance.enterprise_customer
representation = super(EnterpriseCustomerCatalogDetailSerializer, self).to_representation(instance)
# Retrieve the EnterpriseCustomerCatalog search results from the discovery service.
paginated_content = instance.get_paginated_content(request.GET)
count = paginated_content['count']
search_results = paginated_content['results']
for item in search_results:
content_type = item['content_type']
marketing_url = item.get('marketing_url')
if marketing_url:
item['marketing_url'] = utils.update_query_parameters(
marketing_url, utils.get_enterprise_utm_context(enterprise_customer)
)
# Add the Enterprise enrollment URL to each content item returned from the discovery service.
if content_type == 'course':
item['enrollment_url'] = instance.get_course_enrollment_url(item['key'])
if content_type == 'courserun':
item['enrollment_url'] = instance.get_course_run_enrollment_url(item['key'])
if content_type == 'program':
item['enrollment_url'] = instance.get_program_enrollment_url(item['uuid'])
# Build pagination URLs
previous_url = None
next_url = None
page = int(request.GET.get('page', '1'))
request_uri = request.build_absolute_uri()
if paginated_content['previous']:
previous_url = utils.update_query_parameters(request_uri, {'page': page - 1})
if paginated_content['next']:
next_url = utils.update_query_parameters(request_uri, {'page': page + 1})
representation['count'] = count
representation['previous'] = previous_url
representation['next'] = next_url
representation['results'] = search_results
return representation
| 434,539
|
Return the updated course data dictionary.
Arguments:
instance (dict): The course data.
Returns:
dict: The updated course data.
|
def to_representation(self, instance):
updated_course = copy.deepcopy(instance)
enterprise_customer_catalog = self.context['enterprise_customer_catalog']
updated_course['enrollment_url'] = enterprise_customer_catalog.get_course_enrollment_url(
updated_course['key']
)
for course_run in updated_course['course_runs']:
course_run['enrollment_url'] = enterprise_customer_catalog.get_course_run_enrollment_url(
course_run['key']
)
return updated_course
| 434,543
|
Return the updated course run data dictionary.
Arguments:
instance (dict): The course run data.
Returns:
dict: The updated course run data.
|
def to_representation(self, instance):
updated_course_run = copy.deepcopy(instance)
enterprise_customer_catalog = self.context['enterprise_customer_catalog']
updated_course_run['enrollment_url'] = enterprise_customer_catalog.get_course_run_enrollment_url(
updated_course_run['key']
)
return updated_course_run
| 434,544
|
Return the updated program data dictionary.
Arguments:
instance (dict): The program data.
Returns:
dict: The updated program data.
|
def to_representation(self, instance):
updated_program = copy.deepcopy(instance)
enterprise_customer_catalog = self.context['enterprise_customer_catalog']
updated_program['enrollment_url'] = enterprise_customer_catalog.get_program_enrollment_url(
updated_program['uuid']
)
for course in updated_program['courses']:
course['enrollment_url'] = enterprise_customer_catalog.get_course_enrollment_url(course['key'])
for course_run in course['course_runs']:
course_run['enrollment_url'] = enterprise_customer_catalog.get_course_run_enrollment_url(
course_run['key']
)
return updated_program
| 434,545
|
Update pagination links in course catalog data and return DRF Response.
Arguments:
data (dict): Dictionary containing catalog courses.
request (HttpRequest): Current request object.
Returns:
(Response): DRF response object containing pagination links.
|
def get_paginated_response(data, request):
url = urlparse(request.build_absolute_uri())._replace(query=None).geturl()
next_page = None
previous_page = None
if data['next']:
next_page = "{base_url}?{query_parameters}".format(
base_url=url,
query_parameters=urlparse(data['next']).query,
)
next_page = next_page.rstrip('?')
if data['previous']:
previous_page = "{base_url}?{query_parameters}".format(
base_url=url,
query_parameters=urlparse(data['previous'] or "").query,
)
previous_page = previous_page.rstrip('?')
return Response(OrderedDict([
('count', data['count']),
('next', next_page),
('previous', previous_page),
('results', data['results'])
]))
| 434,555
|
Send a completion status call to SAP SuccessFactors using the client.
Args:
payload: The learner completion data payload to send to SAP SuccessFactors
|
def transmit(self, payload, **kwargs):
kwargs['app_label'] = 'sap_success_factors'
kwargs['model_name'] = 'SapSuccessFactorsLearnerDataTransmissionAudit'
kwargs['remote_user_id'] = 'sapsf_user_id'
super(SapSuccessFactorsLearnerTransmitter, self).transmit(payload, **kwargs)
| 434,560
|
Update course metadata of the given course and return updated course.
Arguments:
course (dict): Course Metadata returned by course catalog API
enterprise_customer (EnterpriseCustomer): enterprise customer instance.
enterprise_context (dict): Enterprise context to be added to course runs and URLs..
Returns:
(dict): Updated course metadata
|
def update_course(self, course, enterprise_customer, enterprise_context):
course['course_runs'] = self.update_course_runs(
course_runs=course.get('course_runs') or [],
enterprise_customer=enterprise_customer,
enterprise_context=enterprise_context,
)
# Update marketing urls in course metadata to include enterprise related info (i.e. our global context).
marketing_url = course.get('marketing_url')
if marketing_url:
query_parameters = dict(enterprise_context, **utils.get_enterprise_utm_context(enterprise_customer))
course.update({'marketing_url': utils.update_query_parameters(marketing_url, query_parameters)})
# Finally, add context to the course as a whole.
course.update(enterprise_context)
return course
| 434,567
|
Update Marketing urls in course metadata and return updated course.
Arguments:
course_runs (list): List of course runs.
enterprise_customer (EnterpriseCustomer): enterprise customer instance.
enterprise_context (dict): The context to inject into URLs.
Returns:
(dict): Dictionary containing updated course metadata.
|
def update_course_runs(self, course_runs, enterprise_customer, enterprise_context):
updated_course_runs = []
for course_run in course_runs:
track_selection_url = utils.get_course_track_selection_url(
course_run=course_run,
query_parameters=dict(enterprise_context, **utils.get_enterprise_utm_context(enterprise_customer)),
)
enrollment_url = enterprise_customer.get_course_run_enrollment_url(course_run.get('key'))
course_run.update({
'enrollment_url': enrollment_url,
'track_selection_url': track_selection_url,
})
# Update marketing urls in course metadata to include enterprise related info.
marketing_url = course_run.get('marketing_url')
if marketing_url:
query_parameters = dict(enterprise_context, **utils.get_enterprise_utm_context(enterprise_customer))
course_run.update({'marketing_url': utils.update_query_parameters(marketing_url, query_parameters)})
# Add updated course run to the list.
updated_course_runs.append(course_run)
return updated_course_runs
| 434,568
|
Store the data needed to export the learner data to the integrated channel.
Arguments:
* ``user``: User instance with access to the Grades API for the Enterprise Customer's courses.
* ``enterprise_configuration``: EnterpriseCustomerPluginConfiguration instance for the current channel.
|
def __init__(self, user, enterprise_configuration):
# The Grades API and Certificates API clients require an OAuth2 access token,
# so cache the client to allow the token to be reused. Cache other clients for
# general reuse.
self.grades_api = None
self.certificates_api = None
self.course_api = None
self.course_enrollment_api = None
super(LearnerExporter, self).__init__(user, enterprise_configuration)
| 434,569
|
Get enterprise user id from user object.
Arguments:
obj (User): Django User object
Returns:
(int): Primary Key identifier for enterprise user object.
|
def get_enterprise_user_id(self, obj):
# An enterprise learner can not belong to multiple enterprise customer at the same time
# but if such scenario occurs we will pick the first.
enterprise_learner = EnterpriseCustomerUser.objects.filter(user_id=obj.id).first()
return enterprise_learner and enterprise_learner.id
| 434,574
|
Get enterprise SSO UID.
Arguments:
obj (User): Django User object
Returns:
(str): string containing UUID for enterprise customer's Identity Provider.
|
def get_enterprise_sso_uid(self, obj):
# An enterprise learner can not belong to multiple enterprise customer at the same time
# but if such scenario occurs we will pick the first.
enterprise_learner = EnterpriseCustomerUser.objects.filter(user_id=obj.id).first()
return enterprise_learner and enterprise_learner.get_remote_id()
| 434,575
|
Get course's duration as a timedelta.
Arguments:
obj (CourseOverview): CourseOverview object
Returns:
(timedelta): Duration of a course.
|
def get_course_duration(self, obj):
duration = obj.end - obj.start if obj.start and obj.end else None
if duration:
return strfdelta(duration, '{W} weeks {D} days.')
return ''
| 434,576
|
Remove content metadata items from the `items_to_create`, `items_to_update`, `items_to_delete` dicts.
Arguments:
failed_items (list): Failed Items to be removed.
items_to_create (dict): dict containing the items created successfully.
items_to_update (dict): dict containing the items updated successfully.
items_to_delete (dict): dict containing the items deleted successfully.
|
def _remove_failed_items(self, failed_items, items_to_create, items_to_update, items_to_delete):
for item in failed_items:
content_metadata_id = item['courseID']
items_to_create.pop(content_metadata_id, None)
items_to_update.pop(content_metadata_id, None)
items_to_delete.pop(content_metadata_id, None)
| 434,579
|
Send xAPI analytics data of the enterprise learners to the given LRS.
Arguments:
lrs_configuration (XAPILRSConfiguration): Configuration object containing LRS configurations
of the LRS where to send xAPI learner analytics.
days (int): Include course enrollment of this number of days.
|
def send_xapi_statements(self, lrs_configuration, days):
for course_enrollment in self.get_course_enrollments(lrs_configuration.enterprise_customer, days):
try:
send_course_enrollment_statement(lrs_configuration, course_enrollment)
except ClientError:
LOGGER.exception(
'Client error while sending course enrollment to xAPI for'
' enterprise customer {enterprise_customer}.'.format(
enterprise_customer=lrs_configuration.enterprise_customer.name
)
)
| 434,582
|
Get course enrollments for all the learners of given enterprise customer.
Arguments:
enterprise_customer (EnterpriseCustomer): Include Course enrollments for learners
of this enterprise customer.
days (int): Include course enrollment of this number of days.
Returns:
(list): A list of CourseEnrollment objects.
|
def get_course_enrollments(self, enterprise_customer, days):
return CourseEnrollment.objects.filter(
created__gt=datetime.datetime.now() - datetime.timedelta(days=days)
).filter(
user_id__in=enterprise_customer.enterprise_customer_users.values_list('user_id', flat=True)
)
| 434,583
|
Instantiate a new client.
Args:
enterprise_configuration (DegreedEnterpriseCustomerConfiguration): An enterprise customers's
configuration model for connecting with Degreed
|
def __init__(self, enterprise_configuration):
super(DegreedAPIClient, self).__init__(enterprise_configuration)
self.global_degreed_config = apps.get_model('degreed', 'DegreedGlobalConfiguration').current()
self.session = None
self.expires_at = None
| 434,591
|
Send a completion status payload to the Degreed Completion Status endpoint
Args:
user_id: Unused.
payload: JSON encoded object (serialized from DegreedLearnerDataTransmissionAudit)
containing completion status fields per Degreed documentation.
Returns:
A tuple containing the status code and the body of the response.
Raises:
HTTPError: if we received a failure response code from Degreed
|
def create_course_completion(self, user_id, payload): # pylint: disable=unused-argument
return self._post(
urljoin(
self.enterprise_configuration.degreed_base_url,
self.global_degreed_config.completion_status_api_path
),
payload,
self.COMPLETION_PROVIDER_SCOPE
)
| 434,592
|
Synchronize content metadata using the Degreed course content API.
Args:
serialized_data: JSON-encoded object containing content metadata.
http_method: The HTTP method to use for the API request.
Raises:
ClientError: If Degreed API request fails.
|
def _sync_content_metadata(self, serialized_data, http_method):
try:
status_code, response_body = getattr(self, '_' + http_method)(
urljoin(self.enterprise_configuration.degreed_base_url, self.global_degreed_config.course_api_path),
serialized_data,
self.CONTENT_PROVIDER_SCOPE
)
except requests.exceptions.RequestException as exc:
raise ClientError(
'DegreedAPIClient request failed: {error} {message}'.format(
error=exc.__class__.__name__,
message=str(exc)
)
)
if status_code >= 400:
raise ClientError(
'DegreedAPIClient request failed with status {status_code}: {message}'.format(
status_code=status_code,
message=response_body
)
)
| 434,594
|
Make a POST request using the session object to a Degreed endpoint.
Args:
url (str): The url to send a POST request to.
data (str): The json encoded payload to POST.
scope (str): Must be one of the scopes Degreed expects:
- `CONTENT_PROVIDER_SCOPE`
- `COMPLETION_PROVIDER_SCOPE`
|
def _post(self, url, data, scope):
self._create_session(scope)
response = self.session.post(url, data=data)
return response.status_code, response.text
| 434,595
|
Make a DELETE request using the session object to a Degreed endpoint.
Args:
url (str): The url to send a DELETE request to.
data (str): The json encoded payload to DELETE.
scope (str): Must be one of the scopes Degreed expects:
- `CONTENT_PROVIDER_SCOPE`
- `COMPLETION_PROVIDER_SCOPE`
|
def _delete(self, url, data, scope):
self._create_session(scope)
response = self.session.delete(url, data=data)
return response.status_code, response.text
| 434,596
|
Retrieve the list of entitlements available to this learner.
Only those entitlements are returned that satisfy enterprise customer's data sharing setting.
Arguments:
request (HttpRequest): Reference to in-progress request instance.
pk (Int): Primary key value of the selected enterprise learner.
Returns:
(HttpResponse): Response object containing a list of learner's entitlements.
|
def entitlements(self, request, pk=None): # pylint: disable=invalid-name,unused-argument
enterprise_customer_user = self.get_object()
instance = {"entitlements": enterprise_customer_user.entitlements}
serializer = serializers.EnterpriseCustomerUserEntitlementSerializer(instance, context={'request': request})
return Response(serializer.data)
| 434,604
|
DRF view to list all catalogs.
Arguments:
request (HttpRequest): Current request
Returns:
(Response): DRF response object containing course catalogs.
|
def list(self, request):
catalog_api = CourseCatalogApiClient(request.user)
catalogs = catalog_api.get_paginated_catalogs(request.GET)
self.ensure_data_exists(request, catalogs)
serializer = serializers.ResponsePaginationSerializer(catalogs)
return get_paginated_response(serializer.data, request)
| 434,612
|
DRF view to get catalog details.
Arguments:
request (HttpRequest): Current request
pk (int): Course catalog identifier
Returns:
(Response): DRF response object containing course catalogs.
|
def retrieve(self, request, pk=None): # pylint: disable=invalid-name
catalog_api = CourseCatalogApiClient(request.user)
catalog = catalog_api.get_catalog(pk)
self.ensure_data_exists(
request,
catalog,
error_message=(
"Unable to fetch API response for given catalog from endpoint '/catalog/{pk}/'. "
"The resource you are looking for does not exist.".format(pk=pk)
)
)
serializer = self.serializer_class(catalog)
return Response(serializer.data)
| 434,613
|
Delete the file if it already exist and returns the enterprise customer logo image path.
Arguments:
instance (:class:`.EnterpriseCustomerBrandingConfiguration`): EnterpriseCustomerBrandingConfiguration object
filename (str): file to upload
Returns:
path: path of image file e.g. enterprise/branding/<model.id>/<model_id>_logo.<ext>.lower()
|
def logo_path(instance, filename):
extension = os.path.splitext(filename)[1].lower()
instance_id = str(instance.id)
fullname = os.path.join("enterprise/branding/", instance_id, instance_id + "_logo" + extension)
if default_storage.exists(fullname):
default_storage.delete(fullname)
return fullname
| 434,631
|
Send xAPI statement for course enrollment.
Arguments:
lrs_configuration (XAPILRSConfiguration): XAPILRSConfiguration instance where to send statements.
course_enrollment (CourseEnrollment): Course enrollment object.
|
def send_course_enrollment_statement(lrs_configuration, course_enrollment):
user_details = LearnerInfoSerializer(course_enrollment.user)
course_details = CourseInfoSerializer(course_enrollment.course)
statement = LearnerCourseEnrollmentStatement(
course_enrollment.user,
course_enrollment.course,
user_details.data,
course_details.data,
)
EnterpriseXAPIClient(lrs_configuration).save_statement(statement)
| 434,639
|
Send xAPI statement for course completion.
Arguments:
lrs_configuration (XAPILRSConfiguration): XAPILRSConfiguration instance where to send statements.
user (User): Django User object.
course_overview (CourseOverview): Course over view object containing course details.
course_grade (CourseGrade): course grade object.
|
def send_course_completion_statement(lrs_configuration, user, course_overview, course_grade):
user_details = LearnerInfoSerializer(user)
course_details = CourseInfoSerializer(course_overview)
statement = LearnerCourseCompletionStatement(
user,
course_overview,
user_details.data,
course_details.data,
course_grade,
)
EnterpriseXAPIClient(lrs_configuration).save_statement(statement)
| 434,640
|
Parse csv file and return a stream of dictionaries representing each row.
First line of CSV file must contain column headers.
Arguments:
file_stream: input file
expected_columns (set[unicode]): columns that are expected to be present
Yields:
dict: CSV line parsed into a dictionary.
|
def parse_csv(file_stream, expected_columns=None):
reader = unicodecsv.DictReader(file_stream, encoding="utf-8")
if expected_columns and set(expected_columns) - set(reader.fieldnames):
raise ValidationError(ValidationMessages.MISSING_EXPECTED_COLUMNS.format(
expected_columns=", ".join(expected_columns), actual_columns=", ".join(reader.fieldnames)
))
# "yield from reader" would be nicer, but we're on python2.7 yet.
for row in reader:
yield row
| 434,656
|
Return course runs from program data.
Arguments:
program(dict): Program data from Course Catalog API
Returns:
set: course runs in given program
|
def get_course_runs_from_program(program):
course_runs = set()
for course in program.get("courses", []):
for run in course.get("course_runs", []):
if "key" in run and run["key"]:
course_runs.add(run["key"])
return course_runs
| 434,659
|
Returns paginated list.
Arguments:
object_list (QuerySet): A list of records to be paginated.
page (int): Current page number.
page_size (int): Number of records displayed in each paginated set.
show_all (bool): Whether to show all records.
Adopted from django/contrib/admin/templatetags/admin_list.py
https://github.com/django/django/blob/1.11.1/django/contrib/admin/templatetags/admin_list.py#L50
|
def paginated_list(object_list, page, page_size=25):
paginator = CustomPaginator(object_list, page_size)
try:
object_list = paginator.page(page)
except PageNotAnInteger:
object_list = paginator.page(1)
except EmptyPage:
object_list = paginator.page(paginator.num_pages)
page_range = []
page_num = object_list.number
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
if page_num > (PAGES_ON_EACH_SIDE + PAGES_ON_ENDS + 1):
page_range.extend(range(1, PAGES_ON_ENDS + 1))
page_range.append(DOT)
page_range.extend(range(page_num - PAGES_ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(1, page_num + 1))
if page_num < (paginator.num_pages - PAGES_ON_EACH_SIDE - PAGES_ON_ENDS):
page_range.extend(range(page_num + 1, page_num + PAGES_ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages + 1 - PAGES_ON_ENDS, paginator.num_pages + 1))
else:
page_range.extend(range(page_num + 1, paginator.num_pages + 1))
# Override page range to implement custom smart links.
object_list.paginator.page_range = page_range
return object_list
| 434,661
|
Initializes form: puts current user and enterprise_customer into a
field for later access.
Arguments:
user (django.contrib.auth.models.User): current user
enterprise_customer (enterprise.models.EnterpriseCustomer): current customer
|
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
self._user = user
self._enterprise_customer = kwargs.pop('enterprise_customer', None)
super(ManageLearnersForm, self).__init__(*args, **kwargs)
| 434,662
|
Task to send content metadata to each linked integrated channel.
Arguments:
username (str): The username of the User to be used for making API requests to retrieve content metadata.
channel_code (str): Capitalized identifier for the integrated channel.
channel_pk (str): Primary key for identifying integrated channel.
|
def transmit_content_metadata(username, channel_code, channel_pk):
start = time.time()
api_user = User.objects.get(username=username)
integrated_channel = INTEGRATED_CHANNEL_CHOICES[channel_code].objects.get(pk=channel_pk)
LOGGER.info('Transmitting content metadata to integrated channel using configuration: [%s]', integrated_channel)
try:
integrated_channel.transmit_content_metadata(api_user)
except Exception: # pylint: disable=broad-except
LOGGER.exception(
'Transmission of content metadata failed for user [%s] and for integrated '
'channel with code [%s] and id [%s].', username, channel_code, channel_pk
)
duration = time.time() - start
LOGGER.info(
'Content metadata transmission task for integrated channel configuration [%s] took [%s] seconds',
integrated_channel,
duration
)
| 434,705
|
Task to send learner data to each linked integrated channel.
Arguments:
username (str): The username of the User to be used for making API requests for learner data.
channel_code (str): Capitalized identifier for the integrated channel
channel_pk (str): Primary key for identifying integrated channel
|
def transmit_learner_data(username, channel_code, channel_pk):
start = time.time()
api_user = User.objects.get(username=username)
integrated_channel = INTEGRATED_CHANNEL_CHOICES[channel_code].objects.get(pk=channel_pk)
LOGGER.info('Processing learners for integrated channel using configuration: [%s]', integrated_channel)
# Note: learner data transmission code paths don't raise any uncaught exception, so we don't need a broad
# try-except block here.
integrated_channel.transmit_learner_data(api_user)
duration = time.time() - start
LOGGER.info(
'Learner data transmission task for integrated channel configuration [%s] took [%s] seconds',
integrated_channel,
duration
)
| 434,706
|
Task to unlink inactive learners of provided integrated channel.
Arguments:
channel_code (str): Capitalized identifier for the integrated channel
channel_pk (str): Primary key for identifying integrated channel
|
def unlink_inactive_learners(channel_code, channel_pk):
start = time.time()
integrated_channel = INTEGRATED_CHANNEL_CHOICES[channel_code].objects.get(pk=channel_pk)
LOGGER.info('Processing learners to unlink inactive users using configuration: [%s]', integrated_channel)
# Note: learner data transmission code paths don't raise any uncaught exception, so we don't need a broad
# try-except block here.
integrated_channel.unlink_inactive_learners()
duration = time.time() - start
LOGGER.info(
'Unlink inactive learners task for integrated channel configuration [%s] took [%s] seconds',
integrated_channel,
duration
)
| 434,707
|
Send a completion status call to Degreed using the client.
Args:
payload: The learner completion data payload to send to Degreed
|
def transmit(self, payload, **kwargs):
kwargs['app_label'] = 'degreed'
kwargs['model_name'] = 'DegreedLearnerDataTransmissionAudit'
kwargs['remote_user_id'] = 'degreed_user_email'
super(DegreedLearnerTransmitter, self).transmit(payload, **kwargs)
| 434,726
|
Perform the linking of user in the process of logging to the Enterprise Customer.
Args:
backend: The class handling the SSO interaction (SAML, OAuth, etc)
user: The user object in the process of being logged in with
**kwargs: Any remaining pipeline variables
|
def handle_enterprise_logistration(backend, user, **kwargs):
request = backend.strategy.request
enterprise_customer = get_enterprise_customer_for_running_pipeline(
request,
{
'backend': backend.name,
'kwargs': kwargs
}
)
if enterprise_customer is None:
# This pipeline element is not being activated as a part of an Enterprise logistration
return
# proceed with the creation of a link between the user and the enterprise customer, then exit.
enterprise_customer_user, _ = EnterpriseCustomerUser.objects.update_or_create(
enterprise_customer=enterprise_customer,
user_id=user.id
)
enterprise_customer_user.update_session(request)
| 434,728
|
Find the LMS user from the LMS model `UserSocialAuth`.
Arguments:
tpa_provider (third_party_auth.provider): third party auth provider object
tpa_username (str): Username returned by the third party auth
|
def get_user_from_social_auth(tpa_provider, tpa_username):
user_social_auth = UserSocialAuth.objects.select_related('user').filter(
user__username=tpa_username, provider=tpa_provider.backend_name
).first()
return user_social_auth.user if user_social_auth else None
| 434,729
|
Instantiate a new client.
Args:
enterprise_configuration (SAPSuccessFactorsEnterpriseCustomerConfiguration): An enterprise customers's
configuration model for connecting with SAP SuccessFactors
|
def __init__(self, enterprise_configuration):
super(SAPSuccessFactorsAPIClient, self).__init__(enterprise_configuration)
self.global_sap_config = apps.get_model('sap_success_factors', 'SAPSuccessFactorsGlobalConfiguration').current()
self._create_session()
| 434,731
|
Create/update/delete content metadata records using the SuccessFactors OCN Course Import API endpoint.
Arguments:
serialized_data: Serialized JSON string representing a list of content metadata items.
Raises:
ClientError: If SuccessFactors API call fails.
|
def _sync_content_metadata(self, serialized_data):
url = self.enterprise_configuration.sapsf_base_url + self.global_sap_config.course_api_path
try:
status_code, response_body = self._call_post_with_session(url, serialized_data)
except requests.exceptions.RequestException as exc:
raise ClientError(
'SAPSuccessFactorsAPIClient request failed: {error} {message}'.format(
error=exc.__class__.__name__,
message=str(exc)
)
)
if status_code >= 400:
raise ClientError(
'SAPSuccessFactorsAPIClient request failed with status {status_code}: {message}'.format(
status_code=status_code,
message=response_body
)
)
| 434,734
|
Make a post request with an auth token acquired for a specific user to a SuccessFactors endpoint.
Args:
sap_user_id (str): The user to use to retrieve an auth token.
url (str): The url to post to.
payload (str): The json encoded payload to post.
|
def _call_post_with_user_override(self, sap_user_id, url, payload):
SAPSuccessFactorsEnterpriseCustomerConfiguration = apps.get_model( # pylint: disable=invalid-name
'sap_success_factors',
'SAPSuccessFactorsEnterpriseCustomerConfiguration'
)
oauth_access_token, _ = SAPSuccessFactorsAPIClient.get_oauth_access_token(
self.enterprise_configuration.sapsf_base_url,
self.enterprise_configuration.key,
self.enterprise_configuration.secret,
self.enterprise_configuration.sapsf_company_id,
sap_user_id,
SAPSuccessFactorsEnterpriseCustomerConfiguration.USER_TYPE_USER
)
response = requests.post(
url,
data=payload,
headers={
'Authorization': 'Bearer {}'.format(oauth_access_token),
'content-type': 'application/json'
}
)
return response.status_code, response.text
| 434,735
|
Make a post request using the session object to a SuccessFactors endpoint.
Args:
url (str): The url to post to.
payload (str): The json encoded payload to post.
|
def _call_post_with_session(self, url, payload):
now = datetime.datetime.utcnow()
if now >= self.expires_at:
# Create a new session with a valid token
self.session.close()
self._create_session()
response = self.session.post(url, data=payload)
return response.status_code, response.text
| 434,736
|
Add message to request indicating that there was an issue processing request.
Arguments:
request: The current request.
|
def add_generic_info_message_for_error(request):
messages.info(
request,
_(
'{strong_start}Something happened.{strong_end} '
'{span_start}This course link is currently invalid. '
'Please reach out to your Administrator for assistance to this course.{span_end}'
).format(
span_start='<span>',
span_end='</span>',
strong_start='<strong>',
strong_end='</strong>',
)
)
| 434,746
|
Add message to request indicating that there was an issue processing request.
Arguments:
request: The current request.
error_code: A string error code to be used to point devs to the spot in
the code where this error occurred.
|
def add_generic_error_message_with_code(request, error_code):
messages.error(
request,
_(
'{strong_start}Something happened.{strong_end} '
'{span_start}Please reach out to your learning administrator with '
'the following error code and they will be able to help you out.{span_end}'
'{span_start}Error code: {error_code}{span_end}'
).format(
error_code=error_code,
strong_start='<strong>',
strong_end='</strong>',
span_start='<span>',
span_end='</span>',
)
)
| 434,747
|
Store the data needed to export the learner data to the integrated channel.
Arguments:
* user: User instance with access to the Grades API for the Enterprise Customer's courses.
* enterprise_configuration - The configuration connecting an enterprise to an integrated channel.
|
def __init__(self, user, enterprise_configuration):
self.user = user
self.enterprise_configuration = enterprise_configuration
self.enterprise_customer = enterprise_configuration.enterprise_customer
| 434,751
|
Get result for the statement.
Arguments:
course_grade (CourseGrade): Course grade.
|
def get_result(self, course_grade):
return Result(
score=Score(
scaled=course_grade.percent,
raw=course_grade.percent * 100,
min=MIN_SCORE,
max=MAX_SCORE,
),
success=course_grade.passed,
completion=course_grade.passed
)
| 434,759
|
Handle GET request - render "Transmit courses metadata" form.
Arguments:
request (django.http.request.HttpRequest): Request instance
enterprise_customer_uuid (str): Enterprise Customer UUID
Returns:
django.http.response.HttpResponse: HttpResponse
|
def get(self, request, enterprise_customer_uuid):
context = self._build_context(request, enterprise_customer_uuid)
transmit_courses_metadata_form = TransmitEnterpriseCoursesForm()
context.update({self.ContextParameters.TRANSMIT_COURSES_METADATA_FORM: transmit_courses_metadata_form})
return render(request, self.template, context)
| 434,767
|
Handle POST request - handle form submissions.
Arguments:
request (django.http.request.HttpRequest): Request instance
enterprise_customer_uuid (str): Enterprise Customer UUID
|
def post(self, request, enterprise_customer_uuid):
transmit_courses_metadata_form = TransmitEnterpriseCoursesForm(request.POST)
# check that form data is well-formed
if transmit_courses_metadata_form.is_valid():
channel_worker_username = transmit_courses_metadata_form.cleaned_data['channel_worker_username']
# call `transmit_content_metadata` management command to trigger
# transmission of enterprise courses metadata
call_command(
'transmit_content_metadata',
'--catalog_user', channel_worker_username,
enterprise_customer=enterprise_customer_uuid
)
# Redirect to GET
return HttpResponseRedirect('')
context = self._build_context(request, enterprise_customer_uuid)
context.update({self.ContextParameters.TRANSMIT_COURSES_METADATA_FORM: transmit_courses_metadata_form})
return render(request, self.template, context)
| 434,768
|
Get the list of EnterpriseCustomerUsers we want to render.
Arguments:
request (HttpRequest): HTTP Request instance.
search_keyword (str): The keyword to search for in users' email addresses and usernames.
customer_uuid (str): A unique identifier to filter down to only users linked to a
particular EnterpriseCustomer.
page_size (int): Number of learners displayed in each paginated set.
|
def get_enterprise_customer_user_queryset(self, request, search_keyword, customer_uuid, page_size=PAGE_SIZE):
page = request.GET.get('page', 1)
learners = EnterpriseCustomerUser.objects.filter(enterprise_customer__uuid=customer_uuid)
user_ids = learners.values_list('user_id', flat=True)
matching_users = User.objects.filter(pk__in=user_ids)
if search_keyword is not None:
matching_users = matching_users.filter(
Q(email__icontains=search_keyword) | Q(username__icontains=search_keyword)
)
matching_user_ids = matching_users.values_list('pk', flat=True)
learners = learners.filter(user_id__in=matching_user_ids)
return paginated_list(learners, page, page_size)
| 434,770
|
Get the list of PendingEnterpriseCustomerUsers we want to render.
Args:
search_keyword (str): The keyword to search for in pending users' email addresses.
customer_uuid (str): A unique identifier to filter down to only pending users
linked to a particular EnterpriseCustomer.
|
def get_pending_users_queryset(self, search_keyword, customer_uuid):
queryset = PendingEnterpriseCustomerUser.objects.filter(
enterprise_customer__uuid=customer_uuid
)
if search_keyword is not None:
queryset = queryset.filter(user_email__icontains=search_keyword)
return queryset
| 434,771
|
Link single user by email or username.
Arguments:
enterprise_customer (EnterpriseCustomer): learners will be linked to this Enterprise Customer instance
manage_learners_form (ManageLearnersForm): bound ManageLearners form instance
|
def _handle_singular(cls, enterprise_customer, manage_learners_form):
form_field_value = manage_learners_form.cleaned_data[ManageLearnersForm.Fields.EMAIL_OR_USERNAME]
email = email_or_username__to__email(form_field_value)
try:
validate_email_to_link(email, form_field_value, ValidationMessages.INVALID_EMAIL_OR_USERNAME, True)
except ValidationError as exc:
manage_learners_form.add_error(ManageLearnersForm.Fields.EMAIL_OR_USERNAME, exc)
else:
EnterpriseCustomerUser.objects.link_user(enterprise_customer, email)
return [email]
| 434,772
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.