本文整理汇总了Python中openedx.features.content_type_gating.models.ContentTypeGatingConfig类的典型用法代码示例。如果您正苦于以下问题:Python ContentTypeGatingConfig类的具体用法?Python ContentTypeGatingConfig怎么用?Python ContentTypeGatingConfig使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ContentTypeGatingConfig类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _get_course_duration_info
def _get_course_duration_info(self, course_key):
"""
Fetch course duration information from database
"""
try:
key = CourseKey.from_string(course_key)
course = CourseOverview.objects.values('display_name').get(id=key)
duration_config = CourseDurationLimitConfig.current(course_key=key)
gating_config = ContentTypeGatingConfig.current(course_key=key)
duration_enabled = CourseDurationLimitConfig.enabled_for_course(course_key=key)
gating_enabled = ContentTypeGatingConfig.enabled_for_course(course_key=key)
gating_dict = {
'enabled': gating_enabled,
'enabled_as_of': str(gating_config.enabled_as_of) if gating_config.enabled_as_of else 'N/A',
'reason': gating_config.provenances['enabled'].value
}
duration_dict = {
'enabled': duration_enabled,
'enabled_as_of': str(duration_config.enabled_as_of) if duration_config.enabled_as_of else 'N/A',
'reason': duration_config.provenances['enabled'].value
}
return {
'course_id': course_key,
'course_name': course.get('display_name'),
'gating_config': gating_dict,
'duration_config': duration_dict,
}
except (ObjectDoesNotExist, InvalidKeyError):
return {}
示例2: test_enabled_for_course
def test_enabled_for_course(
self,
before_enabled,
):
config = ContentTypeGatingConfig.objects.create(
enabled=True,
course=self.course_overview,
enabled_as_of=timezone.now(),
)
# Tweak the datetime to check for course enablement so it is either
# before or after when the configuration was enabled
if before_enabled:
target_datetime = config.enabled_as_of - timedelta(days=1)
else:
target_datetime = config.enabled_as_of + timedelta(days=1)
course_key = self.course_overview.id
self.assertEqual(
not before_enabled,
ContentTypeGatingConfig.enabled_for_course(
course_key=course_key,
target_datetime=target_datetime,
)
)
示例3: get_group_for_user
def get_group_for_user(cls, course_key, user, user_partition, **kwargs): # pylint: disable=unused-argument
"""
Returns the Group for the specified user.
"""
if not ContentTypeGatingConfig.enabled_for_enrollment(user=user, course_key=course_key,
user_partition=user_partition):
return FULL_ACCESS
else:
return LIMITED_ACCESS
示例4: test_all_current_course_configs
def test_all_current_course_configs(self):
# Set up test objects
for global_setting in (True, False, None):
ContentTypeGatingConfig.objects.create(enabled=global_setting, enabled_as_of=datetime(2018, 1, 1))
for site_setting in (True, False, None):
test_site_cfg = SiteConfigurationFactory.create(values={'course_org_filter': []})
ContentTypeGatingConfig.objects.create(site=test_site_cfg.site, enabled=site_setting, enabled_as_of=datetime(2018, 1, 1))
for org_setting in (True, False, None):
test_org = "{}-{}".format(test_site_cfg.id, org_setting)
test_site_cfg.values['course_org_filter'].append(test_org)
test_site_cfg.save()
ContentTypeGatingConfig.objects.create(org=test_org, enabled=org_setting, enabled_as_of=datetime(2018, 1, 1))
for course_setting in (True, False, None):
test_course = CourseOverviewFactory.create(
org=test_org,
id=CourseLocator(test_org, 'test_course', 'run-{}'.format(course_setting))
)
ContentTypeGatingConfig.objects.create(course=test_course, enabled=course_setting, enabled_as_of=datetime(2018, 1, 1))
with self.assertNumQueries(4):
all_configs = ContentTypeGatingConfig.all_current_course_configs()
# Deliberatly using the last all_configs that was checked after the 3rd pass through the global_settings loop
# We should be creating 3^4 courses (3 global values * 3 site values * 3 org values * 3 course values)
# Plus 1 for the edX/toy/2012_Fall course
self.assertEqual(len(all_configs), 3**4 + 1)
# Point-test some of the final configurations
self.assertEqual(
all_configs[CourseLocator('7-True', 'test_course', 'run-None')],
{
'enabled': (True, Provenance.org),
'enabled_as_of': (datetime(2018, 1, 1, 5, tzinfo=pytz.UTC), Provenance.run),
'studio_override_enabled': (None, Provenance.default),
}
)
self.assertEqual(
all_configs[CourseLocator('7-True', 'test_course', 'run-False')],
{
'enabled': (False, Provenance.run),
'enabled_as_of': (datetime(2018, 1, 1, 5, tzinfo=pytz.UTC), Provenance.run),
'studio_override_enabled': (None, Provenance.default),
}
)
self.assertEqual(
all_configs[CourseLocator('7-None', 'test_course', 'run-None')],
{
'enabled': (True, Provenance.site),
'enabled_as_of': (datetime(2018, 1, 1, 5, tzinfo=pytz.UTC), Provenance.run),
'studio_override_enabled': (None, Provenance.default),
}
)
示例5: test_config_overrides
def test_config_overrides(self, global_setting, site_setting, org_setting, course_setting):
"""
Test that the stacked configuration overrides happen in the correct order and priority.
This is tested by exhaustively setting each combination of contexts, and validating that only
the lowest level context that is set to not-None is applied.
"""
# Add a bunch of configuration outside the contexts that are being tested, to make sure
# there are no leaks of configuration across contexts
non_test_course_enabled = CourseOverviewFactory.create(org='non-test-org-enabled')
non_test_course_disabled = CourseOverviewFactory.create(org='non-test-org-disabled')
non_test_site_cfg_enabled = SiteConfigurationFactory.create(values={'course_org_filter': non_test_course_enabled.org})
non_test_site_cfg_disabled = SiteConfigurationFactory.create(values={'course_org_filter': non_test_course_disabled.org})
ContentTypeGatingConfig.objects.create(course=non_test_course_enabled, enabled=True, enabled_as_of=datetime(2018, 1, 1))
ContentTypeGatingConfig.objects.create(course=non_test_course_disabled, enabled=False)
ContentTypeGatingConfig.objects.create(org=non_test_course_enabled.org, enabled=True, enabled_as_of=datetime(2018, 1, 1))
ContentTypeGatingConfig.objects.create(org=non_test_course_disabled.org, enabled=False)
ContentTypeGatingConfig.objects.create(site=non_test_site_cfg_enabled.site, enabled=True, enabled_as_of=datetime(2018, 1, 1))
ContentTypeGatingConfig.objects.create(site=non_test_site_cfg_disabled.site, enabled=False)
# Set up test objects
test_course = CourseOverviewFactory.create(org='test-org')
test_site_cfg = SiteConfigurationFactory.create(values={'course_org_filter': test_course.org})
ContentTypeGatingConfig.objects.create(enabled=global_setting, enabled_as_of=datetime(2018, 1, 1))
ContentTypeGatingConfig.objects.create(course=test_course, enabled=course_setting, enabled_as_of=datetime(2018, 1, 1))
ContentTypeGatingConfig.objects.create(org=test_course.org, enabled=org_setting, enabled_as_of=datetime(2018, 1, 1))
ContentTypeGatingConfig.objects.create(site=test_site_cfg.site, enabled=site_setting, enabled_as_of=datetime(2018, 1, 1))
all_settings = [global_setting, site_setting, org_setting, course_setting]
expected_global_setting = self._resolve_settings([global_setting])
expected_site_setting = self._resolve_settings([global_setting, site_setting])
expected_org_setting = self._resolve_settings([global_setting, site_setting, org_setting])
expected_course_setting = self._resolve_settings([global_setting, site_setting, org_setting, course_setting])
self.assertEqual(expected_global_setting, ContentTypeGatingConfig.current().enabled)
self.assertEqual(expected_site_setting, ContentTypeGatingConfig.current(site=test_site_cfg.site).enabled)
self.assertEqual(expected_org_setting, ContentTypeGatingConfig.current(org=test_course.org).enabled)
self.assertEqual(expected_course_setting, ContentTypeGatingConfig.current(course_key=test_course.id).enabled)
示例6: create_content_gating_partition
def create_content_gating_partition(course):
"""
Create and return the Content Gating user partition.
"""
enabled_for_course = ContentTypeGatingConfig.enabled_for_course(course_key=course.id)
studio_override_for_course = ContentTypeGatingConfig.current(course_key=course.id).studio_override_enabled
if not (enabled_for_course or studio_override_for_course):
return None
try:
content_gate_scheme = UserPartition.get_scheme(CONTENT_TYPE_GATING_SCHEME)
except UserPartitionError:
LOG.warning(
u"No %r scheme registered, ContentTypeGatingPartitionScheme will not be created.",
CONTENT_TYPE_GATING_SCHEME
)
return None
used_ids = set(p.id for p in course.user_partitions)
if CONTENT_GATING_PARTITION_ID in used_ids:
# It's possible for course authors to add arbitrary partitions via XML import. If they do, and create a
# partition with id 51, it will collide with the Content Gating Partition. We'll catch that here, and
# then fix the course content as needed (or get the course team to).
LOG.warning(
u"Can't add %r partition, as ID %r is assigned to %r in course %s.",
CONTENT_TYPE_GATING_SCHEME,
CONTENT_GATING_PARTITION_ID,
_get_partition_from_id(course.user_partitions, CONTENT_GATING_PARTITION_ID).name,
unicode(course.id),
)
return None
partition = content_gate_scheme.create_user_partition(
id=CONTENT_GATING_PARTITION_ID,
name=_(u"Feature-based Enrollments"),
description=_(u"Partition for segmenting users by access to gated content types"),
parameters={"course_id": unicode(course.id)}
)
return partition
示例7: test_enabled_for_enrollment_failure
def test_enabled_for_enrollment_failure(self):
with self.assertRaises(ValueError):
ContentTypeGatingConfig.enabled_for_enrollment(None, None, None)
with self.assertRaises(ValueError):
ContentTypeGatingConfig.enabled_for_enrollment(Mock(name='enrollment'), Mock(name='user'), None)
with self.assertRaises(ValueError):
ContentTypeGatingConfig.enabled_for_enrollment(Mock(name='enrollment'), None, Mock(name='course_key'))
示例8: test_caching_global
def test_caching_global(self):
global_config = ContentTypeGatingConfig(enabled=True, enabled_as_of=datetime(2018, 1, 1))
global_config.save()
# Check that the global value is not retrieved from cache after save
with self.assertNumQueries(1):
self.assertTrue(ContentTypeGatingConfig.current().enabled)
# Check that the global value can be retrieved from cache after read
with self.assertNumQueries(0):
self.assertTrue(ContentTypeGatingConfig.current().enabled)
global_config.enabled = False
global_config.save()
# Check that the global value in cache was deleted on save
with self.assertNumQueries(1):
self.assertFalse(ContentTypeGatingConfig.current().enabled)
示例9: test_enabled_for_enrollment
def test_enabled_for_enrollment(
self,
already_enrolled,
pass_enrollment,
enrolled_before_enabled,
):
# Tweak the datetime to enable the config so that it is either before
# or after now (which is when the enrollment will be created)
if enrolled_before_enabled:
enabled_as_of = datetime.now() + timedelta(days=1)
else:
enabled_as_of = datetime.now() - timedelta(days=1)
config = ContentTypeGatingConfig.objects.create(
enabled=True,
course=self.course_overview,
enabled_as_of=enabled_as_of,
)
if already_enrolled:
existing_enrollment = CourseEnrollmentFactory.create(
user=self.user,
course=self.course_overview,
)
else:
existing_enrollment = None
if pass_enrollment:
enrollment = existing_enrollment
user = None
course_key = None
else:
enrollment = None
user = self.user
course_key = self.course_overview.id
if already_enrolled and pass_enrollment:
query_count = 4
elif not pass_enrollment and already_enrolled:
query_count = 6
else:
query_count = 5
with self.assertNumQueries(query_count):
enabled = ContentTypeGatingConfig.enabled_for_enrollment(
enrollment=enrollment,
user=user,
course_key=course_key,
)
self.assertEqual(not enrolled_before_enabled, enabled)
示例10: get_group_for_user
def get_group_for_user(cls, course_key, user, user_partition, **kwargs): # pylint: disable=unused-argument
"""
Returns the Group for the specified user.
"""
# For now, treat everyone as a Full-access user, until we have the rest of the
# feature gating logic in place.
if not ContentTypeGatingConfig.enabled_for_enrollment(user=user, course_key=course_key,
user_partition=user_partition):
return FULL_ACCESS
# If CONTENT_TYPE_GATING is enabled use the following logic to determine whether a user should have FULL_ACCESS
# or LIMITED_ACCESS
course_mode = apps.get_model('course_modes.CourseMode')
modes = course_mode.modes_for_course(course_key, include_expired=True, only_selectable=False)
modes_dict = {mode.slug: mode for mode in modes}
# If there is no verified mode, all users are granted FULL_ACCESS
if not course_mode.has_verified_mode(modes_dict):
return FULL_ACCESS
course_enrollment = apps.get_model('student.CourseEnrollment')
mode_slug, is_active = course_enrollment.enrollment_mode_for_user(user, course_key)
if mode_slug and is_active:
course_mode = course_mode.mode_for_course(
course_key,
mode_slug,
modes=modes,
)
if course_mode is None:
LOG.error(
u"User %s is in an unknown CourseMode '%s'"
u" for course %s. Granting full access to content for this user",
user.username,
mode_slug,
course_key,
)
return FULL_ACCESS
if mode_slug == CourseMode.AUDIT:
return LIMITED_ACCESS
else:
return FULL_ACCESS
else:
# Unenrolled users don't get gated content
return LIMITED_ACCESS
示例11: transform
def transform(self, usage_info, block_structure):
if not ContentTypeGatingConfig.enabled_for_enrollment(
user=usage_info.user,
course_key=usage_info.course_key,
):
return
for block_key in block_structure.topological_traversal():
graded = block_structure.get_xblock_field(block_key, 'graded')
has_score = block_structure.get_xblock_field(block_key, 'has_score')
weight_not_zero = block_structure.get_xblock_field(block_key, 'weight') != 0
problem_eligible_for_content_gating = graded and has_score and weight_not_zero
if problem_eligible_for_content_gating:
current_access = block_structure.get_xblock_field(block_key, 'group_access')
if current_access is None:
current_access = {}
current_access.setdefault(
CONTENT_GATING_PARTITION_ID,
[settings.CONTENT_TYPE_GATE_GROUP_IDS['full_access']]
)
block_structure.override_xblock_field(block_key, 'group_access', current_access)
示例12: _get_course_duration_info
def _get_course_duration_info(self, course_key):
"""
Fetch course duration information from database
"""
results = []
try:
key = CourseKey.from_string(course_key)
course = CourseOverview.objects.values('display_name').get(id=key)
duration_config = CourseDurationLimitConfig.current(course_key=key)
gating_config = ContentTypeGatingConfig.current(course_key=key)
partially_enabled = duration_config.enabled != gating_config.enabled
if partially_enabled:
if duration_config.enabled:
enabled = 'Course Duration Limits Only'
enabled_as_of = str(duration_config.enabled_as_of) if duration_config.enabled_as_of else 'N/A'
reason = 'Course duration limits are enabled for this course, but content type gating is disabled.'
elif gating_config.enabled:
enabled = 'Content Type Gating Only'
enabled_as_of = str(gating_config.enabled_as_of) if gating_config.enabled_as_of else 'N/A'
reason = 'Content type gating is enabled for this course, but course duration limits are disabled.'
else:
enabled = duration_config.enabled or False
enabled_as_of = str(duration_config.enabled_as_of) if duration_config.enabled_as_of else 'N/A'
reason = duration_config.provenances['enabled']
data = {
'course_id': course_key,
'course_name': course.get('display_name'),
'enabled': enabled,
'enabled_as_of': enabled_as_of,
'reason': reason,
}
results.append(data)
except (ObjectDoesNotExist, InvalidKeyError):
pass
return results
示例13: get_visibility_partition_info
def get_visibility_partition_info(xblock, course=None):
"""
Retrieve user partition information for the component visibility editor.
This pre-processes partition information to simplify the template.
Arguments:
xblock (XBlock): The component being edited.
course (XBlock): The course descriptor. If provided, uses this to look up the user partitions
instead of loading the course. This is useful if we're calling this function multiple
times for the same course want to minimize queries to the modulestore.
Returns: dict
"""
selectable_partitions = []
# We wish to display enrollment partitions before cohort partitions.
enrollment_user_partitions = get_user_partition_info(xblock, schemes=["enrollment_track"], course=course)
# For enrollment partitions, we only show them if there is a selected group or
# or if the number of groups > 1.
for partition in enrollment_user_partitions:
if len(partition["groups"]) > 1 or any(group["selected"] for group in partition["groups"]):
selectable_partitions.append(partition)
course_key = xblock.scope_ids.usage_id.course_key
is_library = isinstance(course_key, LibraryLocator)
if not is_library and ContentTypeGatingConfig.current(course_key=course_key).studio_override_enabled:
selectable_partitions += get_user_partition_info(xblock, schemes=[CONTENT_TYPE_GATING_SCHEME], course=course)
# Now add the cohort user partitions.
selectable_partitions = selectable_partitions + get_user_partition_info(xblock, schemes=["cohort"], course=course)
# Find the first partition with a selected group. That will be the one initially enabled in the dialog
# (if the course has only been added in Studio, only one partition should have a selected group).
selected_partition_index = -1
# At the same time, build up all the selected groups as they are displayed in the dialog title.
selected_groups_label = ''
for index, partition in enumerate(selectable_partitions):
for group in partition["groups"]:
if group["selected"]:
if len(selected_groups_label) == 0:
selected_groups_label = group['name']
else:
# Translators: This is building up a list of groups. It is marked for translation because of the
# comma, which is used as a separator between each group.
selected_groups_label = _(u'{previous_groups}, {current_group}').format(
previous_groups=selected_groups_label,
current_group=group['name']
)
if selected_partition_index == -1:
selected_partition_index = index
return {
"selectable_partitions": selectable_partitions,
"selected_partition_index": selected_partition_index,
"selected_groups_label": selected_groups_label,
}
示例14: get
def get(self, request, course_id, error=None):
"""Displays the course mode choice page.
Args:
request (`Request`): The Django Request object.
course_id (unicode): The slash-separated course key.
Keyword Args:
error (unicode): If provided, display this error message
on the page.
Returns:
Response
"""
course_key = CourseKey.from_string(course_id)
# Check whether the user has access to this course
# based on country access rules.
embargo_redirect = embargo_api.redirect_if_blocked(
course_key,
user=request.user,
ip_address=get_ip(request),
url=request.path
)
if embargo_redirect:
return redirect(embargo_redirect)
enrollment_mode, is_active = CourseEnrollment.enrollment_mode_for_user(request.user, course_key)
modes = CourseMode.modes_for_course_dict(course_key)
ecommerce_service = EcommerceService()
# We assume that, if 'professional' is one of the modes, it should be the *only* mode.
# If there are both modes, default to non-id-professional.
has_enrolled_professional = (CourseMode.is_professional_slug(enrollment_mode) and is_active)
if CourseMode.has_professional_mode(modes) and not has_enrolled_professional:
purchase_workflow = request.GET.get("purchase_workflow", "single")
verify_url = reverse('verify_student_start_flow', kwargs={'course_id': unicode(course_key)})
redirect_url = "{url}?purchase_workflow={workflow}".format(url=verify_url, workflow=purchase_workflow)
if ecommerce_service.is_enabled(request.user):
professional_mode = modes.get(CourseMode.NO_ID_PROFESSIONAL_MODE) or modes.get(CourseMode.PROFESSIONAL)
if purchase_workflow == "single" and professional_mode.sku:
redirect_url = ecommerce_service.get_checkout_page_url(professional_mode.sku)
if purchase_workflow == "bulk" and professional_mode.bulk_sku:
redirect_url = ecommerce_service.get_checkout_page_url(professional_mode.bulk_sku)
return redirect(redirect_url)
course = modulestore().get_course(course_key)
# If there isn't a verified mode available, then there's nothing
# to do on this page. Send the user to the dashboard.
if not CourseMode.has_verified_mode(modes):
return redirect(reverse('dashboard'))
# If a user has already paid, redirect them to the dashboard.
if is_active and (enrollment_mode in CourseMode.VERIFIED_MODES + [CourseMode.NO_ID_PROFESSIONAL_MODE]):
# If the course has started redirect to course home instead
if course.has_started():
return redirect(reverse('openedx.course_experience.course_home', kwargs={'course_id': course_key}))
return redirect(reverse('dashboard'))
donation_for_course = request.session.get("donation_for_course", {})
chosen_price = donation_for_course.get(unicode(course_key), None)
if CourseEnrollment.is_enrollment_closed(request.user, course):
locale = to_locale(get_language())
enrollment_end_date = format_datetime(course.enrollment_end, 'short', locale=locale)
params = urllib.urlencode({'course_closed': enrollment_end_date})
return redirect('{0}?{1}'.format(reverse('dashboard'), params))
# When a credit mode is available, students will be given the option
# to upgrade from a verified mode to a credit mode at the end of the course.
# This allows students who have completed photo verification to be eligible
# for univerity credit.
# Since credit isn't one of the selectable options on the track selection page,
# we need to check *all* available course modes in order to determine whether
# a credit mode is available. If so, then we show slightly different messaging
# for the verified track.
has_credit_upsell = any(
CourseMode.is_credit_mode(mode) for mode
in CourseMode.modes_for_course(course_key, only_selectable=False)
)
course_id = text_type(course_key)
context = {
"course_modes_choose_url": reverse(
"course_modes_choose",
kwargs={'course_id': course_id}
),
"modes": modes,
"has_credit_upsell": has_credit_upsell,
"course_name": course.display_name_with_default,
"course_org": course.display_org_with_default,
"course_num": course.display_number_with_default,
"chosen_price": chosen_price,
"error": error,
"responsive": True,
"nav_hidden": True,
"content_gating_enabled": ContentTypeGatingConfig.enabled_for_enrollment(
user=request.user,
#.........这里部分代码省略.........
示例15: test_caching_course
def test_caching_course(self):
course = CourseOverviewFactory.create(org='test-org')
site_cfg = SiteConfigurationFactory.create(values={'course_org_filter': course.org})
course_config = ContentTypeGatingConfig(course=course, enabled=True, enabled_as_of=datetime(2018, 1, 1))
course_config.save()
RequestCache.clear_all_namespaces()
# Check that the org value is not retrieved from cache after save
with self.assertNumQueries(2):
self.assertTrue(ContentTypeGatingConfig.current(course_key=course.id).enabled)
RequestCache.clear_all_namespaces()
# Check that the org value can be retrieved from cache after read
with self.assertNumQueries(0):
self.assertTrue(ContentTypeGatingConfig.current(course_key=course.id).enabled)
course_config.enabled = False
course_config.save()
RequestCache.clear_all_namespaces()
# Check that the org value in cache was deleted on save
with self.assertNumQueries(2):
self.assertFalse(ContentTypeGatingConfig.current(course_key=course.id).enabled)
global_config = ContentTypeGatingConfig(enabled=True, enabled_as_of=datetime(2018, 1, 1))
global_config.save()
RequestCache.clear_all_namespaces()
# Check that the org value is not updated in cache by changing the global value
with self.assertNumQueries(0):
self.assertFalse(ContentTypeGatingConfig.current(course_key=course.id).enabled)
site_config = ContentTypeGatingConfig(site=site_cfg.site, enabled=True, enabled_as_of=datetime(2018, 1, 1))
site_config.save()
RequestCache.clear_all_namespaces()
# Check that the org value is not updated in cache by changing the site value
with self.assertNumQueries(0):
self.assertFalse(ContentTypeGatingConfig.current(course_key=course.id).enabled)
org_config = ContentTypeGatingConfig(org=course.org, enabled=True, enabled_as_of=datetime(2018, 1, 1))
org_config.save()
RequestCache.clear_all_namespaces()
# Check that the org value is not updated in cache by changing the site value
with self.assertNumQueries(0):
self.assertFalse(ContentTypeGatingConfig.current(course_key=course.id).enabled)