Skip to content

fl_server_api.serializers.user

Classes:

Name Description
UserSerializer

A serializer for the User model.

Classes

UserSerializer

Bases: ModelSerializer


              flowchart TD
              fl_server_api.serializers.user.UserSerializer[UserSerializer]

              

              click fl_server_api.serializers.user.UserSerializer href "" "fl_server_api.serializers.user.UserSerializer"
            

A serializer for the User model.

This serializer includes a method field for the user's token, which is only included in the serialized data if the request user is the same as the requested user.

Classes:

Name Description
Meta

Methods:

Name Description
create

Create a new User instance.

get_token

Get the user's token.

to_representation

Generate a dictionary representation of the User instance.

Attributes:

Name Type Description
token

A method field for the user's token.

Source code in fl_server_api/serializers/user.py
class UserSerializer(serializers.ModelSerializer):
    """
    A serializer for the User model.

    This serializer includes a method field for the user's token,
    which is only included in the serialized data if the
    request user is the same as the requested user.
    """

    token = serializers.SerializerMethodField()
    """A method field for the user's token."""

    class Meta:
        model = User
        fields = [
            "username", "first_name", "last_name",
            "email", "id", "actor", "client",
            "message_endpoint", "token", "password",
        ]
        extra_kwargs = {
            "id": {"read_only": True},
            "token": {"read_only": True},
            "password": {"write_only": True},
        }

    def get_token(self, user: User) -> str | None:
        """
        Get the user's token.

        The token is only returned if the request user is the same as the requested user.
        The request user ID is passed in the context.

        Args:
            user (User): The user instance.

        Returns:
            str | None: The user's token, or "**********" if the request user is not the same as the requested user.
        """
        if self.context.get("request_user_id") == user.id:
            return Token.objects.get(user=user).key
        return "**********"

    def to_representation(self, instance):
        """
        Generate a dictionary representation of the User instance.

        The token key is removed from the response if the request user is not the same as the requested user.

        Args:
            instance (User): The User instance.

        Returns:
            dict: The dictionary representation of the User instance.
        """
        # remove the token key from the response if the request user is not the same as
        # the requested user since its always empty or "**********"
        data = super().to_representation(instance)
        if data.get("token") == "**********":
            del data["token"]
        return data

    def create(self, validated_data):
        """
        Create a new User instance.

        The user's password is set using the `set_password` method.

        Args:
            validated_data (dict): The validated data for the new User instance.

        Returns:
            User: The created User instance.
        """
        user = User.objects.create(**validated_data)
        user.set_password(validated_data["password"])
        user.save()
        return user

Attributes

token class-attribute instance-attribute
token = SerializerMethodField()

A method field for the user's token.

Classes

Meta

Attributes:

Name Type Description
extra_kwargs
fields
model
Source code in fl_server_api/serializers/user.py
class Meta:
    model = User
    fields = [
        "username", "first_name", "last_name",
        "email", "id", "actor", "client",
        "message_endpoint", "token", "password",
    ]
    extra_kwargs = {
        "id": {"read_only": True},
        "token": {"read_only": True},
        "password": {"write_only": True},
    }
Attributes
extra_kwargs class-attribute instance-attribute
extra_kwargs = {'id': {'read_only': True}, 'token': {'read_only': True}, 'password': {'write_only': True}}
fields class-attribute instance-attribute
fields = ['username', 'first_name', 'last_name', 'email', 'id', 'actor', 'client', 'message_endpoint', 'token', 'password']
model class-attribute instance-attribute
model = User

Functions

create

Create a new User instance.

The user's password is set using the set_password method.

Parameters:

Name Type Description Default
validated_data
dict

The validated data for the new User instance.

required

Returns:

Name Type Description
User

The created User instance.

Source code in fl_server_api/serializers/user.py
def create(self, validated_data):
    """
    Create a new User instance.

    The user's password is set using the `set_password` method.

    Args:
        validated_data (dict): The validated data for the new User instance.

    Returns:
        User: The created User instance.
    """
    user = User.objects.create(**validated_data)
    user.set_password(validated_data["password"])
    user.save()
    return user
get_token
get_token(user: User) -> str | None

Get the user's token.

The token is only returned if the request user is the same as the requested user. The request user ID is passed in the context.

Parameters:

Name Type Description Default
user
User

The user instance.

required

Returns:

Type Description
str | None

str | None: The user's token, or "****" if the request user is not the same as the requested user.

Source code in fl_server_api/serializers/user.py
def get_token(self, user: User) -> str | None:
    """
    Get the user's token.

    The token is only returned if the request user is the same as the requested user.
    The request user ID is passed in the context.

    Args:
        user (User): The user instance.

    Returns:
        str | None: The user's token, or "**********" if the request user is not the same as the requested user.
    """
    if self.context.get("request_user_id") == user.id:
        return Token.objects.get(user=user).key
    return "**********"
to_representation
to_representation(instance)

Generate a dictionary representation of the User instance.

The token key is removed from the response if the request user is not the same as the requested user.

Parameters:

Name Type Description Default
instance
User

The User instance.

required

Returns:

Name Type Description
dict

The dictionary representation of the User instance.

Source code in fl_server_api/serializers/user.py
def to_representation(self, instance):
    """
    Generate a dictionary representation of the User instance.

    The token key is removed from the response if the request user is not the same as the requested user.

    Args:
        instance (User): The User instance.

    Returns:
        dict: The dictionary representation of the User instance.
    """
    # remove the token key from the response if the request user is not the same as
    # the requested user since its always empty or "**********"
    data = super().to_representation(instance)
    if data.get("token") == "**********":
        del data["token"]
    return data