2021-01-01 23:25:23 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
2020-07-20 02:42:22 +00:00
|
|
|
|
2021-01-01 23:25:23 +00:00
|
|
|
from rest_framework import serializers
|
2020-07-20 02:42:22 +00:00
|
|
|
|
2022-05-10 09:28:10 +00:00
|
|
|
from common.utils import decrypt_password
|
2020-07-20 02:42:22 +00:00
|
|
|
|
2021-01-01 23:25:23 +00:00
|
|
|
__all__ = [
|
2022-05-07 08:20:12 +00:00
|
|
|
'ReadableHiddenField', 'EncryptedField'
|
2021-01-01 23:25:23 +00:00
|
|
|
]
|
|
|
|
|
|
|
|
|
|
|
|
# ReadableHiddenField
|
|
|
|
# -------------------
|
|
|
|
|
|
|
|
|
|
|
|
class ReadableHiddenField(serializers.HiddenField):
|
|
|
|
""" 可读的 HiddenField """
|
|
|
|
def __init__(self, **kwargs):
|
|
|
|
super().__init__(**kwargs)
|
|
|
|
self.write_only = False
|
|
|
|
|
|
|
|
def to_representation(self, value):
|
|
|
|
if hasattr(value, 'id'):
|
|
|
|
return getattr(value, 'id')
|
|
|
|
return value
|
2022-05-07 08:20:12 +00:00
|
|
|
|
|
|
|
|
|
|
|
class EncryptedField(serializers.CharField):
|
2022-05-17 11:34:15 +00:00
|
|
|
def __init__(self, write_only=None, **kwargs):
|
|
|
|
if write_only is None:
|
|
|
|
write_only = True
|
|
|
|
kwargs['write_only'] = write_only
|
2022-05-13 09:10:29 +00:00
|
|
|
super().__init__(**kwargs)
|
|
|
|
|
2022-05-07 08:20:12 +00:00
|
|
|
def to_internal_value(self, value):
|
|
|
|
value = super().to_internal_value(value)
|
2022-05-10 09:28:10 +00:00
|
|
|
return decrypt_password(value)
|