def gpg_keyring(self, init=True, hostname=None, **kwargs): """Context manager that yields a temporary GPG keyring. To avoid any locking issues and to isolate the GPG keys for users, every operation that interacts with gpg (and thus uses the keyring) is with a separate, temporary keyring that is created specifically for the operations. Example:: user = User.objects.get(username='******') with user.gpg_keyring() as backend: backend.import_key(...) Parameters ---------- init : bool, optional If ``False``, do not import existing (valid) keys into the keyring. hostname : str, optional If set, also import the private key for the given host configured in the ``XMPP_HOSTS`` setting. """ if hostname is not None: host_fp, host_key, host_pub = load_private_key(hostname) with gpg_backend.temp_keyring(**kwargs) as backend: if init is True: # import existing valid gpg keys for key in self.gpg_keys.valid(): backend.import_key(key.key.encode('utf-8')) if hostname is not None: backend.import_private_key(host_key) backend.import_key(host_pub) yield backend