Duplicate signals handlers for course content dates from edx-when

This commit is contained in:
Calen Pennington
2020-01-31 12:57:00 -05:00
parent 247cffa846
commit 019a97c084
5 changed files with 95 additions and 4 deletions

View File

@@ -0,0 +1,15 @@
"""
Django app configuration for openedx.core.djangoapps.course_dates_signals
"""
from django.apps import AppConfig
class CourseDatesSignalsConfig(AppConfig):
name = 'openedx.core.djangoapps.course_dates_signals'
def ready(self):
"""
Connect handlers to signals.
"""
from . import handlers # pylint: disable=unused-variable

View File

@@ -0,0 +1,75 @@
"""Signal handlers for writing course dates into edx_when."""
from __future__ import absolute_import, unicode_literals
import logging
from django.dispatch import receiver
from six import text_type
from xblock.fields import Scope
from xmodule.modulestore.django import SignalHandler, modulestore
from edx_when.api import FIELDS_TO_EXTRACT, set_dates_for_course
log = logging.getLogger(__name__)
def date_field_values(date_fields, xblock):
"""
Read field values for the specified date fields from the supplied xblock.
"""
result = {}
for field_name in date_fields:
if field_name not in xblock.fields:
continue
field = xblock.fields[field_name]
if field.scope == Scope.settings and field.is_set_on(xblock):
try:
result[field.name] = field.read_from(xblock)
except TypeError as exception:
exception_message = "{message}, Block-location:{location}, Field-name:{field_name}".format(
message=text_type(exception),
location=text_type(xblock.location),
field_name=field.name
)
raise TypeError(exception_message)
return result
def extract_dates_from_course(course):
"""
Extract all dates from the supplied course.
"""
log.info('Publishing course dates for %s', course.id)
if course.self_paced:
metadata = date_field_values(FIELDS_TO_EXTRACT, course)
# self-paced courses may accidentally have a course due date
metadata.pop('due', None)
date_items = [(course.location, metadata)]
else:
date_items = []
items = modulestore().get_items(course.id)
log.info('extracting dates from %d items in %s', len(items), course.id)
for item in items:
date_items.append((item.location, date_field_values(FIELDS_TO_EXTRACT, item)))
return date_items
@receiver(SignalHandler.course_published)
def extract_dates(sender, course_key, **kwargs): # pylint: disable=unused-argument
"""
Extract dates from blocks when publishing a course.
"""
log.info("Extracting dates from %s", course_key)
course = modulestore().get_course(course_key)
if not course:
log.info("No course found for key %s", course_key)
return
date_items = extract_dates_from_course(course)
try:
set_dates_for_course(course_key, date_items)
except Exception: # pylint: disable=broad-except
log.exception('setting dates for %s', course_key)