author Denis Laxalde <denis.laxalde@logilab.fr>
Mon, 20 Oct 2014 16:06:38 +0200
changeset 13 133dda956327
parent 7 6e1d41bacacf
child 5 ecfe8af98c87
child 14 50e1c7ac3e59
permissions -rw-r--r--
[hooks,entities] Handle resources for CKAN dataset Closes #4502967.

# copyright 2014 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# contact http://www.logilab.fr -- mailto:contact@logilab.fr
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 2.1 of the License, or (at your option)
# any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
# You should have received a copy of the GNU Lesser General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
"""cubicweb-cg33catsi utilities"""

import json
from urllib import basejoin

import requests

from cubicweb.predicates import objectify_predicate

class CKANPostError(Exception):
    """CKAN post action error"""

def ckan_post(config, action, data=None):
    url = basejoin(config['ckan-baseurl'], 'api/3/action/' + action)
    headers = {'Authorization': config['ckan-api-key'],
               'Content-Type': 'application/json'}
    r = requests.post(url, headers=headers, data=json.dumps(data or {}))
    if not r.ok:
        error = r.json()['error']
        raise CKANPostError('action %s failed: %s' % (action, error))
    return r.json()['result']

def ckan_instance_configured(cls, req, **kwargs):
    """Return 1 if CKAN instance configuration is defined.

    (Mostly useful in tests to disable CKAN hooks.)
    config = req.vreg.config
    for option in ('ckan-baseurl', 'ckan-api-key', 'ckan-organization'):
        if not config.get(option):
            req.error('CKAN instance configuration incomplete, missing "%s" '
                      'option' % option)
            return 0
    return 1