_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q256700
create_switch
validation
def create_switch(apps, schema_editor): """Create the `role_based_access_control` switch if it does not already exist.""" Switch = apps.get_model('waffle', 'Switch')
python
{ "resource": "" }
q256701
delete_switch
validation
def delete_switch(apps, schema_editor): """Delete the `role_based_access_control` switch.""" Switch = apps.get_model('waffle', 'Switch')
python
{ "resource": "" }
q256702
create_switch
validation
def create_switch(apps, schema_editor): """Create and activate the SAP_USE_ENTERPRISE_ENROLLMENT_PAGE switch if it does
python
{ "resource": "" }
q256703
SapSuccessFactorsLearnerTransmitter.transmit
validation
def transmit(self, payload, **kwargs): """ Send a completion status call to SAP SuccessFactors using the client. Args: payload: The learner completion data payload to send to
python
{ "resource": "" }
q256704
SapSuccessFactorsLearnerTransmitter.handle_transmission_error
validation
def handle_transmission_error(self, learner_data, request_exception): """Handle the case where the employee on SAPSF's side is marked as inactive.""" try: sys_msg = request_exception.response.content except AttributeError: pass else: if 'user account is inactive' in sys_msg: ecu = EnterpriseCustomerUser.objects.get(
python
{ "resource": "" }
q256705
ServiceUserThrottle.allow_request
validation
def allow_request(self, request, view): """ Modify throttling for service users. Updates throttling rate if the request is coming from the service user, and defaults to UserRateThrottle's configured setting otherwise. Updated throttling rate comes from `DEFAULT_THROTTLE_RATES` key in `REST_FRAMEWORK` setting. service user throttling is specified in `DEFAULT_THROTTLE_RATES` by `service_user` key Example Setting: ``` REST_FRAMEWORK = { ... 'DEFAULT_THROTTLE_RATES': { ... 'service_user': '50/day' }
python
{ "resource": "" }
q256706
ServiceUserThrottle.update_throttle_scope
validation
def update_throttle_scope(self): """ Update throttle scope so that service user throttle rates are applied.
python
{ "resource": "" }
q256707
EcommerceApiClient.get_course_final_price
validation
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_details = self.client.baskets.calculate.get( sku=[mode['sku']], username=self.user.username, catalog=enterprise_catalog_uuid, ) except (SlumberBaseException, ConnectionError, Timeout)
python
{ "resource": "" }
q256708
EnterpriseCourseContextSerializerMixin.update_enterprise_courses
validation
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. enterprise_id: the UUID of the enterprise **kwargs: any additional data one would like to add on a per-use basis. Arguments: enterprise_customer: The customer whose data will be used to fill the enterprise context. course_container_key: The key used to find the container for courses in the serializer's data dictionary. """ enterprise_context = { 'tpa_hint': enterprise_customer
python
{ "resource": "" }
q256709
EnterpriseCourseContextSerializerMixin.update_course
validation
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): enterprise customer instance. enterprise_context (dict): Enterprise context to be added to course runs and URLs.. Returns: (dict): Updated course metadata """ course['course_runs'] = self.update_course_runs( course_runs=course.get('course_runs') or [], enterprise_customer=enterprise_customer, enterprise_context=enterprise_context, ) # Update marketing
python
{ "resource": "" }
q256710
EnterpriseCourseContextSerializerMixin.update_course_runs
validation
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 instance. enterprise_context (dict): The context to inject into URLs. Returns: (dict): Dictionary containing updated course metadata. """ updated_course_runs = [] for course_run in course_runs: track_selection_url = utils.get_course_track_selection_url(
python
{ "resource": "" }
q256711
LearnerExporter.export
validation
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 instance containing the course/enrollment completion date; None if not complete. "Course completion" occurs for instructor-paced courses when course certificates are issued, and for self-paced courses, when the course end date is passed, or when the learner achieves a passing grade. * ``grade``: string grade recorded for the learner in the course. """ # Fetch the consenting enrollment data, including the enterprise_customer_user. # Order by the course_id, to avoid fetching course API data more than we have to. enrollment_queryset = EnterpriseCourseEnrollment.objects.select_related( 'enterprise_customer_user' ).filter( enterprise_customer_user__enterprise_customer=self.enterprise_customer, enterprise_customer_user__active=True, ).order_by('course_id') # Fetch course details from the Course API, and cache between calls. course_details = None for enterprise_enrollment in enrollment_queryset: course_id = enterprise_enrollment.course_id # Fetch course details from Courses API # pylint: disable=unsubscriptable-object if course_details is None or course_details['course_id'] != course_id: if self.course_api is None: self.course_api = CourseApiClient() course_details = self.course_api.get_course_details(course_id) if course_details is None: # Course not found, so we have nothing to report. LOGGER.error("No course run details found for enrollment [%d]: [%s]", enterprise_enrollment.pk, course_id) continue consent = DataSharingConsent.objects.proxied_get( username=enterprise_enrollment.enterprise_customer_user.username, course_id=enterprise_enrollment.course_id, enterprise_customer=enterprise_enrollment.enterprise_customer_user.enterprise_customer ) if not consent.granted or enterprise_enrollment.audit_reporting_disabled:
python
{ "resource": "" }
q256712
LearnerExporter.get_learner_data_records
validation
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('integrated_channel', 'LearnerDataTransmissionAudit') completed_timestamp = None course_completed = False if completed_date is not None: completed_timestamp = parse_datetime_to_epoch_millis(completed_date) course_completed = is_passing return [
python
{ "resource": "" }
q256713
LearnerExporter._collect_certificate_data
validation
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 certificate will eventually be generated. Args: enterprise_enrollment (EnterpriseCourseEnrollment): the enterprise enrollment record for which we need to collect completion/grade data Returns: completed_date: Date the course was completed, this is None if course has not been completed. grade: Current grade in the course. is_passing: Boolean indicating if the grade is a passing
python
{ "resource": "" }
q256714
LearnerExporter._collect_grades_data
validation
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 collect completion/grade data course_details (dict): the course details for the course in the enterprise enrollment record. Returns: completed_date: Date the course was completed, this is None if course has not been completed. grade: Current grade in the course. is_passing: Boolean indicating if the grade is a passing grade or not. """ if self.grades_api is None: self.grades_api = GradesApiClient(self.user) course_id = enterprise_enrollment.course_id username = enterprise_enrollment.enterprise_customer_user.user.username try: grades_data = self.grades_api.get_course_grade(course_id, username) except HttpNotFoundError as error: # Grade not found, so we have nothing to report. if hasattr(error, 'content'): response_content = json.loads(error.content) if response_content.get('error_code', '') == 'user_not_enrolled': # This means the user has an enterprise enrollment record but is not enrolled in the course yet LOGGER.info( "User [%s] not enrolled in course [%s], enterprise enrollment [%d]", username, course_id, enterprise_enrollment.pk ) return None, None, None LOGGER.error("No grades data found for [%d]: [%s], [%s]", enterprise_enrollment.pk,
python
{ "resource": "" }
q256715
LearnerInfoSerializer.get_enterprise_user_id
validation
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 multiple enterprise customer at the same time
python
{ "resource": "" }
q256716
LearnerInfoSerializer.get_enterprise_sso_uid
validation
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 multiple enterprise customer at the same time
python
{ "resource": "" }
q256717
CourseInfoSerializer.get_course_duration
validation
def get_course_duration(self, obj): """ Get course's duration as a timedelta. Arguments: obj (CourseOverview): CourseOverview object Returns: (timedelta): Duration of a course. """
python
{ "resource": "" }
q256718
SapSuccessFactorsContentMetadataTransmitter._remove_failed_items
validation
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_create (dict): dict containing the items
python
{ "resource": "" }
q256719
Command.parse_arguments
validation
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 Returns: A tuple containing parsed values for 1. days (int): Integer showing number of days to lookup enterprise enrollments, course completion etc and send to xAPI LRS 2. enterprise_customer_uuid (EnterpriseCustomer): Enterprise Customer if present then send xAPI statements just for this enterprise. """ days = options.get('days', 1) enterprise_customer_uuid = options.get('enterprise_customer_uuid') enterprise_customer = None
python
{ "resource": "" }
q256720
Command.handle
validation
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 enterprise_customer: try: lrs_configuration = XAPILRSConfiguration.objects.get( active=True, enterprise_customer=enterprise_customer ) except XAPILRSConfiguration.DoesNotExist:
python
{ "resource": "" }
q256721
Command.get_course_enrollments
validation
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.
python
{ "resource": "" }
q256722
course_modal
validation
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_modal course %} """ if course: context.update({ 'course_image_uri': course.get('course_image_uri', ''), 'course_title': course.get('course_title', ''), 'course_level_type': course.get('course_level_type', ''),
python
{ "resource": "" }
q256723
link_to_modal
validation
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:forloop.counter0 }} {{ course_title|link_to_modal:3 }} {{ view_details_text|link_to_modal:0 }} """ link = ( '<a' ' href="#!"' ' class="text-underline view-course-details-link"'
python
{ "resource": "" }
q256724
populate_data_sharing_consent
validation
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('consent', 'DataSharingConsent') EnterpriseCourseEnrollment = apps.get_model('enterprise', 'EnterpriseCourseEnrollment') User = apps.get_model('auth', 'User') for enrollment in EnterpriseCourseEnrollment.objects.all(): user = User.objects.get(pk=enrollment.enterprise_customer_user.user_id) data_sharing_consent, __ = DataSharingConsent.objects.get_or_create( username=user.username, enterprise_customer=enrollment.enterprise_customer_user.enterprise_customer, course_id=enrollment.course_id, ) if enrollment.consent_granted
python
{ "resource": "" }
q256725
DegreedAPIClient.create_course_completion
validation
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 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
python
{ "resource": "" }
q256726
DegreedAPIClient.delete_course_completion
validation
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 DegreedLearnerDataTransmissionAudit) containing the required completion status fields for deletion 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
python
{ "resource": "" }
q256727
DegreedAPIClient._sync_content_metadata
validation
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. Raises: ClientError: If Degreed API request fails. """ 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
python
{ "resource": "" }
q256728
DegreedAPIClient._post
validation
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: - `CONTENT_PROVIDER_SCOPE`
python
{ "resource": "" }
q256729
DegreedAPIClient._delete
validation
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 expects: - `CONTENT_PROVIDER_SCOPE`
python
{ "resource": "" }
q256730
DegreedAPIClient._create_session
validation
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 if self.session: self.session.close() oauth_access_token, expires_at = self._get_oauth_access_token( self.enterprise_configuration.key, self.enterprise_configuration.secret, self.enterprise_configuration.degreed_user_id, self.enterprise_configuration.degreed_user_password,
python
{ "resource": "" }
q256731
EnterpriseViewSet.ensure_data_exists
validation
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 = (
python
{ "resource": "" }
q256732
EnterpriseCustomerViewSet.contains_content_items
validation
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 the EnterpriseCustomerCatalogs associated with this EnterpriseCustomer. At least one course run key or program UUID value must be included in the request. """ enterprise_customer = self.get_object() # Maintain plus characters in course key. course_run_ids = [unquote(quote_plus(course_run_id)) for course_run_id in course_run_ids] contains_content_items = False for catalog in enterprise_customer.enterprise_customer_catalogs.all():
python
{ "resource": "" }
q256733
EnterpriseCustomerViewSet.courses
validation
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 enrollment, or will open in the future. """ enterprise_customer = self.get_object() self.check_object_permissions(request, enterprise_customer) self.ensure_data_exists( request, enterprise_customer.catalog, error_message="No catalog is associated with Enterprise {enterprise_name} from endpoint '{path}'.".format( enterprise_name=enterprise_customer.name, path=request.get_full_path() ) ) # We have handled potential error cases and are now ready to call out to the Catalog API. catalog_api = CourseCatalogApiClient(request.user, enterprise_customer.site) courses = catalog_api.get_paginated_catalog_courses(enterprise_customer.catalog, request.GET) # An empty response means that there was a problem fetching data from Catalog API, since # a Catalog with no courses has a non empty response indicating that there are no courses. self.ensure_data_exists( request,
python
{ "resource": "" }
q256734
EnterpriseCustomerViewSet.course_enrollments
validation
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, context={ 'enterprise_customer': enterprise_customer, 'request_user': request.user,
python
{ "resource": "" }
q256735
EnterpriseCustomerViewSet.with_access_to
validation
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.query_params.get('enterprise_id', None) enterprise_slug = self.request.query_params.get('enterprise_slug', None) enterprise_name = self.request.query_params.get('search', None) if enterprise_id is not None:
python
{ "resource": "" }
q256736
EnterpriseCustomerUserViewSet.entitlements
validation
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 (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. """
python
{ "resource": "" }
q256737
EnterpriseCustomerCatalogViewSet.contains_content_items
validation
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 the EnterpriseCustomerCatalog. At least one course run key or program UUID value must be included in the request. """ enterprise_customer_catalog = self.get_object() # Maintain plus characters in course key. course_run_ids = [unquote(quote_plus(course_run_id)) for course_run_id in course_run_ids] contains_content_items = True if course_run_ids:
python
{ "resource": "" }
q256738
EnterpriseCustomerCatalogViewSet.course_detail
validation
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.
python
{ "resource": "" }
q256739
EnterpriseCustomerCatalogViewSet.course_run_detail
validation
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 endpoint.
python
{ "resource": "" }
q256740
EnterpriseCustomerCatalogViewSet.program_detail
validation
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.
python
{ "resource": "" }
q256741
EnterpriseCourseCatalogViewSet.list
validation
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) catalogs = catalog_api.get_paginated_catalogs(request.GET)
python
{ "resource": "" }
q256742
EnterpriseCourseCatalogViewSet.retrieve
validation
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 course catalogs. """ catalog_api = CourseCatalogApiClient(request.user) catalog = catalog_api.get_catalog(pk) self.ensure_data_exists( request, catalog, error_message=(
python
{ "resource": "" }
q256743
EnterpriseCourseCatalogViewSet.courses
validation
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 open in the future. """ catalog_api = CourseCatalogApiClient(request.user, enterprise_customer.site) courses = catalog_api.get_paginated_catalog_courses(pk, request.GET) # If the API returned an empty response, that means
python
{ "resource": "" }
q256744
CouponCodesView.get_required_query_params
validation
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_codes`` from the request. """ email = get_request_value(request, self.REQUIRED_PARAM_EMAIL, '') enterprise_name = get_request_value(request, self.REQUIRED_PARAM_ENTERPRISE_NAME, '') number_of_codes = get_request_value(request, self.OPTIONAL_PARAM_NUMBER_OF_CODES, '')
python
{ "resource": "" }
q256745
CouponCodesView.get_missing_params_message
validation
def get_missing_params_message(self, parameter_state): """ Get a user-friendly message indicating a missing parameter for the API endpoint. """
python
{ "resource": "" }
q256746
SapSuccessFactorsContentMetadataExporter.transform_title
validation
def transform_title(self, content_metadata_item): """ Return the title of the content item. """ title_with_locales = [] for locale in
python
{ "resource": "" }
q256747
SapSuccessFactorsContentMetadataExporter.transform_description
validation
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, 'value': ( content_metadata_item.get('full_description') or
python
{ "resource": "" }
q256748
SapSuccessFactorsContentMetadataExporter.transform_image
validation
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')
python
{ "resource": "" }
q256749
SapSuccessFactorsContentMetadataExporter.transform_launch_points
validation
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. Currently, we only provide a single launch point for a content item. """ return [{ 'providerID': self.enterprise_configuration.provider_id, 'launchURL': content_metadata_item['enrollment_url'], 'contentTitle': content_metadata_item['title'],
python
{ "resource": "" }
q256750
SapSuccessFactorsContentMetadataExporter.transform_courserun_title
validation
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_for_enrollment(content_metadata_item): title += ' ({starts}: {:%B %Y})'.format( parse_lms_api_datetime(course_run_start), starts=_('Starts') ) else: title += ' ({:%B %Y} - {enrollment_closed})'.format( parse_lms_api_datetime(course_run_start), enrollment_closed=_('Enrollment Closed') ) title_with_locales = []
python
{ "resource": "" }
q256751
SapSuccessFactorsContentMetadataExporter.transform_courserun_description
validation
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 locale in self.enterprise_configuration.get_locales(default_locale=content_metadata_language_code):
python
{ "resource": "" }
q256752
SapSuccessFactorsContentMetadataExporter.transform_courserun_schedule
validation
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 [{ 'startDate':
python
{ "resource": "" }
q256753
SapSuccessFactorsContentMetadataExporter.get_content_id
validation
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
python
{ "resource": "" }
q256754
parse_datetime_to_epoch
validation
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. """
python
{ "resource": "" }
q256755
chunks
validation
def chunks(dictionary, chunk_size): """ Yield successive n-sized chunks from dictionary. """ iterable = iter(dictionary)
python
{ "resource": "" }
q256756
strfdelta
validation
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 formatting to be specified. Fields can include seconds, minutes, hours, days, and weeks. Each field is optional. Arguments: tdelta (datetime.timedelta, int): time delta object containing the duration or an integer to go with the input_type. fmt (str): Expected format of the time delta. place holders can only be one of the following. 1. D to extract days from time delta 2. H to extract hours from time delta 3. M to extract months from time delta 4. S to extract seconds from timedelta input_type (str): The input_type argument allows tdelta to be a regular number instead of the default, which is a datetime.timedelta object. Valid input_type strings: 1. 's', 'seconds', 2. 'm', 'minutes', 3. 'h', 'hours', 4. 'd', 'days', 5. 'w', 'weeks' Returns: (str): timedelta object interpolated into a string following the given format. Examples: '{D:02}d {H:02}h {M:02}m {S:02}s' --> '05d 08h 04m 02s' (default) '{W}w {D}d {H}:{M:02}:{S:02}' --> '4w 5d 8:04:02' '{D:2}d {H:2}:{M:02}:{S:02}' --> ' 5d 8:04:02' '{H}h {S}s' --> '72h 800s' """ # Convert tdelta to integer seconds. if input_type == 'timedelta': remainder = int(tdelta.total_seconds()) elif input_type in ['s', 'seconds']: remainder = int(tdelta) elif input_type in ['m', 'minutes']: remainder = int(tdelta) * 60
python
{ "resource": "" }
q256757
DegreedContentMetadataExporter.transform_description
validation
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 = content_metadata_item.get('full_description') or '' if
python
{ "resource": "" }
q256758
logo_path
validation
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: path: path of image file e.g. enterprise/branding/<model.id>/<model_id>_logo.<ext>.lower() """ extension =
python
{ "resource": "" }
q256759
EnterpriseCustomerUserManager.get_link_by_email
validation
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 User.DoesNotExist: pass try:
python
{ "resource": "" }
q256760
EnterpriseCustomerUserManager.link_user
validation
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: existing_user = User.objects.get(email=user_email)
python
{ "resource": "" }
q256761
EnterpriseCustomerUserManager.unlink_user
validation
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 EnterpriseCustomerUser.DoesNotExist if instance of :class:`django.contrib.auth.models.User` with specified email exists and corresponding :class:`.EnterpriseCustomerUser` instance does not. Raises PendingEnterpriseCustomerUser.DoesNotExist exception if instance of :class:`django.contrib.auth.models.User` with specified email exists and corresponding :class:`.PendingEnterpriseCustomerUser` instance does not. """ try: existing_user = User.objects.get(email=user_email) # not capturing DoesNotExist intentionally to signal to view that link does not exist link_record = self.get(enterprise_customer=enterprise_customer, user_id=existing_user.id) link_record.delete() if update_user: # Remove the SailThru flags for enterprise learner. update_user.delay(
python
{ "resource": "" }
q256762
EnterpriseRoleAssignmentContextMixin.enterprise_customer_uuid
validation
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 not linked to an enterprise!'.format( self.__class__, self.user.id ))
python
{ "resource": "" }
q256763
get_data_sharing_consent
validation
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 requester :param course_id (optional): A course ID to which consent may be related :param program_uuid (optional): A program to which consent may be related :return: The data sharing consent object, or None if the enterprise customer for the given UUID does
python
{ "resource": "" }
q256764
get_course_data_sharing_consent
validation
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 enterprise_customer_uuid: The consent requester. :return: The data sharing consent object """ # Prevent circular imports.
python
{ "resource": "" }
q256765
get_program_data_sharing_consent
validation
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. :param enterprise_customer_uuid: The consent requester.
python
{ "resource": "" }
q256766
send_course_enrollment_statement
validation
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 object. """ user_details = LearnerInfoSerializer(course_enrollment.user)
python
{ "resource": "" }
q256767
send_course_completion_statement
validation
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. course_overview (CourseOverview): Course over view object containing course details. course_grade (CourseGrade): course grade object. """ user_details = LearnerInfoSerializer(user)
python
{ "resource": "" }
q256768
ContentMetadataExporter.export
validation
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 [%s]', self.enterprise_customer.name) for item in content_metadata_items: transformed = self._transform_item(item) LOGGER.info( 'Exporting content metadata item with plugin configuration [%s]: [%s]', self.enterprise_configuration,
python
{ "resource": "" }
q256769
ContentMetadataExporter._transform_item
validation
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, edx_data_schema_key in self.DATA_TRANSFORM_MAPPING.items(): # Look for transformer functions defined on subclasses. # Favor content type-specific functions. transformer = ( getattr( self, 'transform_{content_type}_{edx_data_schema_key}'.format( content_type=content_metadata_type, edx_data_schema_key=edx_data_schema_key ), None ) or getattr(
python
{ "resource": "" }
q256770
DataSharingConsentView.get_consent_record
validation
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(
python
{ "resource": "" }
q256771
DataSharingConsentView.get_required_query_params
validation
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 ``enterprise_customer_uuid`` from the request. """ username = get_request_value(request, self.REQUIRED_PARAM_USERNAME, '') course_id = get_request_value(request, self.REQUIRED_PARAM_COURSE_ID, '') program_uuid = get_request_value(request, self.REQUIRED_PARAM_PROGRAM_UUID, '') enterprise_customer_uuid = get_request_value(request, self.REQUIRED_PARAM_ENTERPRISE_CUSTOMER) if not (username and (course_id or program_uuid) and enterprise_customer_uuid): raise ConsentAPIRequestError(
python
{ "resource": "" }
q256772
DataSharingConsentView.get_no_record_response
validation
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_USERNAME: username, self.REQUIRED_PARAM_ENTERPRISE_CUSTOMER: enterprise_customer_uuid, self.CONSENT_EXISTS: False,
python
{ "resource": "" }
q256773
EnterpriseConfig.ready
validation
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
python
{ "resource": "" }
q256774
EnterpriseConfig._disconnect_user_post_save_for_migrations
validation
def _disconnect_user_post_save_for_migrations(self, sender, **kwargs): # pylint: disable=unused-argument """ Handle pre_migrate signal - disconnect User post_save handler. """
python
{ "resource": "" }
q256775
EnterpriseStatement.get_actor
validation
def get_actor(self, username, email): """ Get actor for the statement.
python
{ "resource": "" }
q256776
EnterpriseStatement.get_object
validation
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
python
{ "resource": "" }
q256777
parse_csv
validation
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 present Yields: dict: CSV line parsed into a dictionary. """ reader = unicodecsv.DictReader(file_stream, encoding="utf-8") if expected_columns and
python
{ "resource": "" }
q256778
validate_email_to_link
validation
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: email (str): user email to link raw_email (str): raw value as it was passed by user - used in error message. message_template (str): Validation error template string. ignore_existing (bool): If True to skip the check for an existing Enterprise Customer Raises: ValidationError: if email is invalid or already linked to Enterprise Customer. Returns: bool: Whether or not there is an existing record with the same email address. """ raw_email = raw_email if raw_email is not None else email
python
{ "resource": "" }
q256779
get_course_runs_from_program
validation
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", []):
python
{ "resource": "" }
q256780
get_earliest_start_date_from_program
validation
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: datetime.datetime: The date and time at which the first course started """
python
{ "resource": "" }
q256781
paginated_list
validation
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): 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 """ 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))
python
{ "resource": "" }
q256782
ManageLearnersForm.clean_email_or_username
validation
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: # The field is blank; we just return the existing blank value. return email_or_username email = email_or_username__to__email(email_or_username) bulk_entry = len(split_usernames_and_emails(email)) > 1 if bulk_entry: for email in split_usernames_and_emails(email): validate_email_to_link(
python
{ "resource": "" }
q256783
ManageLearnersForm.clean_course
validation
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
python
{ "resource": "" }
q256784
ManageLearnersForm.clean_program
validation
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: return None try: client = CourseCatalogApiClient(self._user, self._enterprise_customer.site) program = client.get_program_by_uuid(program_id) or client.get_program_by_title(program_id) except MultipleProgramMatchError as exc: raise ValidationError(ValidationMessages.MULTIPLE_PROGRAM_MATCH.format(program_count=exc.programs_matched))
python
{ "resource": "" }
q256785
ManageLearnersForm.clean_notify
validation
def clean_notify(self): """ Clean the notify_on_enrollment field. """
python
{ "resource": "" }
q256786
ManageLearnersForm.clean
validation
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(ManageLearnersForm, self).clean() # Here we take values from `data` (and not `cleaned_data`) as we need raw values - field clean methods # might "invalidate" the value and set it to None, while all we care here is if it was provided at all or not email_or_username = self.data.get(self.Fields.EMAIL_OR_USERNAME, None) bulk_upload_csv = self.files.get(self.Fields.BULK_UPLOAD, None) if not email_or_username and not bulk_upload_csv: raise ValidationError(ValidationMessages.NO_FIELDS_SPECIFIED) if email_or_username and bulk_upload_csv: raise ValidationError(ValidationMessages.BOTH_FIELDS_SPECIFIED)
python
{ "resource": "" }
q256787
ManageLearnersForm._validate_course
validation
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.cleaned_data.get(self.Fields.COURSE_MODE) if not course_mode: raise ValidationError(ValidationMessages.COURSE_WITHOUT_COURSE_MODE) valid_course_modes = course_details["course_modes"] if all(course_mode != mode["slug"] for mode in valid_course_modes):
python
{ "resource": "" }
q256788
ManageLearnersForm._validate_program
validation
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: client = CourseCatalogApiClient(self._user, self._enterprise_customer.site) available_modes = client.get_common_course_modes(course_runs) course_mode = self.cleaned_data.get(self.Fields.COURSE_MODE) except (HttpClientError, HttpServerError): raise ValidationError( ValidationMessages.FAILED_TO_OBTAIN_COURSE_MODES.format(program_title=program.get("title")) )
python
{ "resource": "" }
q256789
EnterpriseCustomerAdminForm.get_catalog_options
validation
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 # once we have fully migrated customer's to EnterpriseCustomerCatalogs. # For now, this code will prevent an admin from creating a new # EnterpriseCustomer with a discovery service catalog. They will have to first # save the EnterpriseCustomer admin form and then edit the EnterpriseCustomer # to add a discovery service catalog. if hasattr(self.instance, 'site'): catalog_api = CourseCatalogApiClient(self.user, self.instance.site)
python
{ "resource": "" }
q256790
EnterpriseCustomerAdminForm.clean
validation
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()
python
{ "resource": "" }
q256791
EnterpriseCustomerIdentityProviderAdminForm.clean
validation
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('provider_id', None) enterprise_customer = self.cleaned_data.get('enterprise_customer', None) if provider_id is None or enterprise_customer is None: # field validation for either provider_id or enterprise_customer has already raised # a validation error. return identity_provider = utils.get_identity_provider(provider_id) if not identity_provider: # This should not happen, as identity providers displayed in drop down are fetched dynamically. message = _( "The specified Identity Provider does not exist. For more " "information, contact a system administrator.", ) # Log message for debugging logger.exception(message) raise ValidationError(message) if identity_provider and identity_provider.site != enterprise_customer.site:
python
{ "resource": "" }
q256792
EnterpriseCustomerReportingConfigAdminForm.clean
validation
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 selected enterprise. invalid_catalogs = [ '{} ({})'.format(catalog.title, catalog.uuid) for catalog in cleaned_data.get('enterprise_customer_catalogs') if catalog.enterprise_customer != report_customer ] if invalid_catalogs: message = _(
python
{ "resource": "" }
q256793
TransmitEnterpriseCoursesForm.clean_channel_worker_username
validation
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() try: User.objects.get(username=channel_worker_username) except User.DoesNotExist:
python
{ "resource": "" }
q256794
verify_edx_resources
validation
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(
python
{ "resource": "" }
q256795
get_global_context
validation
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, 'LMS_SEGMENT_KEY': settings.LMS_SEGMENT_KEY, 'LANGUAGE_CODE': get_language_from_request(request), 'tagline': get_configuration_value("ENTERPRISE_TAGLINE", settings.ENTERPRISE_TAGLINE), 'platform_description': get_configuration_value( "PLATFORM_DESCRIPTION", settings.PLATFORM_DESCRIPTION, ), 'LMS_ROOT_URL': settings.LMS_ROOT_URL, 'platform_name': platform_name, 'header_logo_alt_text': _('{platform_name} home page').format(platform_name=platform_name), 'welcome_text': constants.WELCOME_TEXT.format(platform_name=platform_name), 'enterprise_welcome_text':
python
{ "resource": "" }
q256796
render_page_with_error_code_message
validation
def render_page_with_error_code_message(request, context_data, error_code, log_message): """ Return a 404 page with specified error_code after logging error and adding message to django messages. """ LOGGER.error(log_message) messages.add_generic_error_message_with_code(request,
python
{ "resource": "" }
q256797
GrantDataSharingPermissions.course_or_program_exist
validation
def course_or_program_exist(self, course_id, program_uuid): """ Return whether the input course or program exist. """ course_exists = course_id and CourseApiClient().get_course_details(course_id)
python
{ "resource": "" }
q256798
GrantDataSharingPermissions.get_course_or_program_context
validation
def get_course_or_program_context(self, enterprise_customer, course_id=None, program_uuid=None): """ Return a dict having course or program specific keys for data sharing consent page. """ context_data = {} if course_id: context_data.update({'course_id': course_id, 'course_specific': True}) if not self.preview_mode: try: catalog_api_client = CourseCatalogApiServiceClient(enterprise_customer.site) except ImproperlyConfigured: raise Http404
python
{ "resource": "" }
q256799
GrantDataSharingPermissions.post
validation
def post(self, request): """ Process the above form. """ enterprise_uuid = request.POST.get('enterprise_customer_uuid') success_url = request.POST.get('redirect_url') failure_url = request.POST.get('failure_url') course_id = request.POST.get('course_id', '') program_uuid = request.POST.get('program_uuid', '') enterprise_customer = get_enterprise_customer_or_404(enterprise_uuid) context_data = get_global_context(request, enterprise_customer) if not (enterprise_uuid and success_url and failure_url): error_code = 'ENTGDS005' log_message = ( 'Error: one or more of the following values was falsy: ' 'enterprise_uuid: {enterprise_uuid}, ' 'success_url: {success_url}, ' 'failure_url: {failure_url} for course_id {course_id}. ' 'The following error code was reported to the user {userid}: {error_code}'.format( userid=request.user.id, enterprise_uuid=enterprise_uuid, success_url=success_url, failure_url=failure_url, error_code=error_code, course_id=course_id, ) ) return render_page_with_error_code_message(request, context_data, error_code, log_message) if not self.course_or_program_exist(course_id, program_uuid): error_code = 'ENTGDS006' log_message = ( 'Neither the course with course_id: {course_id} ' 'or program with {program_uuid} exist for ' 'enterprise customer {enterprise_uuid}' 'Error code {error_code} presented to user {userid}'.format( course_id=course_id, program_uuid=program_uuid, error_code=error_code, userid=request.user.id, enterprise_uuid=enterprise_uuid, ) ) return render_page_with_error_code_message(request, context_data, error_code, log_message) consent_record = get_data_sharing_consent( request.user.username, enterprise_uuid, program_uuid=program_uuid, course_id=course_id ) if consent_record is None: error_code = 'ENTGDS007'
python
{ "resource": "" }