source: publico/ILSAPL/trunk/lexml/OAI.py @ 6142

Última Alteração nesse arquivo desde 6142 foi 6142, incluída por lucianodefazio, 9 anos atrás

Commit do SAPL 2.5 - GoogleCode? - no trunk (Versão 2.4 + Módulos de Protocolo Geral e Documentos Administrativos

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