def _main(): api = CertificatesAPI() # Create a new developer certificate print("Creating new developer certificate...") certificate = {"name": "my_dev_certificate"} new_certificate = api.add_developer_certificate(**certificate) print("Successfully created developer certificate with id: %r" % new_certificate.id) # Update certificate updated_certificate = api.update_certificate( new_certificate.id, description="my updated certificate") # Delete the certificate print("Attempting to delete certificate...") api.delete_certificate(updated_certificate.id) print("Successfully deleted certificate (ID: %r)" % updated_certificate.id)
class DevCredentialsAPI: """API to manage developer certificate creation. Wrap the CertificatesAPI. Creates/gets and parses developer certificates. """ def __init__(self, api_key): """Initialise the API.""" self._cert_api = CertificatesAPI(dict(api_key=api_key)) @property def existing_cert_names(self): """List all existing certificate names known to the Pelion account.""" return [ self._cert_api.get_certificate(c.id).name for c in self._cert_api.list_certificates() ] def get_dev_credentials(self, name): """Get an existing developer certificate from Pelion. Return a credentials object. :param str name: name of the developer certificate to create. """ for cert in self._cert_api.list_certificates(): this_cert = self._cert_api.get_certificate(cert.id) if this_cert.name == name: return _parse_cert_header( this_cert.header_file, "#include <inttypes.h>", "MBED_CLOUD_DEV_", ) raise ValueError( "The developer certificate does not exist. " "Available certificates: \n{}".format( "\n".join(self.existing_cert_names) ) ) def create_dev_credentials(self, name): """Create a new developer certificate and return a credentials object. :param str name: name of the developer certificate to create. """ try: cert = self._cert_api.add_developer_certificate(name=name) return _parse_cert_header( cert.header_file, "#include <inttypes.h>", "MBED_CLOUD_DEV_" ) except CloudApiException as err: if err.reason != "Conflict": raise raise ValueError( "The developer certificate you are trying to create " "already exists in the Pelion Device Management Portal." ) def delete_developer_certificate(self, name): """Delete an existing developer certificate from device management.""" for cert in self._cert_api.list_certificates(): if cert.name == name: self._cert_api.delete_certificate(cert.id) return raise ValueError( "Certificate '{}' was not found in Device Management.".format(name) )