From 1479f92ab66e2527e8d6e98a6edce3b01cc7f45a Mon Sep 17 00:00:00 2001 From: Joshua Harlow Date: Thu, 25 Jun 2015 17:09:10 -0700 Subject: [PATCH] Expose api response properties and cache buffer decoding Change-Id: I1e47be192eade575d2954d57991c0dd6d25e47d1 --- cloudinit/sources/base.py | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/cloudinit/sources/base.py b/cloudinit/sources/base.py index 0872ee13..3de21900 100644 --- a/cloudinit/sources/base.py +++ b/cloudinit/sources/base.py @@ -13,15 +13,26 @@ class APIResponse(object): To access the content in the binary format, use the `buffer` attribute, while the unicode content can be - accessed by calling `str` over this. + accessed by calling `str` over this (or by accessing + the `decoded_buffer` property). """ def __init__(self, buffer, encoding="utf-8"): self.buffer = buffer - self._encoding = encoding + self.encoding = encoding + self._decoded_buffer = None + + @property + def decoded_buffer(self): + # Avoid computing this again and again (although multiple threads + # may decode it if they all get in here at the same time, but meh + # thats ok). + if self._decoded_buffer is None: + self._decoded_buffer = self.buffer.decode(self.encoding) + return self._decoded_buffer def __str__(self): - return self.buffer.decode(self._encoding) + return self.decoded_buffer @six.add_metaclass(abc.ABCMeta)