[docs]classCommand(RunServerPlusCommand):"""Custom runserver_plus command that stores the TLS certificate to the database."""
[docs]defstore_tls_certificate(self,cert_file_path,key_file_path):"""Fetch or create the TLS certificate and key from the database."""ifnotos.path.exists(cert_file_path)ornotos.path.exists(key_file_path):print(f'Certificate or key file not found: {cert_file_path}, {key_file_path}')active_credential=ActiveTrustpointTlsServerCredentialModel.objects.first()ifactive_credentialandactive_credential.credential:print('Active TLS credential already exists in the database.')returnNone,Nonewithopen(cert_file_path,'rb')ascert_file:cert_pem=cert_file.read()certificate_serializer=CertificateSerializer.from_pem(cert_pem)withopen(key_file_path)askey_file:key_pem=key_file.read()key_serializer=PrivateKeySerializer.from_pem(key_pem)tls_server_credential_serializer=CredentialSerializer.from_serializers(private_key_serializer=key_serializer,certificate_serializer=certificate_serializer,)trustpoint_tls_server_credential=CredentialModel.save_credential_serializer(credential_serializer=tls_server_credential_serializer,credential_type=CredentialModel.CredentialTypeChoice.TRUSTPOINT_TLS_SERVER,)active_tls,_=ActiveTrustpointTlsServerCredentialModel.objects.get_or_create(id=1)active_tls.credential=trustpoint_tls_server_credentialactive_tls.save()print('Updated ActiveTrustpointTlsServerCredentialModel.')returncert_file_path,key_file_path
[docs]defhandle(self,*args,**options):"""Main command execution logic."""cert_file=options.get('cert_path')key_file=options.get('key_file_path')ifcert_fileandkey_file:self.store_tls_certificate(cert_file,key_file)# Call the original runserver_plus commandsuper().handle(*args,**options)