source: publico/ILSAPL/branches/2.5/lexml/OAI.py @ 7145

Última Alteração nesse arquivo desde 7145 foi 7145, incluída por gustavolepri, 7 anos atrás

fix bug em relacao as consultas

File size: 4.9 KB
Linha 
1# -*- coding: utf-8 -*-
2
3from datetime import datetime
4
5import oaipmh
6import oaipmh.metadata
7import oaipmh.server
8import oaipmh.error
9
10from metadata import OAILEXML
11
12
13def get_writer(prefix, config={}):
14    writer = OAILEXML
15    return writer(prefix, config={})
16
17
18class OAIServer(object):
19    """An OAI-2.0 compliant oai server.
20   
21    Underlying code is based on pyoai's oaipmh.server'
22    """
23   
24    def __init__(self, sapl_tool, config={}):
25        self.config = config
26        self.sapl_tool = sapl_tool
27
28    def get_oai_id(self, internal_id):
29        return 'oai:%s' % internal_id
30
31    def get_internal_id(self, oai_id):
32        return int(oai_id.split('/').pop())
33
34    def get_internal_set_id(self, oai_setspec_id):
35        return oai_setspec_id[4:]
36
37    def get_asset_path(self, internal_id, asset):
38        return os.path.abspath(
39            os.path.join(self.base_asset_path,
40                         internal_id,
41                         asset['filename']))
42
43    def identify(self):
44        result = oaipmh.common.Identify(
45            repositoryName=self.config['titulo'],
46            baseURL=self.config['base_url'],
47            protocolVersion='2.0',
48            adminEmails=self.config['email'],
49            earliestDatestamp=datetime(2001, 1, 1, 10, 00),
50            deletedRecord='transient',
51            granularity='YYYY-MM-DDThh:mm:ssZ',
52            compression=['identity'],
53            toolkit_description=False)
54        if self.config['descricao'] is not None:
55            result.add_description(self.config['descricao'])
56        return result
57
58    def listMetadataFormats(self, identifier=None):
59        result = []
60        for prefix in self.config['metadata_prefixes']:
61            writer = get_writer(prefix, self.config)
62            ns = writer.get_namespace()
63            schema = writer.get_schema_location()
64            result.append((prefix, schema, ns))
65        return result
66   
67    def listRecords(self, metadataPrefix, set=None, from_=None, until=None,
68                    cursor=0, batch_size=10):
69
70        self._checkMetadataPrefix(metadataPrefix)
71        for record in self._listQuery(set, from_, until, cursor, batch_size):
72            header, metadata = self._createHeaderAndMetadata(record)
73            yield header, metadata, None
74
75    def listIdentifiers(self, metadataPrefix, set=None, from_=None, until=None,
76                        cursor=0, batch_size=10):
77       
78        self._checkMetadataPrefix(metadataPrefix)
79        for record in self._listQuery(set, from_, until, cursor, batch_size):
80            yield self._createHeader(record)
81
82    def getRecord(self, metadataPrefix, identifier):
83        self._checkMetadataPrefix(metadataPrefix)
84        header = None
85        metadata = None
86        for record in self._listQuery(identifier=identifier):
87            header, metadata = self._createHeaderAndMetadata(record)
88        if header is None:
89            raise oaipmh.error.IdDoesNotExistError(identifier)
90        return header, metadata, None
91
92    def _checkMetadataPrefix(self, metadataPrefix):
93        if metadataPrefix not in self.config['metadata_prefixes']:
94            raise oaipmh.error.CannotDisseminateFormatError
95
96    def _createHeader(self, record):
97        oai_id = self.get_oai_id(record['record']['id'])
98        datestamp = record['record']['when_modified']
99        sets = []
100        deleted = record['record']['deleted']
101
102        return oaipmh.common.Header(oai_id, datestamp, sets, deleted)
103
104    def _createHeaderAndMetadata(self, record):
105        header = self._createHeader(record)
106        metadata = oaipmh.common.Metadata(record['metadata'])
107        metadata.record = record
108        return header, metadata
109   
110    def _listQuery(self, set=None, from_=None, until=None,
111                   cursor=0, batch_size=10, identifier=None):
112
113        if identifier:
114            identifier = self.get_internal_id(identifier)
115        else:
116            identifier = ''
117        if set:
118            set = self.get_internal_set_id(set)
119       
120        # TODO: verificar se a data eh UTC
121        now = datetime.now()
122        if until != None and until > now:
123            # until nunca deve ser no futuro
124            until = now
125           
126        return self.sapl_tool.oai_query(offset=cursor,
127                                        batch_size=batch_size,
128                                        from_date=from_,
129                                        until_date=until,
130                                        identifier=identifier
131                                        )
132
133
134def OAIServerFactory(sapl_tool, config={}):
135    """Create a new OAI batching OAI Server given a config and
136    a database"""
137    for prefix in config['metadata_prefixes']:
138        metadata_registry = oaipmh.metadata.MetadataRegistry()
139        metadata_registry.registerWriter(prefix, get_writer(prefix, config))
140           
141    return oaipmh.server.BatchingServer(
142        OAIServer(sapl_tool, config),
143        metadata_registry=metadata_registry,
144        resumption_batch_size=config['batch_size']
145        )
Note: Veja TracBrowser para ajuda no uso do navegador do trac.
 

The contents and data of this website are published under license:
Creative Commons 4.0 Brasil - Atribuir Fonte - Compartilhar Igual.