FromCSVTablesGenerator.load_*() now accepts both path to file and file object as argument

This commit is contained in:
Yaroslav Klyuyev 2015-02-16 21:02:28 +02:00
parent 482074fcaf
commit 16ef6d19c3
2 changed files with 16 additions and 6 deletions

View file

@ -9,10 +9,11 @@ from collections import Iterable
import unicodecsv
# pynames:
from pynames.relations import GENDER, LANGUAGE, LANGUAGE_FORMS_LANGTH
from pynames.names import Name
from pynames.base import BaseGenerator
from pynames import exceptions
from pynames.base import BaseGenerator
from pynames.names import Name
from pynames.relations import GENDER, LANGUAGE, LANGUAGE_FORMS_LANGTH
from pynames.utils import is_file
class Template(object):
@ -236,7 +237,7 @@ class FromCSVTablesGenerator(FromTablesGenerator):
self.full_forms_for_languages = set()
def load_settings(self, settings_source):
with open(settings_source) as settings_file:
with (settings_source if is_file(settings_source) else open(settings_source)) as settings_file:
reader = unicodecsv.DictReader(settings_file, encoding='utf-8')
for row in reader:
new_native_language = row.get('native_language', '').strip()
@ -257,7 +258,7 @@ class FromCSVTablesGenerator(FromTablesGenerator):
def load_templates(self, templates_source):
template_slugs = []
with open(templates_source) as templates_file:
with (templates_source if is_file(templates_source) else open(templates_source)) as templates_file:
reader = unicodecsv.DictReader(templates_file, encoding='utf-8')
for row in reader:
template_data = {
@ -274,7 +275,7 @@ class FromCSVTablesGenerator(FromTablesGenerator):
return template_slugs
def load_tables(self, tables_source):
with open(tables_source) as tables_file:
with (tables_source if is_file(tables_source) else open(tables_source)) as tables_file:
reader = unicodecsv.DictReader(tables_file, encoding='utf-8')
slugs = set([fieldname.split(':')[0] for fieldname in reader.fieldnames])
for slug in slugs:

View file

@ -41,3 +41,12 @@ def get_all_generators():
generators.append(generator)
return generators
def is_file(obj):
"""Retrun True is object has 'next', '__enter__' and '__exit__' methods.
Suitable to check both builtin ``file`` and ``django.core.file.File`` instances.
"""
return all([callable(getattr(obj, method_name, None)) for method_name in ('next', '__enter__', '__exit__')])