Hello everyone,
I want to decrypt the patient id value in SampleSerializer. But I don’t know how to do this. Can you help me? Thank you in advance.
views.py
> class SamplesViewSet(viewsets.ModelViewSet):
> queryset = Samples.objects.all().order_by('id')
> serializer_class = SamplesSerializer
encrypt_util.py
> from cryptography.fernet import Fernet
> import base64
> import logging
> import traceback
> from django.conf import settings
>
> def encrypt(pas):
> try:
> pas = str(pas)
> cipher_pass = Fernet(settings.ENCRYPT_KEY)
> encrypt_pass = cipher_pass.encrypt(pas.encode('ascii'))
> encrypt_pass = base64.urlsafe_b64encode(encrypt_pass).decode("ascii")
> return encrypt_pass
> except Exception as e:
> logging.getLogger("error_logger").error(traceback.format_exc())
> return None
>
> def decrypt(pas):
> try:
> pas = base64.urlsafe_b64decode(pas)
> cipher_pass = Fernet(settings.ENCRYPT_KEY)
> decod_pass = cipher_pass.decrypt(pas).decode("ascii")
> return decod_pass
> except Exception as e:
> logging.getLogger("error_logger").error(traceback.format_exc())
> return None
EDIT
I edited the views.py but now it gives me an error:
*return serializer_class(*args, *kwargs)
TypeError: ‘dict’ object is not callable
> class SamplesViewSet(viewsets.ModelViewSet):
>
> queryset = Samples.objects.all().order_by('id')
> serializer = SamplesSerializer(queryset, many=True)
> for i in range(0, len(serializer.data)):
> serializer.data[i]['patientid']['patientid'] = decrypt(serializer.data[i]['patientid']['patientid'])
> response = {'data': serializer.data}
> serializer_class = response
I just want to decrypt the encrypted patientid field in the serializer and show it at datatable on the screen. Here, it is my serlializers.py:
from rest_framework import serializers
from App.models import Samples, Projects, Epi_data
class ProjectsSerializer(serializers.ModelSerializer):
class Meta:
model = Projects
fields = ['name', 'prefix', 'description']
class Epi_dataSerializer(serializers.ModelSerializer):
epi_data_hospitals = HospitalsSerializer(read_only=True)
class Meta:
model = Epi_data
fields = ['patientid', 'bday', 'age', 'gender', 'born_country', 'foreigner']
class SamplesSerializer(serializers.ModelSerializer):
projects = ProjectsSerializer(read_only=True)
patientid = Epi_dataSerializer(read_only=True)
class Meta:
model = Samples
fields = ['id', 'p_id_s', 'reception_date', 'hospital_date', 'culture', 'projects', 'patientid']
You may want to create a custom field class doing decryption/encryption in the to_representation/to_internal_value (or the inverse depending on where the data is encrypted or not).
See Serializer fields - Django REST framework
Then specifying the field explicitely on your serializer : see Serializers - Django REST framework