Search is not available for this dataset
text
stringlengths
75
104k
def update_throttle_scope(self): """ Update throttle scope so that service user throttle rates are applied. """ self.scope = SERVICE_USER_SCOPE self.rate = self.get_rate() self.num_requests, self.duration = self.parse_rate(self.rate)
def get_course_final_price(self, mode, currency='$', enterprise_catalog_uuid=None): """ Get course mode's SKU discounted price after applying any entitlement available for this user. Returns: str: Discounted price of the course mode. """ try: price_detai...
def update_enterprise_courses(self, enterprise_customer, course_container_key='results', **kwargs): """ This method adds enterprise-specific metadata for each course. We are adding following field in all the courses. tpa_hint: a string for identifying Identity Provider. ...
def update_course(self, course, enterprise_customer, enterprise_context): """ Update course metadata of the given course and return updated course. Arguments: course (dict): Course Metadata returned by course catalog API enterprise_customer (EnterpriseCustomer): enterpri...
def update_course_runs(self, course_runs, enterprise_customer, enterprise_context): """ Update Marketing urls in course metadata and return updated course. Arguments: course_runs (list): List of course runs. enterprise_customer (EnterpriseCustomer): enterprise customer i...
def export(self): """ Collect learner data for the ``EnterpriseCustomer`` where data sharing consent is granted. Yields a learner data object for each enrollment, containing: * ``enterprise_enrollment``: ``EnterpriseCourseEnrollment`` object. * ``completed_date``: datetime inst...
def get_learner_data_records(self, enterprise_enrollment, completed_date=None, grade=None, is_passing=False): """ Generate a learner data transmission audit with fields properly filled in. """ # pylint: disable=invalid-name LearnerDataTransmissionAudit = apps.get_model('integrate...
def _collect_certificate_data(self, enterprise_enrollment): """ Collect the learner completion data from the course certificate. Used for Instructor-paced courses. If no certificate is found, then returns the completed_date = None, grade = In Progress, on the idea that a certif...
def _collect_grades_data(self, enterprise_enrollment, course_details): """ Collect the learner completion data from the Grades API. Used for self-paced courses. Args: enterprise_enrollment (EnterpriseCourseEnrollment): the enterprise enrollment record for which we need to ...
def get_enterprise_user_id(self, obj): """ Get enterprise user id from user object. Arguments: obj (User): Django User object Returns: (int): Primary Key identifier for enterprise user object. """ # An enterprise learner can not belong to multipl...
def get_enterprise_sso_uid(self, obj): """ Get enterprise SSO UID. Arguments: obj (User): Django User object Returns: (str): string containing UUID for enterprise customer's Identity Provider. """ # An enterprise learner can not belong to multipl...
def get_course_duration(self, obj): """ Get course's duration as a timedelta. Arguments: obj (CourseOverview): CourseOverview object Returns: (timedelta): Duration of a course. """ duration = obj.end - obj.start if obj.start and obj.end else None...
def transmit(self, payload, **kwargs): """ Transmit content metadata items to the integrated channel. """ items_to_create, items_to_update, items_to_delete, transmission_map = self._partition_items(payload) self._prepare_items_for_delete(items_to_delete) prepared_items = ...
def _remove_failed_items(self, failed_items, items_to_create, items_to_update, items_to_delete): """ 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...
def parse_arguments(*args, **options): # pylint: disable=unused-argument """ Parse and validate arguments for send_course_enrollments command. Arguments: *args: Positional arguments passed to the command **options: optional arguments passed to the command Retur...
def handle(self, *args, **options): """ Send xAPI statements. """ if not CourseEnrollment: raise NotConnectedToOpenEdX("This package must be installed in an OpenEdX environment.") days, enterprise_customer = self.parse_arguments(*args, **options) if enterpri...
def send_xapi_statements(self, lrs_configuration, days): """ 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 l...
def get_course_enrollments(self, enterprise_customer, days): """ Get course enrollments for all the learners of given enterprise customer. Arguments: enterprise_customer (EnterpriseCustomer): Include Course enrollments for learners of this enterprise customer. ...
def course_modal(context, course=None): """ Django template tag that returns course information to display in a modal. You may pass in a particular course if you like. Otherwise, the modal will look for course context within the parent context. Usage: {% course_modal %} {% course_m...
def link_to_modal(link_text, index, autoescape=True): # pylint: disable=unused-argument """ Django template filter that returns an anchor with attributes useful for course modal selection. General Usage: {{ link_text|link_to_modal:index }} Examples: {{ course_title|link_to_modal:forlo...
def handle(self, *args, **options): """ Unlink inactive EnterpriseCustomer(s) SAP learners. """ channels = self.get_integrated_channels(options) for channel in channels: channel_code = channel.channel_code() channel_pk = channel.pk if channel_...
def populate_data_sharing_consent(apps, schema_editor): """ Populates the ``DataSharingConsent`` model with the ``enterprise`` application's consent data. Consent data from the ``enterprise`` application come from the ``EnterpriseCourseEnrollment`` model. """ DataSharingConsent = apps.get_model('co...
def create_course_completion(self, user_id, payload): # pylint: disable=unused-argument """ Send a completion status payload to the Degreed Completion Status endpoint Args: user_id: Unused. payload: JSON encoded object (serialized from DegreedLearnerDataTransmissionAudi...
def delete_course_completion(self, user_id, payload): # pylint: disable=unused-argument """ Delete a completion status previously sent to the Degreed Completion Status endpoint Args: user_id: Unused. payload: JSON encoded object (serialized from DegreedLearnerDataTransm...
def _sync_content_metadata(self, serialized_data, http_method): """ 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. ...
def _post(self, url, data, scope): """ 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...
def _delete(self, url, data, scope): """ 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...
def _create_session(self, scope): """ Instantiate a new session object for use in connecting with Degreed """ now = datetime.datetime.utcnow() if self.session is None or self.expires_at is None or now >= self.expires_at: # Create a new session with a valid token ...
def _get_oauth_access_token(self, client_id, client_secret, user_id, user_password, scope): """ Retrieves OAuth 2.0 access token using the client credentials grant. Args: client_id (str): API client ID client_secret (str): API client secret user_id (str): Degreed com...
def ensure_data_exists(self, request, data, error_message=None): """ Ensure that the wrapped API client's response brings us valid data. If not, raise an error and log it. """ if not data: error_message = ( error_message or "Unable to fetch API response from e...
def contains_content_items(self, request, pk, course_run_ids, program_uuids): """ Return whether or not the specified content is available to the EnterpriseCustomer. Multiple course_run_ids and/or program_uuids query parameters can be sent to this view to check for their existence in th...
def courses(self, request, pk=None): # pylint: disable=invalid-name,unused-argument """ Retrieve the list of courses contained within the catalog linked to this enterprise. Only courses with active course runs are returned. A course run is considered active if it is currently open for ...
def course_enrollments(self, request, pk): """ Creates a course enrollment for an EnterpriseCustomerUser. """ enterprise_customer = self.get_object() serializer = serializers.EnterpriseCustomerCourseEnrollmentsSerializer( data=request.data, many=True, ...
def with_access_to(self, request, *args, **kwargs): # pylint: disable=invalid-name,unused-argument """ Returns the list of enterprise customers the user has a specified group permission access to. """ self.queryset = self.queryset.order_by('name') enterprise_id = self.request.qu...
def entitlements(self, request, pk=None): # pylint: disable=invalid-name,unused-argument """ Retrieve the list of entitlements available to this learner. Only those entitlements are returned that satisfy enterprise customer's data sharing setting. Arguments: request (HttpR...
def contains_content_items(self, request, pk, course_run_ids, program_uuids): """ Return whether or not the EnterpriseCustomerCatalog contains the specified content. Multiple course_run_ids and/or program_uuids query parameters can be sent to this view to check for their existence in th...
def course_detail(self, request, pk, course_key): # pylint: disable=invalid-name,unused-argument """ Return the metadata for the specified course. The course needs to be included in the specified EnterpriseCustomerCatalog in order for metadata to be returned from this endpoint. ...
def course_run_detail(self, request, pk, course_id): # pylint: disable=invalid-name,unused-argument """ Return the metadata for the specified course run. The course run needs to be included in the specified EnterpriseCustomerCatalog in order for metadata to be returned from this endpoi...
def program_detail(self, request, pk, program_uuid): # pylint: disable=invalid-name,unused-argument """ Return the metadata for the specified program. The program needs to be included in the specified EnterpriseCustomerCatalog in order for metadata to be returned from this endpoint. ...
def list(self, request): """ DRF view to list all catalogs. Arguments: request (HttpRequest): Current request Returns: (Response): DRF response object containing course catalogs. """ catalog_api = CourseCatalogApiClient(request.user) cata...
def retrieve(self, request, pk=None): # pylint: disable=invalid-name """ DRF view to get catalog details. Arguments: request (HttpRequest): Current request pk (int): Course catalog identifier Returns: (Response): DRF response object containing cours...
def courses(self, request, enterprise_customer, pk=None): # pylint: disable=invalid-name """ Retrieve the list of courses contained within this catalog. Only courses with active course runs are returned. A course run is considered active if it is currently open for enrollment, or will ...
def get_required_query_params(self, request): """ Gets ``email``, ``enterprise_name``, and ``number_of_codes``, which are the relevant parameters for this API endpoint. :param request: The request to this endpoint. :return: The ``email``, ``enterprise_name``, and ``number_of_cod...
def get_missing_params_message(self, parameter_state): """ Get a user-friendly message indicating a missing parameter for the API endpoint. """ params = ', '.join(name for name, present in parameter_state if not present) return self.MISSING_REQUIRED_PARAMS_MSG.format(params)
def post(self, request): """ POST /enterprise/api/v1/request_codes Requires a JSON object of the following format: >>> { >>> "email": "[email protected]", >>> "enterprise_name": "IBM", >>> "number_of_codes": "50" >>> } Keys: *emai...
def transform_title(self, content_metadata_item): """ Return the title of the content item. """ title_with_locales = [] for locale in self.enterprise_configuration.get_locales(): title_with_locales.append({ 'locale': locale, 'value': c...
def transform_description(self, content_metadata_item): """ Return the description of the content item. """ description_with_locales = [] for locale in self.enterprise_configuration.get_locales(): description_with_locales.append({ 'locale': locale, ...
def transform_image(self, content_metadata_item): """ Return the image URI of the content item. """ image_url = '' if content_metadata_item['content_type'] in ['course', 'program']: image_url = content_metadata_item.get('card_image_url') elif content_metadata_...
def transform_launch_points(self, content_metadata_item): """ Return the content metadata item launch points. SAPSF allows you to transmit an arry of content launch points which are meant to represent sections of a content item which a learner can launch into from SAPSF. Current...
def transform_courserun_title(self, content_metadata_item): """ Return the title of the courserun content item. """ title = content_metadata_item.get('title') or '' course_run_start = content_metadata_item.get('start') if course_run_start: if course_available...
def transform_courserun_description(self, content_metadata_item): """ Return the description of the courserun content item. """ description_with_locales = [] content_metadata_language_code = transform_language_code(content_metadata_item.get('content_language', '')) for lo...
def transform_courserun_schedule(self, content_metadata_item): """ Return the schedule of the courseun content item. """ start = content_metadata_item.get('start') or UNIX_MIN_DATE_STRING end = content_metadata_item.get('end') or UNIX_MAX_DATE_STRING return [{ ...
def get_content_id(self, content_metadata_item): """ Return the id for the given content_metadata_item, `uuid` for programs or `key` for other content """ content_id = content_metadata_item.get('key', '') if content_metadata_item['content_type'] == 'program': content_...
def parse_datetime_to_epoch(datestamp, magnitude=1.0): """ Convert an ISO-8601 datetime string to a Unix epoch timestamp in some magnitude. By default, returns seconds. """ parsed_datetime = parse_lms_api_datetime(datestamp) time_since_epoch = parsed_datetime - UNIX_EPOCH return int(time_si...
def current_time_is_in_interval(start, end): """ Determine whether the current time is on the interval [start, end]. """ interval_start = parse_lms_api_datetime(start or UNIX_MIN_DATE_STRING) interval_end = parse_lms_api_datetime(end or UNIX_MAX_DATE_STRING) return interval_start <= timezone.now...
def chunks(dictionary, chunk_size): """ Yield successive n-sized chunks from dictionary. """ iterable = iter(dictionary) for __ in range(0, len(dictionary), chunk_size): yield {key: dictionary[key] for key in islice(iterable, chunk_size)}
def strfdelta(tdelta, fmt='{D:02}d {H:02}h {M:02}m {S:02}s', input_type='timedelta'): """ Convert a datetime.timedelta object or a regular number to a custom-formatted string. This function works like the strftime() method works for datetime.datetime objects. The fmt argument allows custom formatt...
def transform_description(self, content_metadata_item): """ Return the transformed version of the course description. We choose one value out of the course's full description, short description, and title depending on availability and length limits. """ full_description ...
def logo_path(instance, filename): """ 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...
def get_link_by_email(self, user_email): """ Return link by email. """ try: user = User.objects.get(email=user_email) try: return self.get(user_id=user.id) except EnterpriseCustomerUser.DoesNotExist: pass except ...
def link_user(self, enterprise_customer, user_email): """ Link user email to Enterprise Customer. If :class:`django.contrib.auth.models.User` instance with specified email does not exist, :class:`.PendingEnterpriseCustomerUser` instance is created instead. """ try: ...
def unlink_user(self, enterprise_customer, user_email): """ Unlink user email from Enterprise Customer. If :class:`django.contrib.auth.models.User` instance with specified email does not exist, :class:`.PendingEnterpriseCustomerUser` instance is deleted instead. Raises Enterpri...
def enterprise_customer_uuid(self): """Get the enterprise customer uuid linked to the user.""" try: enterprise_user = EnterpriseCustomerUser.objects.get(user_id=self.user.id) except ObjectDoesNotExist: LOGGER.warning( 'User {} has a {} assignment but is no...
def get_data_sharing_consent(username, enterprise_customer_uuid, course_id=None, program_uuid=None): """ Get the data sharing consent object associated with a certain user, enterprise customer, and other scope. :param username: The user that grants consent :param enterprise_customer_uuid: The consent r...
def get_course_data_sharing_consent(username, course_id, enterprise_customer_uuid): """ Get the data sharing consent object associated with a certain user of a customer for a course. :param username: The user that grants consent. :param course_id: The course for which consent is granted. :param ent...
def get_program_data_sharing_consent(username, program_uuid, enterprise_customer_uuid): """ Get the data sharing consent object associated with a certain user of a customer for a program. :param username: The user that grants consent. :param program_uuid: The program for which consent is granted. :...
def send_course_enrollment_statement(lrs_configuration, course_enrollment): """ Send xAPI statement for course enrollment. Arguments: lrs_configuration (XAPILRSConfiguration): XAPILRSConfiguration instance where to send statements. course_enrollment (CourseEnrollment): Course enrollment o...
def send_course_completion_statement(lrs_configuration, user, course_overview, course_grade): """ Send xAPI statement for course completion. Arguments: lrs_configuration (XAPILRSConfiguration): XAPILRSConfiguration instance where to send statements. user (User): Django User object. ...
def export(self): """ Return the exported and transformed content metadata as a dictionary. """ content_metadata_export = {} content_metadata_items = self.enterprise_api.get_content_metadata(self.enterprise_customer) LOGGER.info('Retrieved content metadata for enterprise ...
def _transform_item(self, content_metadata_item): """ Transform the provided content metadata item to the schema expected by the integrated channel. """ content_metadata_type = content_metadata_item['content_type'] transformed_item = {} for integrated_channel_schema_key, ...
def get_consent_record(self, request): """ Get the consent record relevant to the request at hand. """ username, course_id, program_uuid, enterprise_customer_uuid = self.get_required_query_params(request) return get_data_sharing_consent( username, enterpri...
def get_required_query_params(self, request): """ Gets ``username``, ``course_id``, and ``enterprise_customer_uuid``, which are the relevant query parameters for this API endpoint. :param request: The request to this endpoint. :return: The ``username``, ``course_id``, and ``ente...
def get_no_record_response(self, request): """ Get an HTTPResponse that can be used when there's no related EnterpriseCustomer. """ username, course_id, program_uuid, enterprise_customer_uuid = self.get_required_query_params(request) data = { self.REQUIRED_PARAM_USERN...
def get(self, request): """ GET /consent/api/v1/data_sharing_consent?username=bob&course_id=id&enterprise_customer_uuid=uuid *username* The edX username from whom to get consent. *course_id* The course for which consent is granted. *enterprise_customer_uui...
def post(self, request): """ POST /consent/api/v1/data_sharing_consent Requires a JSON object of the following format: >>> { >>> "username": "bob", >>> "course_id": "course-v1:edX+DemoX+Demo_Course", >>> "enterprise_customer_uuid": "enterprise-uuid-go...
def delete(self, request): """ DELETE /consent/api/v1/data_sharing_consent Requires a JSON object of the following format: >>> { >>> "username": "bob", >>> "course_id": "course-v1:edX+DemoX+Demo_Course", >>> "enterprise_customer_uuid": "enterprise-uui...
def ready(self): """ Perform other one-time initialization steps. """ from enterprise.signals import handle_user_post_save from django.db.models.signals import pre_migrate, post_save post_save.connect(handle_user_post_save, sender=self.auth_user_model, dispatch_uid=USER_...
def _disconnect_user_post_save_for_migrations(self, sender, **kwargs): # pylint: disable=unused-argument """ Handle pre_migrate signal - disconnect User post_save handler. """ from django.db.models.signals import post_save post_save.disconnect(sender=self.auth_user_model, dispat...
def get_actor(self, username, email): """ Get actor for the statement. """ return Agent( name=username, mbox='mailto:{email}'.format(email=email), )
def get_object(self, name, description): """ Get object for the statement. """ return Activity( id=X_API_ACTIVITY_COURSE, definition=ActivityDefinition( name=LanguageMap({'en-US': (name or '').encode("ascii", "ignore").decode('ascii')}), ...
def parse_csv(file_stream, expected_columns=None): """ 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 pre...
def validate_email_to_link(email, raw_email=None, message_template=None, ignore_existing=False): """ Validate email to be linked to Enterprise Customer. Performs two checks: * Checks that email is valid * Checks that it is not already linked to any Enterprise Customer Arguments: ...
def get_course_runs_from_program(program): """ Return course runs from program data. Arguments: program(dict): Program data from Course Catalog API Returns: set: course runs in given program """ course_runs = set() for course in program.get("courses", []): for run i...
def get_earliest_start_date_from_program(program): """ Get the earliest date that one of the courses in the program was available. For the sake of emails to new learners, we treat this as the program start date. Arguemnts: program (dict): Program data from Course Catalog API returns: ...
def paginated_list(object_list, page, page_size=25): """ 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): Whethe...
def clean_email_or_username(self): """ Clean email form field Returns: str: the cleaned value, converted to an email address (or an empty string) """ email_or_username = self.cleaned_data[self.Fields.EMAIL_OR_USERNAME].strip() if not email_or_username: ...
def clean_course(self): """ Verify course ID and retrieve course details. """ course_id = self.cleaned_data[self.Fields.COURSE].strip() if not course_id: return None try: client = EnrollmentApiClient() return client.get_course_details(c...
def clean_program(self): """ Clean program. Try obtaining program treating form value as program UUID or title. Returns: dict: Program information if program found """ program_id = self.cleaned_data[self.Fields.PROGRAM].strip() if not program_id: ...
def clean_notify(self): """ Clean the notify_on_enrollment field. """ return self.cleaned_data.get(self.Fields.NOTIFY, self.NotificationTypes.DEFAULT)
def clean(self): """ Clean fields that depend on each other. In this case, the form can be used to link single user or bulk link multiple users. These are mutually exclusive modes, so this method checks that only one field is passed. """ cleaned_data = super(ManageLearne...
def _validate_course(self): """ Verify that the selected mode is valid for the given course . """ # Verify that the selected mode is valid for the given course . course_details = self.cleaned_data.get(self.Fields.COURSE) if course_details: course_mode = self.c...
def _validate_program(self): """ Verify that selected mode is available for program and all courses in the program """ program = self.cleaned_data.get(self.Fields.PROGRAM) if not program: return course_runs = get_course_runs_from_program(program) try:...
def get_catalog_options(self): """ Retrieve a list of catalog ID and name pairs. Once retrieved, these name pairs can be used directly as a value for the `choices` argument to a ChoiceField. """ # TODO: We will remove the discovery service catalog implementation ...
def clean(self): """ Clean form fields prior to database entry. In this case, the major cleaning operation is substituting a None value for a blank value in the Catalog field. """ cleaned_data = super(EnterpriseCustomerAdminForm, self).clean() if 'catalog' in cle...
def clean(self): """ Final validations of model fields. 1. Validate that selected site for enterprise customer matches with the selected identity provider's site. """ super(EnterpriseCustomerIdentityProviderAdminForm, self).clean() provider_id = self.cleaned_data.get('p...
def clean(self): """ Override of clean method to perform additional validation """ cleaned_data = super(EnterpriseCustomerReportingConfigAdminForm, self).clean() report_customer = cleaned_data.get('enterprise_customer') # Check that any selected catalogs are tied to the ...
def clean_channel_worker_username(self): """ Clean enterprise channel worker user form field Returns: str: the cleaned value of channel user username for transmitting courses metadata. """ channel_worker_username = self.cleaned_data['channel_worker_username'].strip()...
def verify_edx_resources(): """ Ensure that all necessary resources to render the view are present. """ required_methods = { 'ProgramDataExtender': ProgramDataExtender, } for method in required_methods: if required_methods[method] is None: raise NotConnectedToOpenEdX...
def get_global_context(request, enterprise_customer): """ Get the set of variables that are needed by default across views. """ platform_name = get_configuration_value("PLATFORM_NAME", settings.PLATFORM_NAME) # pylint: disable=no-member return { 'enterprise_customer': enterprise_customer...
def get_price_text(price, request): """ Return the localized converted price as string (ex. '$150 USD'). If the local_currency switch is enabled and the users location has been determined this will convert the given price based on conversion rate from the Catalog service and return a localized string ...