contexts.py 1.47 KB
Newer Older
1
"""Generates common contexts"""
Gabe Mulley committed
2
import logging
3

4
from opaque_keys.edx.locations import SlashSeparatedCourseKey
5
from opaque_keys.edx.keys import CourseKey
6
from opaque_keys import InvalidKeyError
7
from util.request import COURSE_REGEX
8

Gabe Mulley committed
9
log = logging.getLogger(__name__)
10 11 12 13


def course_context_from_url(url):
    """
14
    Extracts the course_context from the given `url` and passes it on to
Gabe Mulley committed
15 16 17 18 19
    `course_context_from_course_id()`.
    """
    url = url or ''

    match = COURSE_REGEX.match(url)
20
    course_id = None
Gabe Mulley committed
21
    if match:
22 23 24 25 26 27 28 29 30 31
        course_id_string = match.group('course_id')
        try:
            course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id_string)
        except InvalidKeyError:
            log.warning(
                'unable to parse course_id "{course_id}"'.format(
                    course_id=course_id_string
                ),
                exc_info=True
            )
Gabe Mulley committed
32 33 34 35 36 37 38

    return course_context_from_course_id(course_id)


def course_context_from_course_id(course_id):
    """
    Creates a course context from a `course_id`.
39 40 41 42 43 44 45 46 47

    Example Returned Context::

        {
            'course_id': 'org/course/run',
            'org_id': 'org'
        }

    """
48 49 50 51
    if course_id is None:
        return {'course_id': '', 'org_id': ''}

    # TODO: Make this accept any CourseKey, and serialize it using .to_string
52
    assert isinstance(course_id, CourseKey)
53 54 55
    return {
        'course_id': course_id.to_deprecated_string(),
        'org_id': course_id.org,
56
    }