openedx.core.djangoapps.bookmarks package

Contents

openedx.core.djangoapps.bookmarks package#

Subpackages#

Submodules#

openedx.core.djangoapps.bookmarks.api module#

Bookmarks Python public API.

openedx.core.djangoapps.bookmarks.api_impl module#

Bookmarks Python API.

exception openedx.core.djangoapps.bookmarks.api_impl.BookmarksLimitReachedError#

Bases: Exception

if try to create new bookmark when max limit of bookmarks already reached

openedx.core.djangoapps.bookmarks.api_impl.can_create_more(data)#

Determine if a new Bookmark can be created for the course based on limit defined in django.conf.settings.MAX_BOOKMARKS_PER_COURSE

Parameters:

data (dict) – The data to create the object with.

Returns:

Boolean

openedx.core.djangoapps.bookmarks.api_impl.create_bookmark(user, usage_key)#

Create a bookmark.

Parameters:
  • user (User) – The user of the bookmark.

  • usage_key (UsageKey) – The usage_key of the bookmark.

Returns:

Dict.

Raises:
  • ItemNotFoundError – If no block exists for the usage_key.

  • BookmarksLimitReachedError – if try to create new bookmark when max limit of bookmarks already reached

openedx.core.djangoapps.bookmarks.api_impl.delete_bookmark(user, usage_key)#

Delete a bookmark.

Parameters:
  • user (User) – The user of the bookmark.

  • usage_key (UsageKey) – The usage_key of the bookmark.

Returns:

Dict.

Raises:

ObjectDoesNotExist – If a bookmark with the parameters does not exist.

openedx.core.djangoapps.bookmarks.api_impl.delete_bookmarks(usage_key)#

Delete all bookmarks for usage_key.

Parameters:

usage_key (UsageKey) – The usage_key of the bookmarks.

openedx.core.djangoapps.bookmarks.api_impl.get_bookmark(user, usage_key, fields=None)#

Return data for a bookmark.

Parameters:
  • user (User) – The user of the bookmark.

  • usage_key (UsageKey) – The usage_key of the bookmark.

  • fields (list) – List of field names the data should contain (optional).

Returns:

Dict.

Raises:

ObjectDoesNotExist – If a bookmark with the parameters does not exist.

openedx.core.djangoapps.bookmarks.api_impl.get_bookmarks(user, course_key=None, fields=None, serialized=True)#

Return data for bookmarks of a user.

Parameters:
  • user (User) – The user of the bookmarks.

  • course_key (CourseKey) – The course_key of the bookmarks (optional).

  • fields (list) – List of field names the data should contain (optional). N/A if serialized is False.

  • serialized (bool) – Whether to return a queryset or a serialized list of dicts. Default is True.

Returns:

List of dicts if serialized is True else queryset.

openedx.core.djangoapps.bookmarks.apps module#

Configuration for bookmarks Django app

class openedx.core.djangoapps.bookmarks.apps.BookmarksConfig(app_name, app_module)#

Bases: AppConfig

Configuration class for bookmarks Django app

name = 'openedx.core.djangoapps.bookmarks'#
plugin_app = {'settings_config': {'lms.djangoapp': {'common': {'relative_path': 'settings.common'}, 'production': {'relative_path': 'settings.production'}}}, 'url_config': {'lms.djangoapp': {'app_name': 'openedx.core.djangoapps.bookmarks', 'namespace': '', 'regex': '^api/bookmarks/', 'relative_path': 'urls'}}}#
ready()#

Override this method in subclasses to run code when Django starts.

verbose_name = 'Bookmarks'#

openedx.core.djangoapps.bookmarks.models module#

Models for Bookmarks.

class openedx.core.djangoapps.bookmarks.models.Bookmark(*args, **kwargs)#

Bases: TimeStampedModel

Bookmarks model.

exception DoesNotExist#

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned#

Bases: MultipleObjectsReturned

course_key#

DO NOT REUSE THIS CLASS. Provided for backwards compatibility only!

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

classmethod create(data)#

Create a Bookmark object.

Parameters:

data (dict) – The data to create the object with.

Returns:

A Bookmark object.

Raises:

ItemNotFoundError – If no block exists for the usage_key.

created#

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

property display_name#

Return the display_name from self.xblock_cache.

Returns:

String.

get_next_by_created(*, field=<model_utils.fields.AutoCreatedField: created>, is_next=True, **kwargs)#
get_next_by_modified(*, field=<model_utils.fields.AutoLastModifiedField: modified>, is_next=True, **kwargs)#
static get_path(usage_key)#

Returns data for the path to the block in the course graph.

Note: In case of multiple paths to the block from the course root, this function returns a path arbitrarily but consistently, depending on the modulestore. In the future, we may want to extend it to check which of the paths, the user has access to and return its data.

Parameters:

block (XBlock) – The block whose path is required.

Returns:

list of PathItems

get_previous_by_created(*, field=<model_utils.fields.AutoCreatedField: created>, is_next=False, **kwargs)#
get_previous_by_modified(*, field=<model_utils.fields.AutoLastModifiedField: modified>, is_next=False, **kwargs)#
id#

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

modified#

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

objects = <django.db.models.manager.Manager object>#
property path#

Return the path to the bookmark’s block after checking self.xblock_cache.

Returns:

List of dicts.

property resource_id#

{username,usage_id}.

Type:

Return the resource id

static updated_path(usage_key, xblock_cache)#

Return the update-to-date path.

xblock_cache.paths is the list of all possible paths to a block constructed by doing a DFS of the tree. However, in case of DAGS, which section jump_to_id() takes the user to depends on the modulestore. If xblock_cache.paths has only one item, we can just use it. Otherwise, we use path_to_location() to get the path jump_to_id() will take the user to.

usage_key#

DO NOT REUSE THIS CLASS. Provided for backwards compatibility only!

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

user#

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

user_id#
xblock_cache#

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

xblock_cache_id#
class openedx.core.djangoapps.bookmarks.models.XBlockCache(*args, **kwargs)#

Bases: TimeStampedModel

XBlockCache model to store info about xblocks.

exception DoesNotExist#

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned#

Bases: MultipleObjectsReturned

bookmark_set#

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

course_key#

DO NOT REUSE THIS CLASS. Provided for backwards compatibility only!

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

classmethod create(data)#

Create an XBlockCache object.

Parameters:

data (dict) – The data to create the object with.

Returns:

An XBlockCache object.

created#

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

display_name#

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

get_next_by_created(*, field=<model_utils.fields.AutoCreatedField: created>, is_next=True, **kwargs)#
get_next_by_modified(*, field=<model_utils.fields.AutoLastModifiedField: modified>, is_next=True, **kwargs)#
get_previous_by_created(*, field=<model_utils.fields.AutoCreatedField: created>, is_next=False, **kwargs)#
get_previous_by_modified(*, field=<model_utils.fields.AutoLastModifiedField: modified>, is_next=False, **kwargs)#
id#

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

modified#

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

objects = <django.db.models.manager.Manager object>#
property paths#

Return paths.

Returns:

list of list of PathItems.

usage_key#

DO NOT REUSE THIS CLASS. Provided for backwards compatibility only!

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

openedx.core.djangoapps.bookmarks.models.parse_path_data(path_data)#

Return a list of PathItems constructed from parsing path_data.

openedx.core.djangoapps.bookmarks.models.prepare_path_for_serialization(path)#

Return the data from a list of PathItems ready for serialization to json.

openedx.core.djangoapps.bookmarks.serializers module#

Serializers for Bookmarks.

class openedx.core.djangoapps.bookmarks.serializers.BookmarkSerializer(*args, **kwargs)#

Bases: ModelSerializer

Serializer for the Bookmark model.

class Meta#

Bases: object

Serializer metadata.

fields = ('id', 'course_id', 'usage_id', 'block_type', 'display_name', 'path', 'created')#
model#

alias of Bookmark

get_id(bookmark)#

Return the REST resource id: {username,usage_id}.

get_path(bookmark)#

Serialize and return the path data of the bookmark.

openedx.core.djangoapps.bookmarks.services module#

Bookmarks service.

class openedx.core.djangoapps.bookmarks.services.BookmarksService(user, **kwargs)#

Bases: object

A service that provides access to the bookmarks API.

When bookmarks() or is_bookmarked() is called for the first time, the service fetches and caches all the bookmarks of the user for the relevant course. So multiple calls to get bookmark status during a request (for, example when rendering courseware and getting bookmarks status for search results) will not cause repeated queries to the database.

bookmarks(course_key)#

Return a list of bookmarks for the course for the current user.

Parameters:

course_key – CourseKey of the course for which to retrieve the user’s bookmarks for.

Return type:

list of dict

is_bookmarked(usage_key)#

Return whether the block has been bookmarked by the user.

Parameters:

usage_key – UsageKey of the block.

Returns:

Bool

set_bookmarked(usage_key)#

Adds a bookmark for the block.

Parameters:

usage_key – UsageKey of the block.

Returns:

Bool indicating whether the bookmark was added.

unset_bookmarked(usage_key)#

Removes the bookmark for the block.

Parameters:

usage_key – UsageKey of the block.

Returns:

Bool indicating whether the bookmark was removed.

openedx.core.djangoapps.bookmarks.signals module#

Signals for bookmarks.

openedx.core.djangoapps.bookmarks.signals.trigger_update_xblocks_cache_task(sender, course_key, **kwargs)#

Trigger update_xblocks_cache() when course_published signal is fired.

openedx.core.djangoapps.bookmarks.tasks module#

Tasks for bookmarks.

openedx.core.djangoapps.bookmarks.tasks.paths_equal(paths_1, paths_2)#

Check if two paths are equivalent.

openedx.core.djangoapps.bookmarks.urls module#

URL routes for the bookmarks app.

openedx.core.djangoapps.bookmarks.views module#

HTTP end-points for the Bookmarks API.

For more information, see: https://openedx.atlassian.net/wiki/display/TNL/Bookmarks+API

class openedx.core.djangoapps.bookmarks.views.BookmarksDetailView(**kwargs)#

Bases: APIView, BookmarksViewMixin

Use Cases

Get or delete a specific bookmark for a user.

Example Requests:

GET /api/bookmarks/v1/bookmarks/{username},{usage_id}/?fields=display_name,path

DELETE /api/bookmarks/v1/bookmarks/{username},{usage_id}/

Response for GET

Users can only delete their own bookmarks. If the bookmark_id does not belong to a requesting user’s bookmark a Http404 is returned. Http404 will also be returned if the bookmark does not exist.

  • id: String. The identifier string for the bookmark: {user_id},{usage_id}.

  • course_id: String. The identifier string of the bookmark’s course.

  • usage_id: String. The identifier string of the bookmark’s XBlock.

  • display_name: (optional) String. Display name of the XBlock.

  • path: (optional) List of dicts containing {“usage_id”: <usage-id>, display_name: <display-name>}

    for the XBlocks from the top of the course tree till the parent of the bookmarked XBlock.

  • created: ISO 8601 String. The timestamp of bookmark’s creation.

Response for DELETE

Users can only delete their own bookmarks.

A successful delete returns a 204 and no content.

Users can only delete their own bookmarks. If the bookmark_id does not belong to a requesting user’s bookmark a 404 is returned. 404 will also be returned if the bookmark does not exist.

authentication_classes = (<class 'openedx.core.lib.api.authentication.BearerAuthentication'>, <class 'rest_framework.authentication.SessionAuthentication'>)#
delete(request, username=None, usage_id=None)#

DELETE /api/bookmarks/v1/bookmarks/{username},{usage_id}

get(request, username=None, usage_id=None)#

Get a specific bookmark for a user.

Example Requests

GET /api/bookmarks/v1/bookmarks/{username},{usage_id}?fields=display_name,path

get_usage_key_or_error_response(usage_id)#

Create and return usage_key or error Response.

Parameters:

usage_id (string) – The id of required block.

permission_classes = (<class 'rest_framework.permissions.IsAuthenticated'>, <class 'edx_rest_framework_extensions.permissions.IsUserInUrl'>)#
serializer_class#

alias of BookmarkSerializer

class openedx.core.djangoapps.bookmarks.views.BookmarksListView(**kwargs)#

Bases: ListCreateAPIView, BookmarksViewMixin

REST endpoints for lists of bookmarks.

authentication_classes = (<class 'openedx.core.lib.api.authentication.BearerAuthentication'>, <class 'rest_framework.authentication.SessionAuthentication'>)#
get(request, *args, **kwargs)#

Get a paginated list of bookmarks for a user.

The list can be filtered by passing parameter “course_id=<course_id>” to only include bookmarks from a particular course.

The bookmarks are always sorted in descending order by creation date.

Each page in the list contains 10 bookmarks by default. The page size can be altered by passing parameter “page_size=<page_size>”.

To include the optional fields pass the values in “fields” parameter as a comma separated list. Possible values are:

  • “display_name”

  • “path”

Example Requests

GET /api/bookmarks/v1/bookmarks/?course_id={course_id1}&fields=display_name,path

get_queryset()#

Returns queryset of bookmarks for GET requests.

The results will only include bookmarks for the request’s user. If the course_id is specified in the request parameters, the queryset will only include bookmarks from that course.

get_serializer_context()#

Return the context for the serializer.

paginate_queryset(queryset)#

Override GenericAPIView.paginate_queryset for the purpose of eventing

pagination_class#

alias of BookmarksPagination

permission_classes = (<class 'rest_framework.permissions.IsAuthenticated'>,)#
post(request, *unused_args, **unused_kwargs)#

Create a new bookmark for a user.

The POST request only needs to contain one parameter “usage_id”.

Http400 is returned if the format of the request is not correct, the usage_id is invalid or a block corresponding to the usage_id could not be found.

Example Requests

POST /api/bookmarks/v1/bookmarks/ Request data: {“usage_id”: <usage-id>}

serializer_class#

alias of BookmarkSerializer

class openedx.core.djangoapps.bookmarks.views.BookmarksPagination#

Bases: DefaultPagination

Paginator for bookmarks API.

get_paginated_response(data)#

Annotate the response with pagination information.

max_page_size = 100#
page_size = 10#
class openedx.core.djangoapps.bookmarks.views.BookmarksViewMixin#

Bases: object

Shared code for bookmarks views.

error_response(developer_message, user_message=None, error_status=400)#

Create and return a Response.

Parameters:
  • message (string) – The message to put in the developer_message and user_message fields.

  • status – The status of the response. Default is HTTP_400_BAD_REQUEST.

fields_to_return(params)#

Returns names of fields which should be included in the response.

Parameters:

params (dict) – The request parameters.

Module contents#

# pylint: disable=django-not-configured # pylint: disable=django-not-configured Bookmarks module.

class openedx.core.djangoapps.bookmarks.PathItem(usage_key, display_name)#

Bases: tuple

display_name#

Alias for field number 1

usage_key#

Alias for field number 0