How do I access student data from within an XBlock?

Suppose an XBlock author wants to find out information about the user that's viewing/interacting with an XBlock. How?

Some basic information about the user is available via the user runtime service that Stanford contributed. From within your XBlock's code, first decorate your XBlock class with @XBlock.wants('user') and then do:

user_service = self.runtime.service(self, 'user')
xb_user = user_service.get_current_user()

After that, you can look at some basic info:


Note that emails is a list, even though the edx-platform only currently puts one email address in it at this time.

It's important to remember that the user returned is *not* a Django User object. The code for the XBlockUser that gets returned is here:

The code for where the LMS creates an XBlockUser is here:

If you're running the XBlock on edx-platform, there are some optional attributes that also get set:


These are not guaranteed to be there, so you should always access them like:


And handle the case where that will return None.

If you want to attach user data to your XBlock that is not tied to a particular piece of content, you'll want one of the lesser used field scopes. For example, if you wanted to get the user's name and have a banner in the XBlock say "Hello, <name>", you'd probably want to declare a String field "favorite_color" with a scope of Scope.user_info. Keep in mind that this value will only be accessible from your own XBlock. It will not be accessible from other XBlocks via the user service (though that is an interesting possibility for future extension).