/usr/share/pyshared/pycountry/db.py is in python-pycountry 0.14.1+ds1-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | # vim:fileencoding=utf-8
# Copyright (c) 2008 gocept gmbh & co. kg
# See also LICENSE.txt
# $Id$
"""Generic database code."""
import logging
from xml.dom import minidom
# NullHandler is only defined for python >= 2.7
if 'NullHandler' not in dir(logging):
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.NullHandler = NullHandler
logger = logging.getLogger('pycountry.db')
# Prevent warning, see
# http://docs.python.org/library/logging.html#configuring-logging-for-a-library
logger.addHandler(logging.NullHandler())
class Data(object):
def __init__(self, element, **kw):
self._element = element
for key, value in kw.items():
setattr(self, key, value)
class Database(object):
# Override those names in sub-classes for specific ISO database.
field_map = dict()
data_class_base = Data
data_class_name = None
xml_tag = None
no_index = []
def __init__(self, filename):
self.objects = []
self.indices = {}
self.data_class = type(self.data_class_name, (self.data_class_base,),
{})
f = open(filename, 'rb')
tree = minidom.parse(f)
for entry in tree.getElementsByTagName(self.xml_tag):
mapped_data = {}
for key in entry.attributes.keys():
mapped_data[self.field_map[key]] = (
entry.attributes.get(key).value)
entry_obj = self.data_class(entry, **mapped_data)
self.objects.append(entry_obj)
# Construct list of indices: primary single-column indices
indices = []
for key in self.field_map.values():
if key in self.no_index:
continue
# Slightly horrible hack: to evaluate `key` at definition time of
# the lambda I pass it as a keyword argument.
getter = lambda x, key=key: getattr(x, key, None)
indices.append((key, getter))
# Create indices
for name, _ in indices:
self.indices[name] = {}
# Update indices
for obj in self.objects:
for name, rule in indices:
value = rule(obj)
if value is None:
continue
if value in self.indices[name]:
logger.error(
'%s %r already taken in index %r and will be '
'ignored. This is an error in the XML databases.' %
(self.data_class_name, value, name))
self.indices[name][value] = obj
def __iter__(self):
return iter(self.objects)
def __len__(self):
return len(self.objects)
def get(self, **kw):
assert len(kw) == 1, 'Only one criteria may be given.'
field, value = kw.items()[0]
return self.indices[field][value]
|