utils.py 2.05 KB
Newer Older
Pablo Panero's avatar
Pablo Panero committed
1
2
3
4
5
6
7
8
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""Helper methods for CERN Search records."""

from flask import g
from flask import current_app
from invenio_search import current_search
9
from invenio_search.utils import schema_to_index, build_index_name
Pablo Panero's avatar
Pablo Panero committed
10
11
12
13
14
15
16


def get_user_provides():
    """Extract the user's provides from g."""
    return [need.value for need in g.identity.provides]


17
18
19
20
21
22
23
24
def get_index_from_request(record=None):
    if record is not None and record.get('$schema', '') is not None:
        return cern_search_record_to_index(record)
    current_app.logger.debug('get_index_from_schema() No record or no $schema in it, using defaults')
    return (current_app.config['INDEXER_DEFAULT_INDEX'],
            current_app.config['INDEXER_DEFAULT_DOC_TYPE'])


Pablo Panero's avatar
Pablo Panero committed
25
26
27
28
29
30
31
32
33
34
def cern_search_record_to_index(record):
    """Get index/doc_type given a record.
    It tries to extract from `record['$schema']` the index and doc_type,
    the index has `CERN_SEARCH_INDEX_PREFIX` as prefix or `CERN_SEARCH_DEFAULT_INDEX_PREFIX`
    if it is not set up to be able to use the ES central service.
    If it fails, return the default values. In this case the prefix is the default value.
    :param record: The record object.
    :returns: Tuple (index, doc_type).
    """

35
    prefix = current_app.config['INDEX_PREFIX']
Pablo Panero's avatar
Pablo Panero committed
36
    index_names = current_search.mappings.keys()
37

Pablo Panero's avatar
Pablo Panero committed
38
39
40
    schema = record.get('$schema', '')
    if isinstance(schema, dict):
        schema = schema.get('$ref', '')
41
42
43
44
45
46
47
48
49
50

    parts = schema.split('/')

    if index_names:
        for start in range(len(parts)):
            index_name = build_index_name(*parts[start:])
            if index_name in index_names:
                if index_name.startswith(prefix) and len(index_name) > len(prefix) + 2:
                    return index_name, index_name[len(prefix) + 1:]

51
    current_app.logger.debug('Index {0} - Doc {1}'.format(
52
53
54
        current_app.config['INDEXER_DEFAULT_INDEX'],
        current_app.config['INDEXER_DEFAULT_DOC_TYPE'])
    )
55
    return (current_app.config['INDEXER_DEFAULT_INDEX'],
56
            current_app.config['INDEXER_DEFAULT_DOC_TYPE'])