Exemplo n.º 1
0
    def lookup(cls, xref, code, language=None):
        DB.check_connection()
        
        if xref in cls._langcache:
            if code in cls._langcache[xref]:
                if language in cls._langcache[xref][code]:
                    return cls._langcache[xref][code][language]
        else:
            cls._langcache[xref] = {}
        
        if xref in cls._cache:
            if code in cls._cache[xref]:
                return  cls._cache[xref][code]
        else:
            cls._cache[xref] = {}
            
        projection = dict.fromkeys(Config.auth_heading_tags(), True)
        
        if language:
            for x in Config.get_language_tags():
                projection[x] = True
        
        auth = Auth.find_one({'_id': xref}, projection)
        value = auth.heading_value(code, language) if auth else '**Linked Auth Not Found**'
        
        if language is not None:
            if code not in cls._langcache[xref]:
                cls._langcache[xref][code] = {}
                
            cls._langcache[xref][code][language] = value
        else:
            cls._cache[xref][code] = value

        return value
Exemplo n.º 2
0
    def set(self, code, new_val, subfield_place=0, auth_control=True, auth_flag=False):
        subs = list(filter(lambda sub: sub.code == code, self.subfields))
        
        if auth_control == True and Config.is_authority_controlled(self.record_type, self.tag, code):
            try:
                new_val + int(new_val)
            except ValueError:
                raise Exception('Authority-controlled field {}${} must be set to an xref (integer)'.format(self.tag, code))
                
            auth_controlled = True
        elif auth_flag == True and Config.is_authority_controlled(self.record_type, self.tag, code):
            auth_tag = Config.authority_source_tag(self.record_type, self.tag, code)
            query = QueryDocument(Condition(tag=auth_tag, subfields={code: new_val}))
            authset = AuthSet.from_query(query)
            
            if authset.count == 0:
                raise Exception('Authority-controlled field {}${} value "{}" is invalid'.format(self.tag, code, new_val))
            
            auth_controlled = False
        else:
            new_val = str(new_val)
            auth_controlled = False
            
        ###

        if len(subs) == 0 or subfield_place == '+':
            # new subfield
            
            if Config.is_authority_controlled(self.record_type, self.tag, code) == True:
                self.subfields.append(Linked(code, new_val))
            else:
                self.subfields.append(Literal(code, new_val))

            return self
    
        elif isinstance(subfield_place, int):
            # replace exisiting subfield
            
            subs = [subs[subfield_place]]

        for sub in subs:
            if isinstance(sub, Literal):
                sub.value = new_val

            elif isinstance(sub, Linked):
                sub.xref = new_val

        return self
Exemplo n.º 3
0
    def to_mrc(self, delim=u'\u001f', term=u'\u001e', language=None):
        string = self.ind1 + self.ind2
        
        for sub in self.subfields:
            if language and Config.linked_language_source_tag(self.record_type, self.tag, sub.code, language):
                value = sub.translated(language)
            else: 
                value = sub.value

            string += ''.join([delim + sub.code + value])

        return string + term
Exemplo n.º 4
0
    def to_mrk(self, language=None):
        inds = self.ind1 + self.ind2
        inds = inds.replace(' ', '\\')

        string = '{}  {}'.format(self.tag, inds)
        
        for sub in self.subfields:
            if language and Config.linked_language_source_tag(self.record_type, self.tag, sub.code, language):
                value = sub.translated(language)
            else: 
                value = sub.value
            
            string += ''.join(['${}{}'.format(sub.code, sub.value)])

        return string
Exemplo n.º 5
0
 def heading_value(self, code, language=None):
     if language:
         tag = self.heading_field.tag
         lang_tag = Config.language_source_tag(tag, language)
         source_field = self.get_field(lang_tag)
         
         if source_field is None:
             return '**Linked Auth Translation Not Found**'
     else:
         source_field = self.heading_field
         
         if source_field is None:
             return '**Linked Auth Label Not Found**'
     
     for sub in filter(lambda sub: sub.code == code, source_field.subfields):
         return sub.value
Exemplo n.º 6
0
    def to_str(self, *tags, language=None):
        # non-standard format intended to be human readable
        string = ''

        for field in self.get_fields(*tags):
            string += field.tag + '\n'

            if isinstance(field, Controlfield):
                string += '   ' + field.value + '\n'
            else:
                for sub in field.subfields:
                    if language and Config.linked_language_source_tag(self.record_type, field.tag, sub.code, language):
                        val = sub.translated(language)
                    else:
                        val = sub.value

                    string += '   ' + sub.code + ': ' + val + '\n'

        return string
Exemplo n.º 7
0
    def to_xml_raw(self, *tags, language=None, xref_prefix=''):
        # todo: reimplement with `xml.dom` or `lxml` to enable pretty-printing
        root = XML.Element('record')

        for field in self.get_fields(*tags):
            if isinstance(field, Controlfield):
                node = XML.SubElement(root, 'controlfield')
                node.set('tag', field.tag)
                node.text = field.value
            else:
                node = XML.SubElement(root, 'datafield')
                node.set('tag', field.tag)
                node.set('ind1', field.ind1)
                node.set('ind2', field.ind2)
                
                xref = None
                
                for sub in field.subfields:
                    if hasattr(sub, 'xref'):
                        xref = sub.xref
                    
                    subnode = XML.SubElement(node, 'subfield')
                    subnode.set('code', sub.code)
                    
                    if language and Config.linked_language_source_tag(self.record_type, field.tag, sub.code, language):
                        subnode.text = sub.translated(language)
                        continue   
                        
                    subnode.text = sub.value
                    
                if xref:
                    subnode = XML.SubElement(node, 'subfield')
                    subnode.set('code', '0')
                    subnode.text = xref_prefix + str(xref)
                    
        return root
Exemplo n.º 8
0
    def compile(self):
        tag = self.tag
        subconditions = []

        for sub in self.subfields:
            code = sub[0]
            val = sub[1]

            if not Config.is_authority_controlled(self.record_type, tag, code):
                subconditions.append(
                    SON({'$elemMatch': {
                        'code': code,
                        'value': val
                    }}))
            else:
                if isinstance(val, int):
                    xrefs = [val]
                else:
                    auth_tag = Config.authority_source_tag(
                        self.record_type, tag, code)
                    lookup = SON({
                        auth_tag + '.subfields':
                        SON({'$elemMatch': {
                            'code': code,
                            'value': val
                        }})
                    })
                    xrefs = [
                        doc['_id']
                        for doc in DB.auths.find(lookup, {'_id': 1})
                    ]

                subconditions.append(
                    SON({
                        '$elemMatch': {
                            'code': code,
                            'xref': xrefs[0] if len(xrefs) == 1 else {
                                '$in': xrefs
                            }
                        }
                    }))

        submatch = subconditions[0] if len(subconditions) == 1 else {
            '$all': subconditions
        }

        if not self.modifier:
            return SON({tag: {'$elemMatch': {'subfields': submatch}}})
        else:
            if self.modifier == 'not':
                return SON({
                    '$or': [{
                        tag: {
                            '$not': {
                                '$elemMatch': {
                                    'subfields': submatch
                                }
                            }
                        }
                    }, {
                        tag: {
                            '$exists': False
                        }
                    }]
                })
            elif self.modifier == 'exists':
                return {tag: {'$exists': True}}
            elif self.modifier == 'not_exists':
                return {tag: {'$exists': False}}
            else:
                raise Exception('Invalid modifier')