class Metrics(object): exposed = True namespace = 'metrics' def __init__(self): self.cache = Cache() @mimetype('text/json') def GET(self, key=None): result = self.cache.getset(self.get_namespace(), self.all()) return utils.dump_json(result) def all(self): return {} def get_namespace(self): return self.__class__.namespace
def __init__(self): self.mresource = self.__class__.mresource self.resource_name = self.__class__.__name__.lower() self.cache = Cache()
def __init__(self): self.cache = Cache()
class Resource(object): exposed = True mresource = None aggregate = False def __init__(self): self.mresource = self.__class__.mresource self.resource_name = self.__class__.__name__.lower() self.cache = Cache() def GET(self, id=None): if id == None: res = self.all() else: res = self.find(id) return self._dumpjson(res) def POST(self, *args, **kwargs): try: res = self._build_resource(kwargs).create() return self._dumpjson(res) except ValidationException as e: raise cherrypy.HTTPError(400, str(e)) def PUT(self, *args, **kwargs): res = self.find(id) if res == None: self._raise_not_found() else: return self._dumpjson(res.update(kwargs)) def DELETE(self, id): res = self.find(id) if res == None: self._raise_not_found() else: return self._dumpjson(res.destroy()) def all(self, *args, **kwargs): # Wrap in a lambda for lazy loading m = lambda: [ self._after_load(r.to_dict()) for r in self._all(*args, **kwargs) ] return self.cache.getset(self.resource_name, m) # Because resources are restricted to the # account level, we have to iterate over # all the available api keys and collect the results def aggregate(self): access_key = mixcoatl_settings.access_key secret_key = mixcoatl_settings.secret_key for pair in api_keys: mixcoatl_settings.set_access_key(pair['access_key']) mixcoatl_settings.set_secret_key(pair['secret_key']) for res in self.mresource.all(): yield res mixcoatl_settings.set_access_key(access_key) mixcoatl_settings.set_secret_key(secret_key) def find(self, id): res = self.mresource(id) res.load() if res == None: return res else: return self._after_load(res.to_dict()) def _all(self): return self.mresource.all() def _after_load(self, res): return res def _build_resource(self, attrs): res = self.mresource() for key in attrs.keys(): setattr(res, key, attrs[key]) return res def _dumpjson(self, result): return utils.dump_json(result) def _raise_not_found(self, id=None): raise cherrypy.HTTPError(404, "Could not find resource with id %s" % id)