• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python date_utils.strftime_localized函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中util.date_utils.strftime_localized函数的典型用法代码示例。如果您正苦于以下问题:Python strftime_localized函数的具体用法?Python strftime_localized怎么用?Python strftime_localized使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了strftime_localized函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: _assert_supplemented

    def _assert_supplemented(self, actual, **kwargs):
        """DRY helper used to verify that program data is extended correctly."""
        course_overview = CourseOverview.get_from_id(self.course.id)  # pylint: disable=no-member
        run_mode = dict(
            factories.RunMode(
                certificate_url=None,
                course_image_url=course_overview.course_image_url,
                course_key=unicode(self.course.id),  # pylint: disable=no-member
                course_url=reverse('course_root', args=[self.course.id]),  # pylint: disable=no-member
                end_date=strftime_localized(self.course.end, 'SHORT_DATE'),
                enrollment_open_date=strftime_localized(utils.DEFAULT_ENROLLMENT_START_DATE, 'SHORT_DATE'),
                is_course_ended=self.course.end < timezone.now(),
                is_enrolled=False,
                is_enrollment_open=True,
                marketing_url=MARKETING_URL,
                start_date=strftime_localized(self.course.start, 'SHORT_DATE'),
                upgrade_url=None,
            ),
            **kwargs
        )
        course_code = factories.CourseCode(display_name=self.course_code['display_name'], run_modes=[run_mode])
        expected = copy.deepcopy(self.program)
        expected['course_codes'] = [course_code]

        self.assertEqual(actual, expected)
开发者ID:CraftAcademy,项目名称:edx-platform,代码行数:25,代码来源:test_utils.py


示例2: test_expired_course

    def test_expired_course(self):
        """
        Ensure that a user accessing an expired course sees a redirect to
        the student dashboard, not a 404.
        """
        CourseDurationLimitConfig.objects.create(enabled=True, enabled_as_of=datetime(2010, 1, 1))
        course = CourseFactory.create(start=THREE_YEARS_AGO)
        url = course_home_url(course)

        for mode in [CourseMode.AUDIT, CourseMode.VERIFIED]:
            CourseModeFactory.create(course_id=course.id, mode_slug=mode)

        # assert that an if an expired audit user tries to access the course they are redirected to the dashboard
        audit_user = UserFactory(password=self.TEST_PASSWORD)
        self.client.login(username=audit_user.username, password=self.TEST_PASSWORD)
        audit_enrollment = CourseEnrollment.enroll(audit_user, course.id, mode=CourseMode.AUDIT)
        ScheduleFactory(start=THREE_YEARS_AGO, enrollment=audit_enrollment)

        response = self.client.get(url)

        expiration_date = strftime_localized(course.start + timedelta(weeks=4), 'SHORT_DATE')
        expected_params = QueryDict(mutable=True)
        course_name = CourseOverview.get_from_id(course.id).display_name_with_default
        expected_params['access_response_error'] = 'Access to {run} expired on {expiration_date}'.format(
            run=course_name,
            expiration_date=expiration_date
        )
        expected_url = '{url}?{params}'.format(
            url=reverse('dashboard'),
            params=expected_params.urlencode()
        )
        self.assertRedirects(response, expected_url)
开发者ID:mitocw,项目名称:edx-platform,代码行数:32,代码来源:test_course_home.py


示例3: get_user_orders

def get_user_orders(user):
    """Given a user, get the detail of all the orders from the Ecommerce service.

    Args:
        user (User): The user to authenticate as when requesting ecommerce.

    Returns:
        list of dict, representing orders returned by the Ecommerce service.
    """
    user_orders = []
    commerce_configuration = CommerceConfiguration.current()
    user_query = {'username': user.username}

    use_cache = commerce_configuration.is_cache_enabled
    cache_key = commerce_configuration.CACHE_KEY + '.' + str(user.id) if use_cache else None
    api = ecommerce_api_client(user)
    commerce_user_orders = get_edx_api_data(
        commerce_configuration, 'orders', api=api, querystring=user_query, cache_key=cache_key
    )

    for order in commerce_user_orders:
        if order['status'].lower() == 'complete':
            date_placed = datetime.strptime(order['date_placed'], "%Y-%m-%dT%H:%M:%SZ")
            order_data = {
                'number': order['number'],
                'price': order['total_excl_tax'],
                'order_date': strftime_localized(date_placed, 'SHORT_DATE'),
                'receipt_url': EcommerceService().get_receipt_page_url(order['number']),
                'lines': order['lines'],
            }
            user_orders.append(order_data)

    return user_orders
开发者ID:digitalsatori,项目名称:edx-platform,代码行数:33,代码来源:settings_views.py


示例4: _update_certificate_context

def _update_certificate_context(context, course, user_certificate, platform_name):
    """
    Build up the certificate web view context using the provided values
    (Helper method to keep the view clean)
    """
    # Populate dynamic output values using the course/certificate data loaded above
    certificate_type = context.get('certificate_type')

    # Override the defaults with any mode-specific static values
    context['certificate_id_number'] = user_certificate.verify_uuid
    context['certificate_verify_url'] = "{prefix}{uuid}{suffix}".format(
        prefix=context.get('certificate_verify_url_prefix'),
        uuid=user_certificate.verify_uuid,
        suffix=context.get('certificate_verify_url_suffix')
    )

    # Translators:  The format of the date includes the full name of the month
    date = display_date_for_certificate(course, user_certificate)
    context['certificate_date_issued'] = _('{month} {day}, {year}').format(
        month=strftime_localized(date, "%B"),
        day=date.day,
        year=date.year
    )

    # Translators:  This text represents the verification of the certificate
    context['document_meta_description'] = _('This is a valid {platform_name} certificate for {user_name}, '
                                             'who participated in {partner_short_name} {course_number}').format(
        platform_name=platform_name,
        user_name=context['accomplishment_copy_name'],
        partner_short_name=context['organization_short_name'],
        course_number=context['course_number']
    )

    # Translators:  This text is bound to the HTML 'title' element of the page and appears in the browser title bar
    context['document_title'] = _("{partner_short_name} {course_number} Certificate | {platform_name}").format(
        partner_short_name=context['organization_short_name'],
        course_number=context['course_number'],
        platform_name=platform_name
    )

    # Translators:  This text fragment appears after the student's name (displayed in a large font) on the certificate
    # screen.  The text describes the accomplishment represented by the certificate information displayed to the user
    context['accomplishment_copy_description_full'] = _("successfully completed, received a passing grade, and was "
                                                        "awarded this {platform_name} {certificate_type} "
                                                        "Certificate of Completion in ").format(
        platform_name=platform_name,
        certificate_type=context.get("certificate_type"))

    certificate_type_description = get_certificate_description(user_certificate.mode, certificate_type, platform_name)
    if certificate_type_description:
        context['certificate_type_description'] = certificate_type_description

    # Translators: This text describes the purpose (and therefore, value) of a course certificate
    context['certificate_info_description'] = _("{platform_name} acknowledges achievements through "
                                                "certificates, which are awarded for course activities "
                                                "that {platform_name} students complete.").format(
        platform_name=platform_name,
        tos_url=context.get('company_tos_url'),
        verified_cert_url=context.get('company_verified_certificate_url'))
开发者ID:dehamzah,项目名称:edx-platform,代码行数:59,代码来源:webview.py


示例5: enforce_compliance_on_login

def enforce_compliance_on_login(user, password):
    """
    Verify that the user's password is compliant with password policy rules and determine what should be done
    if it is not.

    Raises NonCompliantPasswordException when the password is found to be non-compliant and the compliance deadline
    for the user has been reached. In this case, login should be prevented.

    Raises NonCompliantPasswordWarning when the password is found to be non-compliant and the compliance deadline for
    the user is in the future.

    Returns None when the password is found to be compliant, or when no deadline for compliance has been set for the
    user.

    Important: This method should only be called AFTER the user has been authenticated.
    """
    is_compliant = _check_user_compliance(user, password)
    if is_compliant:
        return

    deadline = _get_compliance_deadline_for_user(user)
    if deadline is None:
        return

    now = datetime.now(pytz.UTC)
    if now >= deadline:
        raise NonCompliantPasswordException(
            HTML(_(
                u'{strong_tag_open}We recently changed our password requirements{strong_tag_close}{break_line_tag}'
                'Your current password does not meet the new security requirements. We just sent a password-reset '
                'message to the email address associated with this account. Thank you for helping us keep your data '
                'safe.'
            )).format(
                strong_tag_open=HTML('<strong>'),
                strong_tag_close=HTML('</strong>'),
                break_line_tag=HTML('<br/>'),
            )
        )
    else:
        raise NonCompliantPasswordWarning(
            HTML(_(
                u'{strong_tag_open}Required Action: Please update your password{strong_tag_close}{break_line_tag}'
                u'As of {deadline}, {platform_name} will require all learners to have complex passwords. Your current '
                u'password does not meet these requirements. To reset your password, go to to '
                u'{anchor_tag_open}Account Settings{anchor_tag_close}.'
            )).format(
                strong_tag_open=HTML('<strong>'),
                strong_tag_close=HTML('</strong>'),
                break_line_tag=HTML('<br/>'),
                platform_name=settings.PLATFORM_NAME,
                deadline=strftime_localized(deadline, DEFAULT_SHORT_DATE_FORMAT),
                anchor_tag_open=HTML(u'<a href="{account_settings_url}">').format(
                    account_settings_url=settings.LMS_ROOT_URL + "/account/settings"
                ),
                anchor_tag_close=HTML('</a>')
            )
        )
开发者ID:digitalsatori,项目名称:edx-platform,代码行数:57,代码来源:compliance.py


示例6: test_non_live_course

 def test_non_live_course(self):
     """Ensure that a user accessing a non-live course sees a redirect to
     the student dashboard, not a 404.
     """
     self.setup_user()
     self.enroll(self.course)
     url = reverse('info', args=[unicode(self.course.id)])
     response = self.client.get(url)
     start_date = strftime_localized(self.course.start, 'SHORT_DATE')
     self.assertRedirects(response, '{0}?{1}'.format(reverse('dashboard'), urlencode({'notlive': start_date})))
开发者ID:JioEducation,项目名称:edx-platform,代码行数:10,代码来源:test_course_info.py


示例7: check_course_access

def check_course_access(course, user, action, check_if_enrolled=False, check_survey_complete=True):
    """
    Check that the user has the access to perform the specified action
    on the course (CourseDescriptor|CourseOverview).

    check_if_enrolled: If true, additionally verifies that the user is enrolled.
    check_survey_complete: If true, additionally verifies that the user has completed the survey.
    """
    # Allow staff full access to the course even if not enrolled
    if has_access(user, 'staff', course.id):
        return

    request = get_current_request()
    check_content_start_date_for_masquerade_user(course.id, user, request, course.start)

    access_response = has_access(user, action, course, course.id)
    if not access_response:
        # Redirect if StartDateError
        if isinstance(access_response, StartDateError):
            start_date = strftime_localized(course.start, 'SHORT_DATE')
            params = QueryDict(mutable=True)
            params['notlive'] = start_date
            raise CourseAccessRedirect('{dashboard_url}?{params}'.format(
                dashboard_url=reverse('dashboard'),
                params=params.urlencode()
            ), access_response)

        # Redirect if AuditExpiredError
        if isinstance(access_response, AuditExpiredError):
            params = QueryDict(mutable=True)
            params['access_response_error'] = access_response.additional_context_user_message
            raise CourseAccessRedirect('{dashboard_url}?{params}'.format(
                dashboard_url=reverse('dashboard'),
                params=params.urlencode()
            ), access_response)

        # Redirect if the user must answer a survey before entering the course.
        if isinstance(access_response, MilestoneAccessError):
            raise CourseAccessRedirect('{dashboard_url}'.format(
                dashboard_url=reverse('dashboard'),
            ), access_response)

        # Deliberately return a non-specific error message to avoid
        # leaking info about access control settings
        raise CoursewareAccessException(access_response)

    if check_if_enrolled:
        # If the user is not enrolled, redirect them to the about page
        if not CourseEnrollment.is_enrolled(user, course.id):
            raise CourseAccessRedirect(reverse('about_course', args=[unicode(course.id)]))

    # Redirect if the user must answer a survey before entering the course.
    if check_survey_complete and action == 'load':
        if is_survey_required_and_unanswered(user, course):
            raise CourseAccessRedirect(reverse('course_survey', args=[unicode(course.id)]))
开发者ID:edx,项目名称:edx-platform,代码行数:55,代码来源:courses.py


示例8: get_expiration_banner_text

def get_expiration_banner_text(user, course, language='en'):
    """
    Get text for banner that messages user course expiration date
    for different tests that depend on it.
    """
    expiration_date = now() + timedelta(weeks=4)
    upgrade_link = verified_upgrade_deadline_link(user=user, course=course)
    enrollment = CourseEnrollment.get_enrollment(user, course.id)
    upgrade_deadline = enrollment.upgrade_deadline
    if upgrade_deadline is None or now() < upgrade_deadline:
        upgrade_deadline = enrollment.course_upgrade_deadline

    date_string = u'<span class="localized-datetime" data-format="shortDate" \
        data-datetime="{formatted_date}" data-language="{language}">{formatted_date_localized}</span>'
    formatted_expiration_date = date_string.format(
        language=language,
        formatted_date=expiration_date.strftime("%Y-%m-%d"),
        formatted_date_localized=strftime_localized(expiration_date, EXPIRATION_DATE_FORMAT_STR)
    )
    if upgrade_deadline:
        formatted_upgrade_deadline = date_string.format(
            language=language,
            formatted_date=upgrade_deadline.strftime("%Y-%m-%d"),
            formatted_date_localized=strftime_localized(upgrade_deadline, EXPIRATION_DATE_FORMAT_STR)
        )

        bannerText = u'<strong>Audit Access Expires {expiration_date}</strong><br>\
                     You lose all access to this course, including your progress, on {expiration_date}.\
                     <br>Upgrade by {upgrade_deadline} to get unlimited access to the course as long as it exists\
                     on the site. <a href="{upgrade_link}">Upgrade now<span class="sr-only"> to retain access past\
                     {expiration_date}</span></a>'.format(
            expiration_date=formatted_expiration_date,
            upgrade_link=upgrade_link,
            upgrade_deadline=formatted_upgrade_deadline
        )
    else:
        bannerText = u'<strong>Audit Access Expires {expiration_date}</strong><br>\
                     You lose all access to this course, including your progress, on {expiration_date}.\
                     '.format(
            expiration_date=formatted_expiration_date
        )
    return bannerText
开发者ID:edx,项目名称:edx-platform,代码行数:42,代码来源:helpers.py


示例9: test_course_enrollment_status

    def test_course_enrollment_status(self, start_offset, end_offset, is_enrollment_open):
        """Verify that course enrollment status is reflected correctly."""
        self.course.enrollment_start = timezone.now() - datetime.timedelta(days=start_offset)
        self.course.enrollment_end = timezone.now() - datetime.timedelta(days=end_offset)
        self.course = self.update_course(self.course, self.user.id)  # pylint: disable=no-member

        data = utils.ProgramDataExtender(self.program, self.user).extend()

        self._assert_supplemented(
            data,
            is_enrollment_open=is_enrollment_open,
            enrollment_open_date=strftime_localized(self.course.enrollment_start, 'SHORT_DATE'),
        )
开发者ID:CraftAcademy,项目名称:edx-platform,代码行数:13,代码来源:test_utils.py


示例10: supplement_program_data

def supplement_program_data(program_data, user):
    """Supplement program course codes with CourseOverview and CourseEnrollment data.

    Arguments:
        program_data (dict): Representation of a program.
        user (User): The user whose enrollments to inspect.
    """
    for organization in program_data['organizations']:
        # TODO cache the results of the get_organization_by_short_name call
        # so we don't have to hit database that frequently
        org_obj = get_organization_by_short_name(organization['key'])
        if org_obj and org_obj.get('logo'):
            organization['img'] = org_obj['logo'].url

    for course_code in program_data['course_codes']:
        for run_mode in course_code['run_modes']:
            course_key = CourseKey.from_string(run_mode['course_key'])
            course_overview = CourseOverview.get_from_id(course_key)

            run_mode['course_url'] = reverse('course_root', args=[course_key])
            run_mode['course_image_url'] = course_overview.course_image_url

            run_mode['start_date'] = course_overview.start_datetime_text()
            run_mode['end_date'] = course_overview.end_datetime_text()

            end_date = course_overview.end or datetime.datetime.max.replace(tzinfo=pytz.UTC)
            run_mode['is_course_ended'] = end_date < timezone.now()

            run_mode['is_enrolled'] = CourseEnrollment.is_enrolled(user, course_key)

            enrollment_start = course_overview.enrollment_start or datetime.datetime.min.replace(tzinfo=pytz.UTC)
            enrollment_end = course_overview.enrollment_end or datetime.datetime.max.replace(tzinfo=pytz.UTC)
            is_enrollment_open = enrollment_start <= timezone.now() < enrollment_end
            run_mode['is_enrollment_open'] = is_enrollment_open
            if not is_enrollment_open:
                # Only render this enrollment open date if the enrollment open is in the future
                run_mode['enrollment_open_date'] = strftime_localized(enrollment_start, 'SHORT_DATE')

            # TODO: Currently unavailable on LMS.
            run_mode['marketing_url'] = ''

            certificate_data = certificate_api.certificate_downloadable_status(user, course_key)
            certificate_uuid = certificate_data.get('uuid')
            if certificate_uuid:
                run_mode['certificate_url'] = certificate_api.get_certificate_url(
                    course_id=course_key,
                    uuid=certificate_uuid,
                )

    return program_data
开发者ID:microfins,项目名称:edx-platform,代码行数:50,代码来源:utils.py


示例11: strftime

 def strftime(self, *args, **kwargs):
     """
     A locale-aware implementation of strftime.
     """
     # This is the wrong place to import this function.  I'm putting it here
     # because the xmodule test suite can't import this module, because
     # Django is not available in that suite.  This function isn't called in
     # that suite, so this hides the import so the test won't fail.
     #
     # As I said, this is wrong.  But Cale says this code will soon be
     # refactored to a place that will be right, and the code can be made
     # right there.  If you are reading this comment after April 1, 2014,
     # then Cale was a liar.
     from util.date_utils import strftime_localized
     return strftime_localized(*args, **kwargs)
开发者ID:CDOT-EDX,项目名称:edx-platform,代码行数:15,代码来源:django.py


示例12: to_dict

    def to_dict(self):
        """
        Convert entitlement to dictionary representation including relevant policy information.

        Returns:
            The entitlement UUID
            The associated course's UUID
            The date at which the entitlement expired. None if it is still active.
            The localized string representing the date at which the entitlement expires.
        """
        expiration_date = None
        if self.get_days_until_expiration() < settings.ENTITLEMENT_EXPIRED_ALERT_PERIOD:
            expiration_date = strftime_localized(
                now() + timedelta(days=self.get_days_until_expiration()),
                'SHORT_DATE'
            )
        expired_at = strftime_localized(self.expired_at_datetime, 'SHORT_DATE') if self.expired_at_datetime else None

        return {
            'uuid': str(self.uuid),
            'course_uuid': str(self.course_uuid),
            'expired_at': expired_at,
            'expiration_date': expiration_date
        }
开发者ID:albluqmun,项目名称:edx-platform,代码行数:24,代码来源:models.py


示例13: test_no_enrollment_start_date

    def test_no_enrollment_start_date(self):
        """Verify that a closed course with no explicit enrollment start date doesn't cause an error.

        Regression test for ECOM-4973.
        """
        self.course.enrollment_end = timezone.now() - datetime.timedelta(days=1)
        self.course = self.update_course(self.course, self.user.id)  # pylint: disable=no-member

        data = utils.supplement_program_data(self.program, self.user)

        self._assert_supplemented(
            data,
            is_enrollment_open=False,
            enrollment_open_date=strftime_localized(utils.DEFAULT_ENROLLMENT_START_DATE, 'SHORT_DATE'),
        )
开发者ID:bingworld,项目名称:edx-platform,代码行数:15,代码来源:test_utils.py


示例14: test_course_run_enrollment_status

    def test_course_run_enrollment_status(self, start_offset, end_offset, is_enrollment_open):
        """
        Verify that course run enrollment status is reflected correctly.
        """
        self.course.enrollment_start = datetime.datetime.now(utc) - datetime.timedelta(days=start_offset)
        self.course.enrollment_end = datetime.datetime.now(utc) - datetime.timedelta(days=end_offset)

        self.course = self.update_course(self.course, self.user.id)

        data = ProgramDataExtender(self.program, self.user).extend()

        self._assert_supplemented(
            data,
            is_enrollment_open=is_enrollment_open,
            enrollment_open_date=strftime_localized(self.course.enrollment_start, 'SHORT_DATE'),
        )
开发者ID:dehamzah,项目名称:edx-platform,代码行数:16,代码来源:test_utils.py


示例15: test_non_live_course

 def test_non_live_course(self):
     """Ensure that a user accessing a non-live course sees a redirect to
     the student dashboard, not a 404.
     """
     self.setup_user()
     self.enroll(self.course)
     url = reverse('info', args=[unicode(self.course.id)])
     response = self.client.get(url)
     start_date = strftime_localized(self.course.start, 'SHORT_DATE')
     expected_params = QueryDict(mutable=True)
     expected_params['notlive'] = start_date
     expected_url = '{url}?{params}'.format(
         url=reverse('dashboard'),
         params=expected_params.urlencode()
     )
     self.assertRedirects(response, expected_url)
开发者ID:Colin-Fredericks,项目名称:edx-platform,代码行数:16,代码来源:test_course_info.py


示例16: enforce_compliance_on_login

def enforce_compliance_on_login(user, password):
    """
    Verify that the user's password is compliant with password policy rules and determine what should be done
    if it is not.

    Raises NonCompliantPasswordException when the password is found to be non-compliant and the compliance deadline
    for the user has been reached. In this case, login should be prevented.

    Raises NonCompliantPasswordWarning when the password is found to be non-compliant and the compliance deadline for
    the user is in the future.

    Returns None when the password is found to be compliant, or when no deadline for compliance has been set for the
    user.

    Important: This method should only be called AFTER the user has been authenticated.
    """
    is_compliant = _check_user_compliance(user, password)
    if is_compliant:
        return

    deadline = _get_compliance_deadline_for_user(user)
    if deadline is None:
        return

    now = datetime.now(pytz.UTC)
    if now >= deadline:
        raise NonCompliantPasswordException(
            _capitalize_first(_(
                '{platform_name} now requires more complex passwords. Your current password does not meet the new '
                'requirements. Change your password now using the "Forgot password?" link below to continue using the '
                'site. Thank you for helping us keep your data safe.'
            ).format(
                platform_name=settings.PLATFORM_NAME
            ))
        )
    else:
        raise NonCompliantPasswordWarning(
            _capitalize_first(_(
                '{platform_name} now requires more complex passwords. Your current password does not meet the new '
                'requirements. You must change your password by {deadline} to be able to continue using the site. '
                'To change your password, select the dropdown menu icon next to your username, then select "Account". '
                'You can reset your password from this page. Thank you for helping us keep your data safe.'
            ).format(
                platform_name=settings.PLATFORM_NAME,
                deadline=strftime_localized(deadline, DEFAULT_SHORT_DATE_FORMAT)
            ))
        )
开发者ID:cmscom,项目名称:edx-platform,代码行数:47,代码来源:compliance.py


示例17: _get_asset_json

def _get_asset_json(display_name, date, location, thumbnail_location, locked):
    """
    Helper method for formatting the asset information to send to client.
    """
    asset_url = StaticContent.get_url_path_from_location(location)
    external_url = settings.LMS_BASE + asset_url
    return {
        'display_name': display_name,
        'date_added': strftime_localized(date, "%m %d, %Y %H:%M"),
        'url': asset_url,
        'external_url': external_url,
        'portable_url': StaticContent.get_static_path_from_location(location),
        'thumbnail': StaticContent.get_url_path_from_location(thumbnail_location) if thumbnail_location is not None else None,
        'locked': locked,
        # Needed for Backbone delete/update.
        'id': asset_url
    }
开发者ID:altsen,项目名称:xiaodun-platform,代码行数:17,代码来源:assets.py


示例18: get_user_orders

def get_user_orders(user):
    """Given a user, get the detail of all the orders from the Ecommerce service.

    Arguments:
        user (User): The user to authenticate as when requesting ecommerce.

    Returns:
        list of dict, representing orders returned by the Ecommerce service.
    """
    no_data = []
    user_orders = []
    allowed_course_modes = ['professional', 'verified', 'credit']
    commerce_configuration = CommerceConfiguration.current()
    user_query = {'username': user.username}

    use_cache = commerce_configuration.is_cache_enabled
    cache_key = commerce_configuration.CACHE_KEY + '.' + str(user.id) if use_cache else None
    api = ecommerce_api_client(user)
    commerce_user_orders = get_edx_api_data(
        commerce_configuration, user, 'orders', api=api, querystring=user_query, cache_key=cache_key
    )

    for order in commerce_user_orders:
        if order['status'].lower() == 'complete':
            for line in order['lines']:
                product = line.get('product')
                if product:
                    for attribute in product['attribute_values']:
                        if attribute['name'] == 'certificate_type' and attribute['value'] in allowed_course_modes:
                            try:
                                date_placed = datetime.strptime(order['date_placed'], "%Y-%m-%dT%H:%M:%SZ")
                                order_data = {
                                    'number': order['number'],
                                    'price': order['total_excl_tax'],
                                    'title': order['lines'][0]['title'],
                                    'order_date': strftime_localized(
                                        date_placed.replace(tzinfo=pytz.UTC), 'SHORT_DATE'
                                    ),
                                    'receipt_url': commerce_configuration.receipt_page + order['number']
                                }
                                user_orders.append(order_data)
                            except KeyError:
                                log.exception('Invalid order structure: %r', order)
                                return no_data

    return user_orders
开发者ID:imranariffin,项目名称:edx-platform,代码行数:46,代码来源:views.py


示例19: get_user_orders

def get_user_orders(user):
    """Given a user, get the detail of all the orders from the Ecommerce service.

    Arguments:
        user (User): The user to authenticate as when requesting ecommerce.

    Returns:
        list of dict, representing orders returned by the Ecommerce service.
    """
    no_data = []
    user_orders = []
    allowed_course_modes = ["professional", "verified", "credit"]
    commerce_configuration = CommerceConfiguration.current()
    user_query = {"username": user.username}

    use_cache = commerce_configuration.is_cache_enabled
    cache_key = commerce_configuration.CACHE_KEY + "." + str(user.id) if use_cache else None
    api = ecommerce_api_client(user)
    commerce_user_orders = get_edx_api_data(
        commerce_configuration, user, "orders", api=api, querystring=user_query, cache_key=cache_key
    )

    for order in commerce_user_orders:
        if order["status"].lower() == "complete":
            for line in order["lines"]:
                product = line.get("product")
                if product:
                    for attribute in product["attribute_values"]:
                        if attribute["name"] == "certificate_type" and attribute["value"] in allowed_course_modes:
                            try:
                                date_placed = datetime.strptime(order["date_placed"], "%Y-%m-%dT%H:%M:%SZ")
                                order_data = {
                                    "number": order["number"],
                                    "price": order["total_excl_tax"],
                                    "title": order["lines"][0]["title"],
                                    "order_date": strftime_localized(
                                        date_placed.replace(tzinfo=pytz.UTC), "SHORT_DATE"
                                    ),
                                    "receipt_url": commerce_configuration.receipt_page + order["number"],
                                }
                                user_orders.append(order_data)
                            except KeyError:
                                log.exception("Invalid order structure: %r", order)
                                return no_data

    return user_orders
开发者ID:moonshot,项目名称:edx-platform,代码行数:46,代码来源:views.py


示例20: test_non_live_course

    def test_non_live_course(self):
        """
        Ensure that a user accessing a non-live course sees a redirect to
        the student dashboard, not a 404.
        """
        future_course = self.create_future_course()
        self.create_user_for_course(future_course, CourseUserType.ENROLLED)

        url = course_home_url(future_course)
        response = self.client.get(url)
        start_date = strftime_localized(future_course.start, 'SHORT_DATE')
        expected_params = QueryDict(mutable=True)
        expected_params['notlive'] = start_date
        expected_url = '{url}?{params}'.format(
            url=reverse('dashboard'),
            params=expected_params.urlencode()
        )
        self.assertRedirects(response, expected_url)
开发者ID:mitocw,项目名称:edx-platform,代码行数:18,代码来源:test_course_home.py



注:本文中的util.date_utils.strftime_localized函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python date_utils.to_timestamp函数代码示例发布时间:2022-05-26
下一篇:
Python date_utils.get_time_display函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap