Created
June 10, 2016 10:21
-
-
Save kezabelle/f33b706957f7843d301d4ebcc9acde37 to your computer and use it in GitHub Desktop.
how one might "get" a bunch of related files given a single file node, based on the original filepath.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os, codecs, functools | |
from collections import namedtuple | |
from django.template.loader import get_template | |
from django.template import TemplateDoesNotExist | |
MISSING = object() | |
def django_handler(path): | |
try: | |
return get_template(path) | |
except TemplateDoesNotExist: | |
return MISSING | |
def open_handler(path, encoding="ascii"): | |
try: | |
with codecs.open(path, mode='r', encoding=encoding) as f: | |
return f.read() | |
except IOError: | |
return MISSING | |
utf8_open_handler = functools.partial(open_handler, encoding="utf-8") | |
FoundRelated = namedtuple('FoundRelated', 'parent child result') | |
def getrelated(filename, handler, extensions, swallow_parent_exceptions=False, swallow_child_exceptions=False): | |
data = handler(filename) | |
if data is not MISSING: | |
yield FoundRelated(parent=filename, child=filename, result=data) | |
else: | |
if swallow_parent_exceptions is False: | |
raise ValueError(u"'{fname}' does not exist".format(fname=filename)) | |
original_path, original_extention = os.path.splitext(filename) | |
for index, looking_extension in enumerate(extensions): | |
path = u'{fname}.{selector}'.format(fname=original_path, selector=looking_extension) | |
data = handler(path) | |
if data is not MISSING: | |
yield FoundRelated(parent=filename, child=path, result=data) | |
else: | |
if swallow_child_exceptions is False: | |
raise ValueError(u"'{fname}' does not exist".format(fname=path)) | |
getrelated_no_exceptions = functools.partial(getrelated, swallow_parent_exceptions=True, swallow_child_exceptions=True) | |
getrelated_with_exceptions = functools.partial(getrelated, swallow_parent_exceptions=False, swallow_child_exceptions=False) | |
""" | |
Example usage: | |
tuple(getrelated_with_exceptions("lol.txt", open_handler, ['json', 'yaml'])) | |
tuple(getrelated_with_exceptions("lol.txt", utf8_open_handler, ['json', 'yaml'])) | |
tuple(getrelated_no_exceptions("lol.txt", open_handler, ['json', 'yaml'])) | |
tuple(getrelated_no_exceptions("lol.txt", utf8_open_handler, ['json', 'yaml'])) | |
tuple(getrelated("base.html", django_handler, ['json'])) | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample utf8 file which should work: https://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-demo.txt