From: Simon Cross Date: Sat, 17 May 2014 14:47:10 +0000 (+0200) Subject: Add direct yaml and json support to resources. X-Git-Tag: 0.1~96^2~2 X-Git-Url: https://git.ctpug.org.za/?a=commitdiff_plain;ds=sidebyside;h=751c25c3684b8e634c9b804f384950fa4c6d1768;p=naja.git Add direct yaml and json support to resources. --- diff --git a/naja/resources/__init__.py b/naja/resources/__init__.py index 191cbd4..b080786 100644 --- a/naja/resources/__init__.py +++ b/naja/resources/__init__.py @@ -1,3 +1,5 @@ -from naja.resources.loader import Loader +from naja.resources.loader import Loader, ResourceNotFound + +__all__ = ['resources', 'ResourceNotFound'] resources = Loader('data') diff --git a/naja/resources/loader.py b/naja/resources/loader.py index 28a3c7a..69eff2f 100644 --- a/naja/resources/loader.py +++ b/naja/resources/loader.py @@ -1,5 +1,6 @@ import os import sys +import json try: from pkg_resources import resource_filename @@ -11,6 +12,12 @@ except ImportError: # time going down this rabbithole already return os.path.join(os.path.dirname(__file__), '..', '..', 'data', path) + +try: + import yaml +except ImportError: + yaml = None + import pygame @@ -99,3 +106,15 @@ class Loader(object): self._cache[key] = pygame.font.Font(fn, font_size) return self._cache[key] + + def get_yaml(self, *path_fragments): + if yaml is None: + raise ResourceNotFound("%s - %s" % ( + os.path.join(*path_fragments), + "YAML module not available")) + with self.get_file(*path_fragments) as yaml_file: + return yaml.safe_load(yaml_file) + + def get_json(self, *path_fragments): + with self.get_file(*path_fragments) as json_file: + return json.load(json_file)