Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

serializers.py 2.2 KiB

8 anni fa
8 anni fa
8 anni fa
8 anni fa
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import json
  2. from api import models
  3. from rest_framework import serializers
  4. from django.utils.translation import ugettext_lazy as _
  5. class JsonSettingsField(serializers.Field):
  6. default_error_messages = {
  7. 'invalid': _('Value must be valid JSON.')
  8. }
  9. def to_representation(self, value):
  10. return json.loads(value)
  11. def to_internal_value(self, data):
  12. try:
  13. return json.dumps(data)
  14. except (TypeError, ValueError):
  15. self.fail('invalid')
  16. class PasswordInfoSerializer(serializers.ModelSerializer):
  17. settings = JsonSettingsField()
  18. class Meta:
  19. model = models.PasswordInfo
  20. fields = ('counter', 'settings', 'length')
  21. class EntrySerializer(serializers.ModelSerializer):
  22. site = serializers.CharField(allow_blank=True)
  23. login = serializers.CharField(allow_blank=True)
  24. password = PasswordInfoSerializer()
  25. class Meta:
  26. model = models.Entry
  27. fields = ('id', 'site', 'login', 'password', 'created', 'modified')
  28. read_only_fields = ('created', 'modified')
  29. def create(self, validated_data):
  30. password_data = validated_data.pop('password')
  31. user = self.context['request'].user
  32. password_info = models.PasswordInfo.objects.create(**password_data)
  33. return models.Entry.objects.create(user=user, password=password_info, **validated_data)
  34. def update(self, instance, validated_data):
  35. password_data = validated_data.pop('password')
  36. password_info = instance.password
  37. for attr, value in password_data.items():
  38. setattr(password_info, attr, value)
  39. password_info.save()
  40. for attr, value in validated_data.items():
  41. setattr(instance, attr, value)
  42. instance.save()
  43. return instance
  44. class PasswordSerializer(serializers.ModelSerializer):
  45. class Meta:
  46. model = models.Password
  47. fields = ('id', 'login', 'site', 'lowercase', 'uppercase', 'symbols', 'numbers', 'counter', 'length',
  48. 'created', 'modified')
  49. read_only_fields = ('created', 'modified')
  50. def create(self, validated_data):
  51. user = self.context['request'].user
  52. return models.Password.objects.create(user=user, **validated_data)