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 = se...
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....
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...
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 o...
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; " "rece...
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.ar...
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...
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 abso...
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...
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) ...
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 ...
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...
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 Webe...
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._obje...
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 incorr...
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...
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() ...
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" ...
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 i...
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: ...
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]', ...
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']) ...
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 unenroll...
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'...
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...
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: # Th...
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 wheth...
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. ...
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)) re...
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, F...
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) ...
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 i...
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...
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 ...
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.clien...
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, ...
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_CUSTOM...
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 resul...
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'] )...
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[...
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'] ...
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(...
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...
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, ) ...
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: ...
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(enterp...
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 ...
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 enterpr...
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 enterpr...
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 t...
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) ...
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 n...
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: ...
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. Retu...
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: ...
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, ...
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, ...
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` ...
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_SCO...
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 en...
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, contex...
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...
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 ...
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. enterpr...
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) retur...
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_enrollme...
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_gr...
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...
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 dictiona...
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(...
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/tem...
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) ...
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 iden...
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 confi...
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 integrate...
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...
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 transm...
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...
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 ...
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, ...
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) ...
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}...
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 h...
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, comp...
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}) ...
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.clean...
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 ...
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)...
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...
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,...
434,772