openedx.core.djangoapps.util package

Contents

openedx.core.djangoapps.util package#

Subpackages#

Submodules#

openedx.core.djangoapps.util.apps module#

Configuration for the openedx.core.djangoapps.util Django application

class openedx.core.djangoapps.util.apps.UtilConfig(app_name, app_module)#

Bases: AppConfig

Configuration class for the openedx.core.djangoapps.util Django application

label = 'open_edx_util'#
name = 'openedx.core.djangoapps.util'#
ready()#

Registers signal handlers at startup.

verbose_name = 'Open edX Utilities'#

openedx.core.djangoapps.util.checks module#

Miscellaneous system checks

openedx.core.djangoapps.util.checks.warn_if_devstack_settings(**kwargs)#

Raises a warning if we’re using any Devstack settings file.

openedx.core.djangoapps.util.forms module#

Custom forms-related types

class openedx.core.djangoapps.util.forms.ExtendedNullBooleanField(*, required=True, widget=None, label=None, initial=None, help_text='', error_messages=None, show_hidden_initial=False, validators=(), localize=False, disabled=False, label_suffix=None, template_name=None, bound_field_class=None)#

Bases: NullBooleanField

A field whose valid values are None, True, ‘True’, ‘true’, ‘1’, False, ‘False’, ‘false’ and ‘0’.

NULL_BOOLEAN_CHOICES = ((None, ''), (True, True), (True, 'True'), (True, 'true'), (True, '1'), (False, False), (False, 'False'), (False, 'false'), (False, '0'))#
to_python(value)#

Explicitly check for the string ‘True’ and ‘False’, which is what a hidden field will submit for True and False, for ‘true’ and ‘false’, which are likely to be returned by JavaScript serializations of forms, and for ‘1’ and ‘0’, which is what a RadioField will submit. Unlike the Booleanfield, this field must check for True because it doesn’t use the bool() function.

widget = <django.forms.widgets.Select object>#
class openedx.core.djangoapps.util.forms.MultiValueField(*, required=True, widget=None, label=None, initial=None, help_text='', error_messages=None, show_hidden_initial=False, validators=(), localize=False, disabled=False, label_suffix=None, template_name=None, bound_field_class=None)#

Bases: Field

Field class that supports a set of values for a single form field.

The field input can be specified as:
  1. a comma-separated-list (foo:bar1,bar2,bar3), or

  2. a repeated field in a MultiValueDict (foo:bar1, foo:bar2, foo:bar3)

  3. a combination of the above (foo:bar1,bar2, foo:bar3)

Note that there is currently no way to pass a value that includes a comma.

The resulting field value is a python set of the values as strings.

to_python(list_of_string_values)#

Convert the form input to a list of strings

validate(values)#

Ensure no empty values were passed

widget#

alias of MultipleHiddenInput

openedx.core.djangoapps.util.forms.to_bool(value)#

Explicitly checks for the string ‘True’, ‘False’, ‘true’, ‘false’, ‘1’ and ‘0’ and returns boolean True or False. Returns None if value is not passed at all and raises an exception for any other value.

openedx.core.djangoapps.util.maintenance_banner module#

View decorator to add a maintenance banner configured in settings.

openedx.core.djangoapps.util.maintenance_banner.add_maintenance_banner(func)#

View decorator to select where exactly the banner will appear

Add to function-based views like this:

from openedx.core.djangoapps.util.maintenance_banner import add_maintenance_banner

@add_maintenance_banner def my_view(request):

Add to class-based views using method_decorator:

from openedx.core.djangoapps.util.maintenance_banner import add_maintenance_banner from django.utils.decorators import method_decorator

@method_decorator(add_maintenance_banner, name=’dispatch’) class MyView(View):

openedx.core.djangoapps.util.model_utils module#

class openedx.core.djangoapps.util.model_utils.Creator(field)#

Bases: object

A placeholder class that provides a way to set the attribute on the model.

class openedx.core.djangoapps.util.model_utils.CreatorMixin#

Bases: object

Mixin class to provide SubfieldBase functionality to django fields. See: https://docs.djangoproject.com/en/1.11/releases/1.8/#subfieldbase

contribute_to_class(cls, name, *args, **kwargs)#
from_db_value(value, expression, connection)#

openedx.core.djangoapps.util.ratelimit module#

Code to get ip from request.

openedx.core.djangoapps.util.ratelimit.real_ip(group, request)#

Get a client IP suitable for use in rate-limiting.

To prevent evasion of rate-limiting, use the safest (rightmost) IP in the external IP chain.

(Intended to be called by django-ratelimit, hence the unused argument.)

openedx.core.djangoapps.util.ratelimit.request_data_email(group, request) str#

Return the the email data param if it exists, otherwise return a random id.

openedx.core.djangoapps.util.ratelimit.request_post_email(group, request) str#

Return the the email post param if it exists, otherwise return a random id.

If the request doesn’t have an email post body param, treat it as a unique key. This will probably mean that it will not get rate limited.

This ratelimit key function is meant to be used with the user_authn/views/login.py::login_user function. To rate-limit any first party auth. For 3rd party auth, there is separate rate limiting currently in place so we don’t do any rate limiting for that case here.

openedx.core.djangoapps.util.ratelimit.request_post_email_or_username(group, request) str#

Return the the email or email_or_username post param if it exists, otherwise return a random id.

If the request doesn’t have an email or email_or_username post body param, treat it as a unique key. This will probably mean that it will not get rate limited.

This ratelimit key function is meant to be used with the user_authn/views/login.py::login_user function. To rate-limit any first party auth. For 3rd party auth, there is separate rate limiting currently in place so we don’t do any rate limiting for that case here.

openedx.core.djangoapps.util.row_delete module#

Code to delete rows from a table within a Django mgmt command using best practices. Following lines show how to use delete_rows():

# Command to delete all rows from the student_historicalcourseenrollment table.

import logging

from openedx.core.djangoapps.util.row_delete import BaseDeletionCommand, delete_rows from common.djangoapps.student.models import CourseEnrollment

log = logging.getLogger(__name__)

class Command(BaseDeletionCommand):

# Example usage: ./manage.py lms –settings=devstack delete_historical_enrollment_data help = ‘Deletes all historical CourseEnrollment rows (in chunks).’

def handle(self, *args, **options):

# Deletes rows, chunking the deletes to avoid long table/row locks. chunk_size, sleep_between = super(Command, self).handle(*args, **options) delete_rows(

CourseEnrollment.objects, ‘student_historicalcourseenrollment’, ‘history_id’, chunk_size, sleep_between

)

class openedx.core.djangoapps.util.row_delete.BaseDeletionCommand(stdout=None, stderr=None, no_color=False, force_color=False)#

Bases: BaseCommand

Base command used to delete all rows from a table.

DEFAULT_CHUNK_SIZE = 10000#
DEFAULT_SLEEP_BETWEEN_DELETES = 0#
add_arguments(parser)#

Entry point for subclassed commands to add custom arguments.

handle(*args, **options)#

Deletes rows, chunking the deletes to avoid long table/row locks.

openedx.core.djangoapps.util.row_delete.delete_rows(model_mgr, table_name, primary_id_name, chunk_size, sleep_between)#

Deletes ALL rows from table, chunking the deletes to avoid long table/row locks.

Parameters:
  • model_mgr (django.db.models.manager.Manager) – Django ORM mgr for the table’s model.

  • table_name (str) – Name of table from which to delete all rows.

  • primary_id_name (str) – Name of primary ID autoincrement column from table.

  • chunk_size (int) – Number of rows to delete in each transaction.

  • sleep_between (float) – Number of seconds to sleep between transactions.

openedx.core.djangoapps.util.signals module#

Signal handler for exceptions.

openedx.core.djangoapps.util.signals.record_request_exception(sender, **kwargs)#

Logs the stack trace whenever an exception occurs in processing a request.

openedx.core.djangoapps.util.test_forms module#

Mixins for testing forms.

class openedx.core.djangoapps.util.test_forms.FormTestMixin#

Bases: object

A mixin for testing forms

assert_error(expected_field, expected_message)#

Create a form bound to self.form_data, assert its invalidity, and assert that its error dictionary contains one entry with the expected field and message

assert_field_value(field, expected_value)#

Create a form bound to self.form_data, assert its validity, and assert that the given field in the cleaned data has the expected value

assert_valid(expected_cleaned_data)#

Check that the form returns the expected data

get_form(expected_valid)#

Return a form bound to self.form_data, asserting its validity (or lack thereof) according to expected_valid

openedx.core.djangoapps.util.user_messages module#

Support for per-request messages to be shown to the user.

These utilities are based upon the Django message framework, and allow code to register messages to be shown to the user on their next page view. These messages are shown in a page banner which is supported on all pages that utilize the main.html template.

There are two common use cases:
  • register a message before rendering a view, in which case the message will be shown on the resulting page

  • register a message before posting or redirecting. In these situations the message will be shown on the subsequent page. This is typically used to show a success message to the use.

class openedx.core.djangoapps.util.user_messages.PageLevelMessages#

Bases: UserMessageCollection

This set of messages appears as top page level messages.

NAMESPACE = 'page_level_messages'#
classmethod get_message_html(body_html, title=None, dismissable=False, **kwargs)#

Returns the entire HTML snippet for the message.

classmethod get_namespace()#

Returns the namespace of the message collection.

classmethod user_messages(request)#

Returns outstanding user messages, along with any persistent site-wide messages.

class openedx.core.djangoapps.util.user_messages.UserMessage(type, message_html)#

Bases: object

Representation of a message to be shown to a user.

property css_class#

Returns the CSS class to be used on the message element.

property icon_class#

Returns the CSS icon class representing the message type.

class openedx.core.djangoapps.util.user_messages.UserMessageCollection#

Bases: object

A collection of messages to be shown to a user.

classmethod get_message_html(body_html, title=None, dismissable=False, **kwargs)#

Returns the entire HTML snippet for the message.

Classes that extend this base class can override the message styling by implementing their own version of this function. Messages that do not use a title can just pass the body_html.

abstractmethod classmethod get_namespace()#

Returns the namespace of the message collection.

The name is used to namespace the subset of django messages. For example, return ‘course_home_messages’.

classmethod register_error_message(request, message, **kwargs)#

Registers an error message to be shown to the user.

classmethod register_info_message(request, message, **kwargs)#

Registers an information message to be shown to the user.

classmethod register_success_message(request, message, **kwargs)#

Registers a success message to be shown to the user.

classmethod register_user_message(request, message_type, body_html, once_only=False, **kwargs)#

Register a message to be shown to the user in the next page.

Parameters:
  • message_type (UserMessageType) – the user message type

  • body_html (str) – body of the message in html format

  • title (str) – optional title for the message as plain text

  • dismissable (bool) – shows a dismiss button (defaults to no button)

  • once_only (bool) – show the message only once per request

classmethod register_warning_message(request, message, **kwargs)#

Registers a warning message to be shown to the user.

classmethod user_messages(request)#

Returns any outstanding user messages.

Note: this function also marks these messages as being complete so they won’t be returned in the next request.

class openedx.core.djangoapps.util.user_messages.UserMessageType(*values)#

Bases: Enum

An enumeration of the types of user messages.

ERROR = 40#
INFO = 20#
SUCCESS = 25#
WARNING = 30#

openedx.core.djangoapps.util.user_utils module#

Custom user-related utility code.

class openedx.core.djangoapps.util.user_utils.SystemUser#

Bases: AnonymousUser

A User that can act on behalf of system actions, when a user object is needed, but no real user exists.

Like the AnonymousUser, this User is not represented in the database, and has no primary key.

openedx.core.djangoapps.util.waffle module#

Waffle flags and switches

Module contents#