common.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from __future__ import print_function
  2. import os
  3. import ckan.plugins as p
  4. def load_config(config_filepath):
  5. import paste.deploy
  6. config_abs_path = os.path.abspath(config_filepath)
  7. conf = paste.deploy.appconfig('config:' + config_abs_path)
  8. import ckan
  9. ckan.config.environment.load_environment(conf.global_conf,
  10. conf.local_conf)
  11. def register_translator():
  12. # Register a translator in this thread so that
  13. # the _() functions in logic layer can work
  14. from paste.registry import Registry
  15. from pylons import translator
  16. from ckan.lib.cli import MockTranslator
  17. global registry
  18. registry = Registry()
  19. registry.prepare()
  20. global translator_obj
  21. translator_obj = MockTranslator()
  22. registry.register(translator, translator_obj)
  23. def get_resources(state='active', publisher_ref=None, resource_id=None,
  24. dataset_name=None):
  25. ''' Returns all active resources, or filtered by the given criteria. '''
  26. from ckan import model
  27. resources = model.Session.query(model.Resource) \
  28. .filter_by(state=state)
  29. if p.toolkit.check_ckan_version(max_version='2.2.99'):
  30. # earlier CKANs had ResourceGroup
  31. resources = resources.join(model.ResourceGroup)
  32. resources = resources \
  33. .join(model.Package) \
  34. .filter_by(state='active')
  35. criteria = [state]
  36. if publisher_ref:
  37. publisher = model.Group.get(publisher_ref)
  38. assert publisher
  39. resources = resources.filter(model.Package.owner_org == publisher.id)
  40. criteria.append('Publisher:%s' % publisher.name)
  41. if dataset_name:
  42. resources = resources.filter(model.Package.name == dataset_name)
  43. criteria.append('Dataset:%s' % dataset_name)
  44. if resource_id:
  45. resources = resources.filter(model.Resource.id == resource_id)
  46. criteria.append('Resource:%s' % resource_id)
  47. resources = resources.all()
  48. print('%i resources (%s)' % (len(resources), ' '.join(criteria)))
  49. return resources