1
\$\begingroup\$

I built a small project using Django-Rest-Framework. Please comment on the best practice style for the code below, which will make it simpler.

class LoginSerializer(serializers.Serializer):
    phone = serializers.CharField()
    password = serializers.CharField()

    def validate(self, data):
        phone = data.get("phone", "")
        password = data.get("password", "")
        # need simplify the structure below
        if phone and password:
            user = authenticate(phone=phone, password=password)
            if user:
                if user.is_active:
                    data['user'] = user
                else:
                    raise exceptions.ValidationError('User is deactivated.')
            else:
                raise exceptions.ValidationError(
                    'Unable to login with given credentials.')
        else:
            raise exceptions.ValidationError(
                'Must provide username and password both.')
        return data

How I can make this more Pythonic?

\$\endgroup\$
1
\$\begingroup\$
  • Returning early makes code not follow the arrow anti-pattern. And makes the flow of the code simpler.
  • There's otherwise not much to comment on.
class LoginSerializer(serializers.Serializer):
    phone = serializers.CharField()
    password = serializers.CharField()

    def validate(self, data):
        phone = data.get("phone", "")
        password = data.get("password", "")
        # need simplify the structure below
        if not (phone and password):
            raise exceptions.ValidationError('Must provide username and password both.')

        user = authenticate(phone=phone, password=password)
        if not user:
            raise exceptions.ValidationError('Unable to login with given credentials.')

        if not user.is_active:
            raise exceptions.ValidationError('User is deactivated.')

        data['user'] = user
        return data
| improve this answer | |
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.