repo
stringclasses
856 values
pull_number
int64
3
127k
instance_id
stringlengths
12
58
issue_numbers
sequencelengths
1
5
base_commit
stringlengths
40
40
patch
stringlengths
67
1.54M
test_patch
stringlengths
0
107M
problem_statement
stringlengths
3
307k
hints_text
stringlengths
0
908k
created_at
timestamp[s]
ckan/ckan
3,038
ckan__ckan-3038
[ "2990" ]
05eb24111246467820d290a92784307bf3bc1042
diff --git a/ckan/controllers/group.py b/ckan/controllers/group.py --- a/ckan/controllers/group.py +++ b/ckan/controllers/group.py @@ -159,6 +159,7 @@ def index(self): sort_by = c.sort_by_selected = request.params.get('sort') try: self._check_access('site_read', context) + self._check_access('group_list', context) except NotAuthorized: abort(403, _('Not authorized to see this page'))
diff --git a/ckan/tests/controllers/test_organization.py b/ckan/tests/controllers/test_organization.py --- a/ckan/tests/controllers/test_organization.py +++ b/ckan/tests/controllers/test_organization.py @@ -1,6 +1,7 @@ from bs4 import BeautifulSoup from nose.tools import assert_equal, assert_true from routes import url_for +from mock import patch from ckan.tests import factories, helpers from ckan.tests.helpers import webtest_submit, submit_and_follow, assert_in @@ -61,6 +62,22 @@ def test_all_fields_saved(self): assert_equal(group['description'], 'Sciencey datasets') +class TestOrganizationList(helpers.FunctionalTestBase): + def setup(self): + super(TestOrganizationList, self).setup() + self.app = helpers._get_test_app() + self.user = factories.User() + self.user_env = {'REMOTE_USER': self.user['name'].encode('ascii')} + self.organization_list_url = url_for(controller='organization', + action='index') + + @patch('ckan.logic.auth.get.organization_list', return_value={'success': False}) + def test_error_message_shown_when_no_organization_list_permission(self, mock_check_access): + response = self.app.get(url=self.organization_list_url, + extra_environ=self.user_env, + status=403) + + class TestOrganizationRead(helpers.FunctionalTestBase): def setup(self): super(TestOrganizationRead, self).setup()
Server error at /organization if not authorized to list organizations ### CKAN Version if known (or site URL) 2.5.2 ### Please describe the expected behaviour The behaviour should be similar to if the user goes to /organization/foo and does not have "organization_show" access ie the user gets logged out and sees a message "Organizations are not available." ### Please describe the actual behaviour Server error: ``` URL: http://localhost:5000/organization File '/home/martinb/workspace/ckan/lib/default/local/lib/python2.7/site-packages/weberror/evalexception.py', line 428 in respond app_iter = self.application(environ, detect_start_response) File '/home/martinb/workspace/ckan/lib/default/local/lib/python2.7/site-packages/webob/dec.py', line 147 in __call__ resp = self.call_func(req, *args, **self.kwargs) File '/home/martinb/workspace/ckan/lib/default/local/lib/python2.7/site-packages/webob/dec.py', line 208 in call_func return self.func(req, *args, **kwargs) File '/home/martinb/workspace/ckan/lib/default/local/lib/python2.7/site-packages/fanstatic/publisher.py', line 234 in __call__ return request.get_response(self.app) File '/home/martinb/workspace/ckan/lib/default/local/lib/python2.7/site-packages/webob/request.py', line 1053 in get_response application, catch_exc_info=False) File '/home/martinb/workspace/ckan/lib/default/local/lib/python2.7/site-packages/webob/request.py', line 1022 in call_application app_iter = application(self.environ, start_response) File '/home/martinb/workspace/ckan/lib/default/local/lib/python2.7/site-packages/webob/dec.py', line 147 in __call__ resp = self.call_func(req, *args, **self.kwargs) File '/home/martinb/workspace/ckan/lib/default/local/lib/python2.7/site-packages/webob/dec.py', line 208 in call_func return self.func(req, *args, **kwargs) File '/home/martinb/workspace/ckan/lib/default/local/lib/python2.7/site-packages/fanstatic/injector.py', line 54 in __call__ response = request.get_response(self.app) File '/home/martinb/workspace/ckan/lib/default/local/lib/python2.7/site-packages/webob/request.py', line 1053 in get_response application, catch_exc_info=False) File '/home/martinb/workspace/ckan/lib/default/local/lib/python2.7/site-packages/webob/request.py', line 1022 in call_application app_iter = application(self.environ, start_response) File '/home/martinb/workspace/ckan/lib/default/src/ckan/ckan/config/middleware.py', line 389 in inner result = application(environ, start_response) File '/home/martinb/workspace/ckan/lib/default/local/lib/python2.7/site-packages/beaker/middleware.py', line 73 in __call__ return self.app(environ, start_response) File '/home/martinb/workspace/ckan/lib/default/local/lib/python2.7/site-packages/beaker/middleware.py', line 155 in __call__ return self.wrap_app(environ, session_start_response) File '/home/martinb/workspace/ckan/lib/default/local/lib/python2.7/site-packages/routes/middleware.py', line 131 in __call__ response = self.app(environ, start_response) File '/home/martinb/workspace/ckan/lib/default/local/lib/python2.7/site-packages/pylons/wsgiapp.py', line 125 in __call__ response = self.dispatch(controller, environ, start_response) File '/home/martinb/workspace/ckan/lib/default/local/lib/python2.7/site-packages/pylons/wsgiapp.py', line 324 in dispatch return controller(environ, start_response) File '/home/martinb/workspace/ckan/lib/default/src/ckan/ckan/lib/base.py', line 337 in __call__ res = WSGIController.__call__(self, environ, start_response) File '/home/martinb/workspace/ckan/lib/default/local/lib/python2.7/site-packages/pylons/controllers/core.py', line 221 in __call__ response = self._dispatch_call() File '/home/martinb/workspace/ckan/lib/default/local/lib/python2.7/site-packages/pylons/controllers/core.py', line 172 in _dispatch_call response = self._inspect_call(func) File '/home/martinb/workspace/ckan/lib/default/local/lib/python2.7/site-packages/pylons/controllers/core.py', line 107 in _inspect_call result = self._perform_call(func, args) File '/home/martinb/workspace/ckan/lib/default/local/lib/python2.7/site-packages/pylons/controllers/core.py', line 60 in _perform_call return func(**args) File '/home/martinb/workspace/ckan/lib/default/src/ckan/ckan/controllers/group.py', line 178 in index data_dict_global_results) File '/home/martinb/workspace/ckan/lib/default/src/ckan/ckan/logic/__init__.py', line 416 in wrapped result = _action(context, data_dict, **kw) File '/home/martinb/workspace/ckan/lib/default/src/ckan/ckan/logic/action/get.py', line 608 in organization_list _check_access('organization_list', context, data_dict) File '/home/martinb/workspace/ckan/lib/default/src/ckan/ckan/logic/__init__.py', line 286 in check_access raise NotAuthorized(msg) NotAuthorized: <function unauthorized at 0x7f1d7e787410> requires an authenticated user ``` ### What steps can be taken to reproduce the issue? Log in with a user that does not have "organization_list" access and go to /organization
@k-nut if you've got some time, this looks like a quick one
2016-05-20T10:08:14
ckan/ckan
3,042
ckan__ckan-3042
[ "3041" ]
05eb24111246467820d290a92784307bf3bc1042
diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py --- a/ckan/lib/helpers.py +++ b/ckan/lib/helpers.py @@ -54,8 +54,8 @@ def __init__(self, *args, **kwargs): def __getitem__(self, key): try: - value = super(HelperAttributeDict, self).__getitem__(self, key) - except AttributeError: + value = super(HelperAttributeDict, self).__getitem__(key) + except KeyError: raise ckan.exceptions.HelperError( 'Helper \'{key}\' has not been defined.'.format( key=key diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -158,6 +158,7 @@ 'test_datastore_view = ckan.tests.lib.test_datapreview:MockDatastoreBasedResourceView', 'test_datapusher_plugin = ckanext.datapusher.tests.test_interfaces:FakeDataPusherPlugin', 'test_routing_plugin = ckan.tests.config.test_middleware:MockRoutingPlugin', + 'test_helpers_plugin = ckan.tests.lib.test_helpers:TestHelpersPlugin', ], 'babel.extractors': [ 'ckan = ckan.lib.extract:extract_ckan',
diff --git a/ckan/templates/tests/broken_helper_as_attribute.html b/ckan/templates/tests/broken_helper_as_attribute.html new file mode 100644 --- /dev/null +++ b/ckan/templates/tests/broken_helper_as_attribute.html @@ -0,0 +1,5 @@ +{% extends 'page.html' %} + +{% block page %} + {{ h.not_here() }} +{% endblock %} diff --git a/ckan/templates/tests/broken_helper_as_item.html b/ckan/templates/tests/broken_helper_as_item.html new file mode 100644 --- /dev/null +++ b/ckan/templates/tests/broken_helper_as_item.html @@ -0,0 +1,5 @@ +{% extends 'page.html' %} + +{% block page %} + {{ h['not_here']() }} +{% endblock %} diff --git a/ckan/templates/tests/helper_as_attribute.html b/ckan/templates/tests/helper_as_attribute.html new file mode 100644 --- /dev/null +++ b/ckan/templates/tests/helper_as_attribute.html @@ -0,0 +1,5 @@ +{% extends 'page.html' %} + +{% block page %} + My lang is: {{ h.lang() }} +{% endblock %} diff --git a/ckan/templates/tests/helper_as_item.html b/ckan/templates/tests/helper_as_item.html new file mode 100644 --- /dev/null +++ b/ckan/templates/tests/helper_as_item.html @@ -0,0 +1,5 @@ +{% extends 'page.html' %} + +{% block page %} + My lang is: {{ h['lang']() }} +{% endblock %} diff --git a/ckan/tests/lib/test_helpers.py b/ckan/tests/lib/test_helpers.py --- a/ckan/tests/lib/test_helpers.py +++ b/ckan/tests/lib/test_helpers.py @@ -4,10 +4,14 @@ from babel import Locale import ckan.lib.helpers as h +import ckan.plugins as p import ckan.exceptions from ckan.tests import helpers +import ckan.lib.base as base +ok_ = nose.tools.ok_ eq_ = nose.tools.eq_ +raises = nose.tools.raises CkanUrlException = ckan.exceptions.CkanUrlException @@ -266,3 +270,102 @@ def test_server_timezone(self): @helpers.change_config('ckan.display_timezone', 'America/New_York') def test_named_timezone(self): eq_(h.get_display_timezone(), pytz.timezone('America/New_York')) + + +class TestHelperException(helpers.FunctionalTestBase): + + @raises(ckan.exceptions.HelperError) + def test_helper_exception_non_existing_helper_as_attribute(self): + '''Calling a non-existing helper on `h` raises a HelperException.''' + if not p.plugin_loaded('test_helpers_plugin'): + p.load('test_helpers_plugin') + + app = self._get_test_app() + + app.get('/broken_helper_as_attribute') + + p.unload('test_helpers_plugin') + + @raises(ckan.exceptions.HelperError) + def test_helper_exception_non_existing_helper_as_item(self): + '''Calling a non-existing helper on `h` raises a HelperException.''' + if not p.plugin_loaded('test_helpers_plugin'): + p.load('test_helpers_plugin') + + app = self._get_test_app() + + app.get('/broken_helper_as_item') + + p.unload('test_helpers_plugin') + + def test_helper_existing_helper_as_attribute(self): + '''Calling an existing helper on `h` doesn't raises a + HelperException.''' + + if not p.plugin_loaded('test_helpers_plugin'): + p.load('test_helpers_plugin') + + app = self._get_test_app() + + res = app.get('/helper_as_attribute') + + ok_('My lang is: en' in res.body) + + p.unload('test_helpers_plugin') + + def test_helper_existing_helper_as_item(self): + '''Calling an existing helper on `h` doesn't raises a + HelperException.''' + + if not p.plugin_loaded('test_helpers_plugin'): + p.load('test_helpers_plugin') + + app = self._get_test_app() + + res = app.get('/helper_as_item') + + ok_('My lang is: en' in res.body) + + p.unload('test_helpers_plugin') + + +class TestHelpersPlugin(p.SingletonPlugin): + + p.implements(p.IRoutes, inherit=True) + + controller = 'ckan.tests.lib.test_helpers:TestHelperController' + + def after_map(self, _map): + + _map.connect('/broken_helper_as_attribute', + controller=self.controller, + action='broken_helper_as_attribute') + + _map.connect('/broken_helper_as_item', + controller=self.controller, + action='broken_helper_as_item') + + _map.connect('/helper_as_attribute', + controller=self.controller, + action='helper_as_attribute') + + _map.connect('/helper_as_item', + controller=self.controller, + action='helper_as_item') + + return _map + + +class TestHelperController(p.toolkit.BaseController): + + def broken_helper_as_attribute(self): + return base.render('tests/broken_helper_as_attribute.html') + + def broken_helper_as_item(self): + return base.render('tests/broken_helper_as_item.html') + + def helper_as_attribute(self): + return base.render('tests/helper_as_attribute.html') + + def helper_as_item(self): + return base.render('tests/helper_as_item.html') diff --git a/ckan/tests/plugins/test_toolkit.py b/ckan/tests/plugins/test_toolkit.py --- a/ckan/tests/plugins/test_toolkit.py +++ b/ckan/tests/plugins/test_toolkit.py @@ -1,4 +1,4 @@ -from nose.tools import assert_equal, assert_raises, assert_true +from nose.tools import assert_equal, assert_raises, assert_true, raises from ckan.plugins import toolkit as tk @@ -260,11 +260,21 @@ def test_raise(self): tk.requires_ckan_version, min_version='3') -class TestTemplateHelper(object): +class TestToolkitHelper(object): def test_call_helper(self): # the null_function would return '' assert_true(tk.h.icon_url('x')) - def test_attribute_error_on_missing_helper(self): + def test_tk_helper_attribute_error_on_missing_helper(self): assert_raises(AttributeError, getattr, tk.h, 'not_a_real_helper_function') + + @raises(AttributeError) + def test_tk_helper_as_attribute_missing_helper(self): + '''Directly attempt access to module function''' + tk.h.nothere() + + @raises(tk.HelperError) + def test_tk_helper_as_item_missing_helper(self): + '''Directly attempt access as item''' + tk.h['nothere']()
Attempting to access non-existing helpers should raise HelperException ### CKAN Version if known (or site URL) 2.6a, master ### Please describe the expected behaviour If helper function is called in a template, but the function doesn't exist, a `ckan.exceptions.HelperError` should be raised. ### Please describe the actual behaviour A `jinja.exceptions.UndefinedError` is raised. ### What steps can be taken to reproduce the issue? Add `{{ h.not_here() }}` to the base.html template and request the index page. PR on its way.
2016-05-20T15:54:05
ckan/ckan
3,047
ckan__ckan-3047
[ "3045" ]
1fae410b2fd92f2f48d9d3a00cedaf54a46387e8
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -177,14 +177,6 @@ zip_safe=False, packages=find_packages(exclude=['ez_setup']), namespace_packages=['ckanext', 'ckanext.stats'], - include_package_data=True, - package_data={'ckan': [ - 'i18n/*/LC_MESSAGES/*.mo', - 'migration/migrate.cfg', - 'migration/README', - 'migration/tests/test_dumps/*', - 'migration/versions/*', - ]}, message_extractors={ 'ckan': [ ('**.py', 'python', None),
Migration 021 missing after pip install ### CKAN Version if known (or site URL) CKAN 2.5.2 ### Please describe the expected behaviour After installation of CKAN, the files 021_postgres_downgrade.sql, 021_postgres_upgrade.sql, 021_postgresql_downgrade.sql, and 021_postgresql_upgrade.sql should be in the migration/versions directory. ### Please describe the actual behaviour They're not in the directory. Running paster --plugin=ckan db init fails with a KeyError for migration 021. ### What steps can be taken to reproduce the issue? ``` sisyphus:~ $ virtualenv ./v Running virtualenv with interpreter /usr/bin/python2 New python executable in /home/gbowland/v/bin/python2 Also creating executable in /home/gbowland/v/bin/python Installing setuptools, pkg_resources, pip, wheel...done. sisyphus:~ $ . ./v/bin/activate (v) sisyphus:~ $ pip install ckan==2.5.2 Collecting ckan==2.5.2 Installing collected packages: ckan Successfully installed ckan-2.5.2 (v) sisyphus:~ $ ls v/lib/python2.7/site-packages/ckan/migration/versions/021* zsh: no matches found: v/lib/python2.7/site-packages/ckan/migration/versions/021* ``` Note that 021 is different in that it has .sql files, that may be the issue. Installing with pip via the git tag (git+git://github.com/ckan/[email protected]) works fine. If I do `python setup.py bdist` from the tag 'ckan-2.5.2` the resulting tarfile includes the .sql files for 021, so I'm a bit puzzled as to what happened.
nigelb on IRC mentioned that the process for releases is sdist, the SQL files for 021 migration are definitely not being included when an sdist is made.
2016-05-23T10:08:12
ckan/ckan
3,054
ckan__ckan-3054
[ "3046" ]
3717886a0231499b52db1e8eba869b2947358e1f
diff --git a/ckan/logic/validators.py b/ckan/logic/validators.py --- a/ckan/logic/validators.py +++ b/ckan/logic/validators.py @@ -29,7 +29,7 @@ def owner_org_validator(key, data, errors, context): if value is missing or value is None: if not authz.check_config_permission('create_unowned_dataset'): - raise Invalid(_('A organization must be supplied')) + raise Invalid(_('An organization must be provided')) data.pop(key, None) raise df.StopOnError @@ -38,7 +38,7 @@ def owner_org_validator(key, data, errors, context): user = model.User.get(user) if value == '': if not authz.check_config_permission('create_unowned_dataset'): - raise Invalid(_('A organization must be supplied')) + raise Invalid(_('An organization must be provided')) return group = model.Group.get(value)
diff --git a/ckan/tests/controllers/test_package.py b/ckan/tests/controllers/test_package.py --- a/ckan/tests/controllers/test_package.py +++ b/ckan/tests/controllers/test_package.py @@ -8,6 +8,7 @@ assert_true, ) +from mock import patch, MagicMock from routes import url_for import ckan.model as model @@ -40,6 +41,48 @@ def test_form_renders(self): env, response = _get_package_new_page(app) assert_true('dataset-edit' in response.forms) + @helpers.change_config('ckan.auth.create_unowned_dataset', 'false') + def test_needs_organization_but_no_organizations_has_button(self): + ''' Scenario: The settings say every dataset needs an organization + but there are no organizations. If the user is allowed to create an + organization they should be prompted to do so when they try to create + a new dataset''' + app = self._get_test_app() + sysadmin = factories.Sysadmin() + + env = {'REMOTE_USER': sysadmin['name'].encode('ascii')} + response = app.get( + url=url_for(controller='package', action='new'), + extra_environ=env + ) + assert 'dataset-edit' not in response.forms + assert url_for(controller='organization', action='new') in response + + @helpers.mock_auth('ckan.logic.auth.create.package_create') + @helpers.change_config('ckan.auth.create_unowned_dataset', 'false') + @helpers.change_config('ckan.auth.user_create_organizations', 'false') + def test_needs_organization_but_no_organizations_no_button(self, + mock_p_create): + ''' Scenario: The settings say every dataset needs an organization + but there are no organizations. If the user is not allowed to create an + organization they should be told to ask the admin but no link should be + presented. Note: This cannot happen with the default ckan and requires + a plugin to overwrite the package_create behavior''' + mock_p_create.return_value = {'success': True} + + app = self._get_test_app() + user = factories.User() + + env = {'REMOTE_USER': user['name'].encode('ascii')} + response = app.get( + url=url_for(controller='package', action='new'), + extra_environ=env + ) + + assert 'dataset-edit' not in response.forms + assert url_for(controller='organization', action='new') not in response + assert 'Ask a system administrator' in response + def test_name_required(self): app = self._get_test_app() env, response = _get_package_new_page(app) diff --git a/ckan/tests/helpers.py b/ckan/tests/helpers.py --- a/ckan/tests/helpers.py +++ b/ckan/tests/helpers.py @@ -328,6 +328,53 @@ def wrapper(*args, **kwargs): return decorator +def mock_auth(auth_function_path): + ''' + Decorator to easily mock a CKAN auth method in the context of a test + function + + It adds a mock object for the provided auth_function_path as a parameter to + the test function. + + Essentially it makes sure that `ckan.authz.clear_auth_functions_cache` is + called before and after to make sure that the auth functions pick up + the newly changed values. + + Usage:: + + @helpers.mock_auth('ckan.logic.auth.create.package_create') + def test_mock_package_create(self, mock_package_create): + from ckan import logic + mock_package_create.return_value = {'success': True} + + # package_create is mocked + eq_(logic.check_access('package_create', {}), True) + + assert mock_package_create.called + + :param action_name: the full path to the auth function to be mocked, + e.g. ``ckan.logic.auth.create.package_create`` + :type action_name: string + + ''' + from ckan.authz import clear_auth_functions_cache + + def decorator(func): + def wrapper(*args, **kwargs): + + try: + with mock.patch(auth_function_path) as mocked_auth: + clear_auth_functions_cache() + new_args = args + tuple([mocked_auth]) + return_value = func(*new_args, **kwargs) + finally: + clear_auth_functions_cache() + return return_value + + return nose.tools.make_decorator(func)(wrapper) + return decorator + + def mock_action(action_name): ''' Decorator to easily mock a CKAN action in the context of a test function
Creation of datasets/harvest sources with no organization specified ### CKAN Version if known (or site URL) 2.5.2 ### Please describe the expected behaviour Alternative 1: When adding a new dataset/harvest source and no organization has been created so far, the user should be promoted with a note that this has to be done first. Maybe the form could be grayed out. Alternative 2: When adding a new dataset/harvest source and no organization has been created so far, the form should still include the organization-field. When the user puts focus on it, a dialogue opens assisting the user in creating a new organization. ### Please describe the actual behaviour When adding a new dataset/harvest source and no organization has been created so far, the form field for organization is not displayed. The form can be filled out. After saving an error message reads > The form contains invalid entries: > Owner org: A organization must be supplied This is confusing since no such field is provided. ### What steps can be taken to reproduce the issue? 1. Create a new ckan instance or delete all organizations. 2. Create a new dataset/set up a new harvest source.
btw. "Owner org: **An** organization must be supplied" And maybe _provided_ is better here …
2016-05-25T13:39:36
ckan/ckan
3,056
ckan__ckan-3056
[ "2859" ]
dc3bb9eb01e8e266b97cc9e10f74e263988fd9b7
diff --git a/ckan/controllers/group.py b/ckan/controllers/group.py --- a/ckan/controllers/group.py +++ b/ckan/controllers/group.py @@ -825,10 +825,15 @@ def activity(self, id, offset=0): except (NotFound, NotAuthorized): abort(404, _('Group not found')) - # Add the group's activity stream (already rendered to HTML) to the - # template context for the group/read.html template to retrieve later. - c.group_activity_stream = self._action('group_activity_list_html')( - context, {'id': c.group_dict['id'], 'offset': offset}) + try: + # Add the group's activity stream (already rendered to HTML) to the + # template context for the group/read.html + # template to retrieve later. + c.group_activity_stream = self._action('group_activity_list_html')( + context, {'id': c.group_dict['id'], 'offset': offset}) + + except ValidationError as error: + base.abort(400) return render(self._activity_template(group_type), extra_vars={'group_type': group_type}) diff --git a/ckan/controllers/user.py b/ckan/controllers/user.py --- a/ckan/controllers/user.py +++ b/ckan/controllers/user.py @@ -585,8 +585,11 @@ def activity(self, id, offset=0): self._setup_template_variables(context, data_dict) - c.user_activity_stream = get_action('user_activity_list_html')( - context, {'id': c.user_dict['id'], 'offset': offset}) + try: + c.user_activity_stream = get_action('user_activity_list_html')( + context, {'id': c.user_dict['id'], 'offset': offset}) + except ValidationError: + base.abort(400) return render('user/activity_stream.html')
Sanitize offset when listing group activity This is a very minor problem, apart that it causes `HTTP 500` errors where it should simply ignore the `offset` parameter (or reply with a `HTTP 400`). It happens at https://github.com/ckan/ckan/blob/master/ckan/controllers/group.py#L860 because `offset` is not validated and passed as-is to the action api function. We have encountered this type of errors several times in our production site, since crawling robots insist on trying URLs like http://labs.geodata.gov.gr/group/activity/imagery-base-maps-earth-cover/None The above is tested on CKAN 2.2, but seems to be exactly the same at the master branch.
You are right, we have a couple of these on some actions. The best thing is to add [this decorator](https://github.com/ckan/ckan/blob/master/ckan/logic/action/get.py#L3254) to the [relevant action](https://github.com/ckan/ckan/blob/master/ckan/logic/action/get.py#L2695) and try / except a ValidationError on the group controller. Do you want to submit a small PR for this? That's ok, and is roughly what we've done in our fork to overcome it. I think the same problem also shows up in user activity lists (https://github.com/ckan/ckan/blob/master/ckan/controllers/user.py#L550). So, i will return with a PR.
2016-05-25T14:33:43
ckan/ckan
3,058
ckan__ckan-3058
[ "3057" ]
dc3bb9eb01e8e266b97cc9e10f74e263988fd9b7
diff --git a/ckan/logic/schema.py b/ckan/logic/schema.py --- a/ckan/logic/schema.py +++ b/ckan/logic/schema.py @@ -1,3 +1,7 @@ +from formencode.validators import OneOf + +import ckan.model +import ckan.plugins as plugins from ckan.lib.navl.validators import (ignore_missing, keep_extras, not_empty, @@ -6,60 +10,7 @@ if_empty_same_as, not_missing, ignore_empty - ) -from ckan.logic.validators import (package_id_not_changed, - package_id_exists, - package_id_or_name_exists, - resource_id_exists, - name_validator, - package_name_validator, - package_version_validator, - group_name_validator, - tag_length_validator, - tag_name_validator, - tag_string_convert, - duplicate_extras_key, - ignore_not_package_admin, - ignore_not_group_admin, - ignore_not_sysadmin, - no_http, - tag_not_uppercase, - user_name_validator, - user_password_validator, - user_both_passwords_entered, - user_passwords_match, - user_password_not_empty, - isodate, - int_validator, - natural_number_validator, - is_positive_integer, - boolean_validator, - user_about_validator, - vocabulary_name_validator, - vocabulary_id_not_changed, - vocabulary_id_exists, - user_id_exists, - user_id_or_name_exists, - object_id_validator, - activity_type_exists, - resource_id_exists, - tag_not_in_vocabulary, - group_id_exists, - owner_org_validator, - user_name_exists, - role_exists, - url_validator, - datasets_with_no_organization_cannot_be_private, - list_of_strings, - if_empty_guess_format, - clean_format, - no_loops_in_hierarchy, - filter_fields_and_values_should_have_same_length, - filter_fields_and_values_exist_and_are_valid, - extra_key_not_in_root_schema, - empty_if_not_sysadmin, - package_id_does_not_exist, - ) + ) from ckan.logic.converters import (convert_user_name_or_id_to_id, convert_package_name_or_id_to_id, convert_group_name_or_id_to_id, @@ -68,20 +19,65 @@ remove_whitespace, extras_unicode_convert, ) -from formencode.validators import OneOf -import ckan.model -import ckan.plugins as plugins +from ckan.logic.validators import ( + package_id_not_changed, + package_id_or_name_exists, + name_validator, + package_name_validator, + package_version_validator, + group_name_validator, + tag_length_validator, + tag_name_validator, + tag_string_convert, + duplicate_extras_key, + ignore_not_package_admin, + ignore_not_group_admin, + ignore_not_sysadmin, + no_http, + user_name_validator, + user_password_validator, + user_both_passwords_entered, + user_passwords_match, + user_password_not_empty, + isodate, + int_validator, + natural_number_validator, + is_positive_integer, + boolean_validator, + user_about_validator, + vocabulary_name_validator, + vocabulary_id_not_changed, + vocabulary_id_exists, + object_id_validator, + activity_type_exists, + resource_id_exists, + tag_not_in_vocabulary, + group_id_exists, + owner_org_validator, + user_name_exists, + role_exists, + datasets_with_no_organization_cannot_be_private, + list_of_strings, + if_empty_guess_format, + clean_format, + no_loops_in_hierarchy, + filter_fields_and_values_should_have_same_length, + filter_fields_and_values_exist_and_are_valid, + extra_key_not_in_root_schema, + empty_if_not_sysadmin, + package_id_does_not_exist, + ) def default_resource_schema(): - schema = { 'id': [ignore_empty, unicode], 'revision_id': [ignore_missing, unicode], 'package_id': [ignore], 'url': [not_empty, unicode, remove_whitespace], 'description': [ignore_missing, unicode], - 'format': [if_empty_guess_format, ignore_missing, clean_format, unicode], + 'format': [if_empty_guess_format, ignore_missing, clean_format, + unicode], 'hash': [ignore_missing, unicode], 'state': [ignore], 'position': [ignore], @@ -102,11 +98,13 @@ def default_resource_schema(): return schema + def default_update_resource_schema(): schema = default_resource_schema() schema['revision_id'] = [ignore] return schema + def default_tags_schema(): schema = { 'name': [not_missing, @@ -114,7 +112,7 @@ def default_tags_schema(): unicode, tag_length_validator, tag_name_validator, - ], + ], 'vocabulary_id': [ignore_missing, unicode, vocabulary_id_exists], 'revision_timestamp': [ignore], 'state': [ignore], @@ -122,13 +120,14 @@ def default_tags_schema(): } return schema + def default_create_tag_schema(): schema = default_tags_schema() # When creating a tag via the tag_create() logic action function, a # vocabulary_id _must_ be given (you cannot create free tags via this # function). schema['vocabulary_id'] = [not_missing, not_empty, unicode, - vocabulary_id_exists, tag_not_in_vocabulary] + vocabulary_id_exists, tag_not_in_vocabulary] # You're not allowed to specify your own ID when creating a tag. schema['id'] = [empty] return schema @@ -137,7 +136,8 @@ def default_create_tag_schema(): def default_create_package_schema(): schema = { '__before': [duplicate_extras_key, ignore], - 'id': [empty_if_not_sysadmin, ignore_missing, unicode, package_id_does_not_exist], + 'id': [empty_if_not_sysadmin, ignore_missing, unicode, + package_id_does_not_exist], 'revision_id': [ignore], 'name': [not_empty, unicode, name_validator, package_name_validator], 'title': [if_empty_same_as("name"), unicode], @@ -147,14 +147,14 @@ def default_create_package_schema(): 'maintainer_email': [ignore_missing, unicode], 'license_id': [ignore_missing, unicode], 'notes': [ignore_missing, unicode], - 'url': [ignore_missing, unicode],#, URL(add_http=False)], + 'url': [ignore_missing, unicode], # , URL(add_http=False)], 'version': [ignore_missing, unicode, package_version_validator], 'state': [ignore_not_package_admin, ignore_missing], 'type': [ignore_missing, unicode], 'owner_org': [owner_org_validator, unicode], 'log_message': [ignore_missing, unicode, no_http], 'private': [ignore_missing, boolean_validator, - datasets_with_no_organization_cannot_be_private], + datasets_with_no_organization_cannot_be_private], '__extras': [ignore], '__junk': [empty], 'resources': default_resource_schema(), @@ -174,6 +174,7 @@ def default_create_package_schema(): } return schema + def default_update_package_schema(): schema = default_create_package_schema() @@ -186,7 +187,7 @@ def default_update_package_schema(): # Supplying the package name when updating a package is optional (you can # supply the id to identify the package instead). schema['name'] = [ignore_missing, name_validator, package_name_validator, - unicode] + unicode] # Supplying the package title when updating a package is optional, if it's # not supplied the title will not be changed. @@ -196,6 +197,7 @@ def default_update_package_schema(): return schema + def default_show_package_schema(): schema = default_create_package_schema() @@ -203,22 +205,20 @@ def default_show_package_schema(): schema['id'] = [] schema.update({ - 'tags': {'__extras': [ckan.lib.navl.validators.keep_extras]}}) + 'tags': {'__extras': [keep_extras]}}) # Add several keys to the 'resources' subschema so they don't get stripped # from the resource dicts by validation. schema['resources'].update({ 'format': [ignore_missing, clean_format, unicode], - 'created': [ckan.lib.navl.validators.ignore_missing], + 'created': [ignore_missing], 'position': [not_empty], - 'last_modified': [ckan.lib.navl.validators.ignore_missing], - 'cache_last_updated': [ckan.lib.navl.validators.ignore_missing], + 'last_modified': [], + 'cache_last_updated': [], 'revision_id': [], 'package_id': [], - 'cache_last_updated': [], 'size': [], 'state': [], - 'last_modified': [], 'mimetype': [], 'cache_url': [], 'name': [], @@ -228,17 +228,17 @@ def default_show_package_schema(): }) schema.update({ - 'state': [ckan.lib.navl.validators.ignore_missing], + 'state': [ignore_missing], 'isopen': [ignore_missing], 'license_url': [ignore_missing], 'revision_id': [], - }) + }) schema['groups'].update({ 'description': [ignore_missing], 'display_name': [ignore_missing], 'image_display_url': [ignore_missing], - }) + }) # Remove validators for several keys from the schema so validation doesn't # strip the keys from the package dicts if the values are 'missing' (i.e. @@ -252,8 +252,8 @@ def default_show_package_schema(): schema['url'] = [] schema['version'] = [] - # Add several keys that are missing from default_create_package_schema(), so - # validation doesn't strip the keys from the package dicts. + # Add several keys that are missing from default_create_package_schema(), + # so validation doesn't strip the keys from the package dicts. schema['metadata_created'] = [] schema['metadata_modified'] = [] schema['creator_user_id'] = [] @@ -268,8 +268,8 @@ def default_show_package_schema(): return schema -def default_group_schema(): +def default_group_schema(): schema = { 'id': [ignore_missing, unicode], 'revision_id': [ignore], @@ -288,8 +288,8 @@ def default_group_schema(): '__junk': [ignore], 'packages': { "id": [not_empty, unicode, package_id_or_name_exists], - "title":[ignore_missing, unicode], - "name":[ignore_missing, unicode], + "title": [ignore_missing, unicode], + "name": [ignore_missing, unicode], "__extras": [ignore] }, 'users': { @@ -305,9 +305,10 @@ def default_group_schema(): } return schema + def group_form_schema(): schema = default_group_schema() - #schema['extras_validation'] = [duplicate_extras_key, ignore] + # schema['extras_validation'] = [duplicate_extras_key, ignore] schema['packages'] = { "name": [not_empty, unicode], "title": [ignore_missing], @@ -327,6 +328,7 @@ def default_update_group_schema(): schema["name"] = [ignore_missing, group_name_validator, unicode] return schema + def default_show_group_schema(): schema = default_group_schema() @@ -334,17 +336,17 @@ def default_show_group_schema(): schema['num_followers'] = [] schema['created'] = [] schema['display_name'] = [] - schema['extras'] = {'__extras': [ckan.lib.navl.validators.keep_extras]} + schema['extras'] = {'__extras': [keep_extras]} schema['package_count'] = [] - schema['packages'] = {'__extras': [ckan.lib.navl.validators.keep_extras]} + schema['packages'] = {'__extras': [keep_extras]} schema['revision_id'] = [] schema['state'] = [] - schema['users'] = {'__extras': [ckan.lib.navl.validators.keep_extras]} + schema['users'] = {'__extras': [keep_extras]} return schema -def default_extras_schema(): +def default_extras_schema(): schema = { 'id': [ignore], 'key': [not_empty, extra_key_not_in_root_schema, unicode], @@ -356,20 +358,21 @@ def default_extras_schema(): } return schema -def default_relationship_schema(): +def default_relationship_schema(): schema = { - 'id': [ignore_missing, unicode], - 'subject': [ignore_missing, unicode], - 'object': [ignore_missing, unicode], - 'type': [not_empty, OneOf(ckan.model.PackageRelationship.get_all_types())], - 'comment': [ignore_missing, unicode], - 'state': [ignore], + 'id': [ignore_missing, unicode], + 'subject': [ignore_missing, unicode], + 'object': [ignore_missing, unicode], + 'type': [not_empty, + OneOf(ckan.model.PackageRelationship.get_all_types())], + 'comment': [ignore_missing, unicode], + 'state': [ignore], } return schema -def default_create_relationship_schema(): +def default_create_relationship_schema(): schema = default_relationship_schema() schema['id'] = [empty] schema['subject'] = [not_empty, unicode, package_id_or_name_exists] @@ -377,8 +380,8 @@ def default_create_relationship_schema(): return schema -def default_update_relationship_schema(): +def default_update_relationship_schema(): schema = default_relationship_schema() schema['id'] = [ignore_missing, package_id_not_changed] @@ -391,15 +394,13 @@ def default_update_relationship_schema(): return schema - - def default_user_schema(): - schema = { 'id': [ignore_missing, unicode], 'name': [not_empty, name_validator, user_name_validator, unicode], 'fullname': [ignore_missing, unicode], - 'password': [user_password_validator, user_password_not_empty, ignore_missing, unicode], + 'password': [user_password_validator, user_password_not_empty, + ignore_missing, unicode], 'password_hash': [ignore_missing, ignore_not_sysadmin, unicode], 'email': [not_empty, unicode], 'about': [ignore_missing, user_about_validator, unicode], @@ -413,37 +414,45 @@ def default_user_schema(): } return schema + def user_new_form_schema(): schema = default_user_schema() - schema['password1'] = [unicode,user_both_passwords_entered,user_password_validator,user_passwords_match] + schema['password1'] = [unicode, user_both_passwords_entered, + user_password_validator, user_passwords_match] schema['password2'] = [unicode] return schema + def user_edit_form_schema(): schema = default_user_schema() schema['password'] = [ignore_missing] - schema['password1'] = [ignore_missing,unicode,user_password_validator,user_passwords_match] - schema['password2'] = [ignore_missing,unicode] + schema['password1'] = [ignore_missing, unicode, user_password_validator, + user_passwords_match] + schema['password2'] = [ignore_missing, unicode] return schema + def default_update_user_schema(): schema = default_user_schema() - schema['name'] = [ignore_missing, name_validator, user_name_validator, unicode] - schema['password'] = [user_password_validator,ignore_missing, unicode] + schema['name'] = [ignore_missing, name_validator, user_name_validator, + unicode] + schema['password'] = [user_password_validator, ignore_missing, unicode] return schema + def default_generate_apikey_user_schema(): schema = default_update_user_schema() schema['apikey'] = [not_empty, unicode] return schema + def default_user_invite_schema(): schema = { 'email': [not_empty, unicode], @@ -452,6 +461,7 @@ def default_user_invite_schema(): } return schema + def default_task_status_schema(): schema = { 'id': [ignore], @@ -466,6 +476,7 @@ def default_task_status_schema(): } return schema + def default_vocabulary_schema(): schema = { 'id': [ignore_missing, unicode, vocabulary_id_exists], @@ -474,41 +485,46 @@ def default_vocabulary_schema(): } return schema + def default_create_vocabulary_schema(): schema = default_vocabulary_schema() schema['id'] = [empty] return schema + def default_update_vocabulary_schema(): schema = default_vocabulary_schema() schema['id'] = [ignore_missing, vocabulary_id_not_changed] schema['name'] = [ignore_missing, vocabulary_name_validator] return schema + def default_create_activity_schema(): schema = { 'id': [ignore], 'timestamp': [ignore], 'user_id': [not_missing, not_empty, unicode, - convert_user_name_or_id_to_id], + convert_user_name_or_id_to_id], 'object_id': [not_missing, not_empty, unicode, object_id_validator], # We don't bother to validate revision ID, since it's always created # internally by the activity_create() logic action function. 'revision_id': [], 'activity_type': [not_missing, not_empty, unicode, - activity_type_exists], + activity_type_exists], 'data': [ignore_empty, ignore_missing], } return schema + def default_follow_user_schema(): schema = {'id': [not_missing, not_empty, unicode, - convert_user_name_or_id_to_id]} + convert_user_name_or_id_to_id]} return schema + def default_follow_dataset_schema(): schema = {'id': [not_missing, not_empty, unicode, - convert_package_name_or_id_to_id]} + convert_package_name_or_id_to_id]} return schema @@ -523,7 +539,7 @@ def member_schema(): def default_follow_group_schema(): schema = {'id': [not_missing, not_empty, unicode, - convert_group_name_or_id_to_id]} + convert_group_name_or_id_to_id]} return schema @@ -576,8 +592,9 @@ def default_package_search_schema(): 'facet.mincount': [ignore_missing, natural_number_validator], 'facet.limit': [ignore_missing, int_validator], 'facet.field': [ignore_missing, convert_to_json_if_string, - list_of_strings], - 'extras': [ignore_missing] # Not used by Solr, but useful for extensions + list_of_strings], + 'extras': [ignore_missing] # Not used by Solr, + # but useful for extensions } return schema @@ -627,14 +644,13 @@ def default_update_resource_view_schema(resource_view): 'id': [not_missing, not_empty, unicode], 'resource_id': [ignore_missing, resource_id_exists], 'title': [ignore_missing, unicode], - 'view_type': [ignore],# can not change after create + 'view_type': [ignore], # cannot change after create 'package_id': [ignore] }) return schema def default_update_configuration_schema(): - schema = { 'ckan.site_title': [unicode], 'ckan.site_logo': [unicode],
diff --git a/ckan/tests/legacy/test_coding_standards.py b/ckan/tests/legacy/test_coding_standards.py --- a/ckan/tests/legacy/test_coding_standards.py +++ b/ckan/tests/legacy/test_coding_standards.py @@ -415,7 +415,6 @@ class TestPep8(object): 'ckan/logic/auth/get.py', 'ckan/logic/auth/update.py', 'ckan/logic/converters.py', - 'ckan/logic/schema.py', 'ckan/logic/validators.py', 'ckan/migration/versions/001_add_existing_tables.py', 'ckan/migration/versions/002_add_author_and_maintainer.py',
ckan.logic.schema file is messy There are a couple of pep8/style issues in [ckan/logic/schema.py](https://github.com/ckan/ckan/blob/master/ckan/logic/schema.py) They are mainly - [x] unsued imports - [x] not 2 lines between functions - [x] dictionaries with duplicate keys I will clean those in three separate commits and then tick them off here. The last checkbox probably needs some explanation: [here](https://github.com/ckan/ckan/blob/master/ckan/logic/schema.py#L210) we call `update` on a dictionary and pass it a new dictionary. The new one contains the keys `cache_last_updated` and `last_modified` twice so that the second empty declarations overwrite the first one. I assume that the values that actually contain something are the ones that are wanted and will remove the empty ones in favor of them.
2016-05-25T14:57:52
ckan/ckan
3,061
ckan__ckan-3061
[ "3011" ]
dd8551949005d30a7b0372bf2013b7816881d75d
diff --git a/ckan/logic/action/create.py b/ckan/logic/action/create.py --- a/ckan/logic/action/create.py +++ b/ckan/logic/action/create.py @@ -316,6 +316,16 @@ def resource_create(context, data_dict): updated_pkg_dict = _get_action('package_show')(context, {'id': package_id}) resource = updated_pkg_dict['resources'][-1] + ## Add the default views to the new resource + logic.get_action('resource_create_default_resource_views')( + {'model': context['model'], + 'user': context['user'], + 'ignore_auth': True + }, + {'resource': resource, + 'package': updated_pkg_dict + }) + for plugin in plugins.PluginImplementations(plugins.IResourceController): plugin.after_create(context, resource) diff --git a/ckan/logic/action/update.py b/ckan/logic/action/update.py --- a/ckan/logic/action/update.py +++ b/ckan/logic/action/update.py @@ -307,13 +307,6 @@ def package_update(context, data_dict): item.after_update(context, data) - # Create default views for resources if necessary - if data.get('resources'): - logic.get_action('package_create_default_resource_views')( - {'model': context['model'], 'user': context['user'], - 'ignore_auth': True}, - {'package': data}) - if not context.get('defer_commit'): model.repo.commit() diff --git a/ckanext/reclineview/plugin.py b/ckanext/reclineview/plugin.py --- a/ckanext/reclineview/plugin.py +++ b/ckanext/reclineview/plugin.py @@ -62,7 +62,7 @@ def update_config(self, config): def can_view(self, data_dict): resource = data_dict['resource'] return (resource.get('datastore_active') or - resource.get('url') == '_datastore_only_resource') + '_datastore_only_resource' in resource.get('url', '')) def setup_template_variables(self, context, data_dict): return {'resource_json': json.dumps(data_dict['resource']), @@ -90,7 +90,7 @@ def can_view(self, data_dict): resource = data_dict['resource'] if (resource.get('datastore_active') or - resource.get('url') == '_datastore_only_resource'): + '_datastore_only_resource' in resource.get('url', '')): return True resource_format = resource.get('format', None) if resource_format:
diff --git a/ckan/tests/lib/test_datapreview.py b/ckan/tests/lib/test_datapreview.py --- a/ckan/tests/lib/test_datapreview.py +++ b/ckan/tests/lib/test_datapreview.py @@ -271,50 +271,6 @@ def test_default_views_created_on_package_create(self): eq_(len(views_list), 1) eq_(views_list[0]['view_type'], 'image_view') - def test_default_views_created_on_package_update(self): - - dataset_dict = factories.Dataset( - resources=[{ - 'url': 'http://not.for.viewing', - 'format': 'xxx', - }] - ) - - resource_id = dataset_dict['resources'][0]['id'] - - views_list = helpers.call_action('resource_view_list', id=resource_id) - - eq_(len(views_list), 0) - - updated_data_dict = { - 'id': dataset_dict['id'], - 'resources': [ - { - 'url': 'http://not.for.viewing', - 'format': 'xxx', - }, - { - 'url': 'http://some.image.png', - 'format': 'png', - }, - - - ] - } - - dataset_dict = helpers.call_action('package_update', **updated_data_dict) - - for resource in dataset_dict['resources']: - resource_id = resource['id'] if resource['format'] == 'PNG' else None - - assert resource_id - - updated_views_list = helpers.call_action('resource_view_list', id=resource_id) - eq_(len(updated_views_list), 1) - eq_(updated_views_list[0]['view_type'], 'image_view') - - pass - def test_default_views_created_on_resource_create(self): dataset_dict = factories.Dataset( @@ -336,32 +292,3 @@ def test_default_views_created_on_resource_create(self): eq_(len(views_list), 1) eq_(views_list[0]['view_type'], 'image_view') - - def test_default_views_created_on_resource_update(self): - - dataset_dict = factories.Dataset( - resources=[{ - 'url': 'http://not.for.viewing', - 'format': 'xxx', - }] - ) - - resource_id = dataset_dict['resources'][0]['id'] - - views_list = helpers.call_action('resource_view_list', id=resource_id) - - eq_(len(views_list), 0) - - resource_dict = { - 'id': resource_id, - 'package_id': dataset_dict['id'], - 'url': 'http://some.image.png', - 'format': 'png', - } - - updated_resource_dict = helpers.call_action('resource_update', **resource_dict) - - views_list = helpers.call_action('resource_view_list', id=updated_resource_dict['id']) - - eq_(len(views_list), 1) - eq_(views_list[0]['view_type'], 'image_view')
Default view is re-added when removed before DataStore upload is complete I'm doing the following via the API on a CKAN 2.5.2 installation that has DataStore + DataPusher enabled: 1. Create a CSV resource 2. Remove the default `recline_view` 3. Add a new `recline_grid_view` view I'd expect the resource to end up with a single view (the one I added in step 3). However, it ends up with _two_ views: the one I created and a _new_ default view (ID is different from the original default view). It seems that the default view is added again once the data has been uploaded to the DataStore by the DataPusher. If steps 1-3 are done quickly enough (before the upload to the DataStore has completed) then the resource has only the intended `recline_grid_view`, which at that point shows an error (because the data is not yet available). As soon as the data is available (i.e. as soon as the error is gone after a reload) the resource has gotten an additional `recline_view`. Here's a small script to demonstrate the problem: ``` python ckan = ckanapi.RemoteCKAN(CKAN_URL, apikey=API_KEY) res_dict = ckan.action.resource_create(package_id=PKG_ID, url=CSV_URL, name='Test', format='CSV') view_dicts = ckan.action.resource_view_list(id=res_dict['id']) for view_dict in view_dicts: ckan.action.resource_view_delete(id=view_dict['id']) ckan.action.resource_view_create(resource_id=res_dict['id'], title='My View', view_type='recline_grid_view') # Uncomment to make assertion fail #import time #time.sleep(10) assert len(ckan.action.resource_view_list(id=res_dict['id'])) == 1 ``` If you uncomment the `sleep` lines (to wait until the data is in the DataStore) then the assertion fails.
This is another side-effect of #2234 (which I'm very much starting to regret to ever have implemented). Essentially we added a call to `resource_patch` on `datastore_create` to set the `datastore_active` extra on the resource. So what happens is: - Resource is created, default views are created - You delete the default view you don't want - In the meantime, DataPusher is doing its thing - When the data is uploaded to the DataStore, `datastore_create` calls `resource_patch` (to set up the `datastore_active` extra) which calls `resource_update` which calls `package_update` which calls `package_create_default_resource_views` and recreates the view. @wardi I know you hate it but the only thing I can think of is passing a `create_views = False` entry on the context that ends up in `package_update` and avoids the default views creation. @torfsen I know it's not ideal but on the meantime you can delete the extra view via the API if you are doing it as part of a script So datapusher is deleting and recreating the datastore table. That shows up as a new table so the default views are created, or are we calling package_create_default_resource_views on every package_update? > are we calling package_create_default_resource_views on every package_update? This. It has no relation with the DataPusher creating or dropping tables, other than it triggers an update when it imports data to the DataStore So.. anyone editing a dataset will cause all the default resource views to reappear too, right? We need something like a white-out for resource views that have been removed so they don't get re-added, or we just need to me more selective about when that code is run, not on every package_update You are right. Neither of the two options are easy as things stand right now. Views are not marked as deleted on the DB, they are just removed entirely so the white-out option is probably the hardest. Thinking on when we want default views to be created, I think the most common cases are: - Creating a package (if resources are provided, ie creating it via the API or a custom combined form) - Creating resource on an existing package (like on the default UI) - When we finish pushing data to the DataStore (DataPusher does that now) So just on `package_create`, `resource_create` and `datapusher_hook`. If we only cover these cases, and not any updates we will miss situations like people changing the format of a resource and new views for that format not appearing, but that might be preferable to the current behaviour. :+1: That sounds like a simpler solution. @torfsen Do you have time to work on patch along those lines? @k-nut this is also a good one to get an introduction about how DataPusher / DataStore / Resource views work @amercader Sorry, I'm currently busy with other stuff. As a workaround I'm currently polling [`datastore_info`](http://docs.ckan.org/en/latest/maintaining/datastore.html#ckanext.datastore.logic.action.datastore_info) until the resource has been uploaded to the datastore before deleting the default views. @amercader I am taking a look at this now.
2016-05-26T10:40:24
ckan/ckan
3,065
ckan__ckan-3065
[ "3060" ]
ed2196b31421365fc559eb8e0fa9141fa17a057f
diff --git a/ckan/config/environment.py b/ckan/config/environment.py --- a/ckan/config/environment.py +++ b/ckan/config/environment.py @@ -8,6 +8,7 @@ import sqlalchemy from pylons import config +import formencode import ckan.config.routing as routing import ckan.model as model @@ -199,6 +200,12 @@ def update_config(): template_paths = extra_template_paths.split(',') + template_paths config['pylons.app_globals'].template_paths = template_paths + # Set the default language for validation messages from formencode + # to what is set as the default locale in the config + default_lang = config.get('ckan.locale_default', 'en') + formencode.api.set_stdtranslation(domain="FormEncode", + languages=[default_lang]) + # Markdown ignores the logger config, so to get rid of excessive # markdown debug messages in the log, set it to the level of the # root logger. diff --git a/ckan/lib/navl/dictization_functions.py b/ckan/lib/navl/dictization_functions.py --- a/ckan/lib/navl/dictization_functions.py +++ b/ckan/lib/navl/dictization_functions.py @@ -6,6 +6,7 @@ from ckan.common import _ + class Missing(object): def __unicode__(self): raise Invalid(_('Missing value'))
diff --git a/ckan/tests/lib/test_navl.py b/ckan/tests/lib/test_navl.py new file mode 100644 --- /dev/null +++ b/ckan/tests/lib/test_navl.py @@ -0,0 +1,30 @@ +import nose +import pylons + +from ckan.tests import helpers +from ckan.config import environment + +eq_ = nose.tools.eq_ + + +class TestFormencdoeLanguage(object): + @helpers.change_config('ckan.locale_default', 'de') + def test_formencode_uses_locale_default(self): + environment.update_config() + from ckan.lib.navl.dictization_functions import validate + from ckan.lib.navl.validators import not_empty + from formencode import validators + schema = { + "name": [not_empty, unicode], + "email": [validators.Email], + "email2": [validators.Email], + } + + data = { + "name": "fred", + "email": "32", + "email2": "[email protected]", + } + + converted_data, errors = validate(data, schema) + eq_({'email': [u'Eine E-Mail-Adresse muss genau ein @-Zeichen enthalten']}, errors)
Tests fail when LANG environment variable is set to German ### CKAN Version if known (or site URL) 2.6.0a ### Please describe the expected behaviour All the tests on master pass ### Please describe the actual behaviour Two tests in `/ckan/tests/legacy/lib/test_navl.py` are failing. Output: ``` ..........FF ====================================================================== FAIL: ckan.tests.legacy.lib.test_navl.test_formencode_compat ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/knut/.virtualenvs/ckan/lib/python2.7/site-packages/nose/case.py", line 197, in runTest self.test(*self.arg) File "/Users/knut/viderum/ckan/ckan/tests/legacy/lib/test_navl.py", line 334, in test_formencode_compat assert errors == {'email': [u'An email address must contain a single @']}, errors AssertionError: {'email': [u'Eine E-Mail-Adresse muss genau ein @-Zeichen enthalten']} ====================================================================== FAIL: ckan.tests.legacy.lib.test_navl.test_range_validator ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/knut/.virtualenvs/ckan/lib/python2.7/site-packages/nose/case.py", line 197, in runTest self.test(*self.arg) File "/Users/knut/viderum/ckan/ckan/tests/legacy/lib/test_navl.py", line 350, in test_range_validator assert errors == {'name': [u'Missing value'], 'email': [u'Please enter a number that is 10 or smaller']}, errors AssertionError: {'email': [u'Bitte geben Sie eine Zahl ein, die kleiner oder gleich 10 ist'], 'name': [u'Missing value']} ``` When run with `LANG` set to `en_US.UTF-8` the tests pass: ``` user@host:$ LANG="en_US.UTF-8" nosetests --ckan --with-pylons=test-core.ini ckan/tests/legacy/lib/test_navl.py ``` ``` ............ ---------------------------------------------------------------------- Ran 12 tests in 0.005s OK ``` ### What steps can be taken to reproduce the issue? Run the tests with a non English `LANG`: ``` LANG="de_DE.UTF-8" nosetests --ckan --with-pylons=test-core.ini ckan/tests/legacy/lib/test_navl.py ```
Point 3 from [this part](http://www.formencode.org/en/latest/Validator.html#localization-of-error-messages-i18n) of the documentation of formencode seems to be relevant here.
2016-05-27T09:44:13
ckan/ckan
3,080
ckan__ckan-3080
[ "3073" ]
e171528b8e4a9220dd3b2245a4b2a0a7d1a64a07
diff --git a/ckan/lib/i18n.py b/ckan/lib/i18n.py --- a/ckan/lib/i18n.py +++ b/ckan/lib/i18n.py @@ -1,7 +1,9 @@ import os -from babel import Locale, localedata -from babel.core import LOCALE_ALIASES, get_locale_identifier +from babel import Locale +from babel.core import (LOCALE_ALIASES, + get_locale_identifier, + UnknownLocaleError) from babel.support import Translations from paste.deploy.converters import aslist from pylons import config @@ -48,7 +50,18 @@ def _get_locales(): i18n_path = os.path.join(config.get('ckan.i18n_directory'), 'i18n') else: i18n_path = os.path.dirname(ckan.i18n.__file__) - locales += [l for l in os.listdir(i18n_path) if localedata.exists(l)] + + # For every file in the ckan i18n directory see if babel can understand + # the locale. If yes, add it to the available locales + for locale in os.listdir(i18n_path): + try: + Locale.parse(locale) + locales.append(locale) + except (ValueError, UnknownLocaleError): + # Babel does not know how to make a locale out of this. + # This is fine since we are passing all files in the + # ckan.i18n_directory here which e.g. includes the __init__.py + pass assert locale_default in locales, \ 'default language "%s" not available' % locale_default @@ -123,11 +136,21 @@ def get_available_locales(): e.g. [ Locale('en'), Locale('de'), ... ] ''' global available_locales if not available_locales: - available_locales = map(Locale.parse, get_locales()) - # Add the full identifier (eg `pt_BR`) to the locale classes, as it does - # not offer a way of accessing it directly - for locale in available_locales: - setattr(locale, 'identifier', get_identifier_from_locale_class(locale)) + available_locales = [] + for locale in get_locales(): + # Add the short names for the locales. This equals the filename + # of the ckan translation files as opposed to the long name + # that includes the script which is generated by babel + # so e.g. `zn_CH` instead of `zn_Hans_CH` this is needed + # to properly construct urls with url_for + parsed_locale = Locale.parse(locale) + parsed_locale.short_name = locale + + # Add the full identifier (eg `pt_BR`) to the locale classes, + # as it does not offer a way of accessing it directly + parsed_locale.identifier = \ + get_identifier_from_locale_class(parsed_locale) + available_locales.append(parsed_locale) return available_locales
Chinese (zh_CN and zh_TW) can not be used on a source install CKAN Version if known: master Setting up `ckan.locale_default = zh_CN` fails with `AssertionError: default language "zh_CN" not available`. `zh_CN` and `zh_TW` are the locale codes used on Transifex. [This check](https://github.com/ckan/ckan/blob/master/ckan/lib/i18n.py#L51:L53) fails. The folder where babel keeps the locale data files (`<virtualenv>/lib/python2.7/site-packages/babel/locale-data`) has different codes for the Chinese locales. Bizarrely this works on the package install (2.5.x), ie the `zh_CN.dat` files are there. Not sure if it's related to the recent upgrade to Babel (#3004) or something specific with the package install (seems unlikely) Probably related to https://github.com/python-babel/babel/pull/25
2016-06-02T08:23:04
ckan/ckan
3,082
ckan__ckan-3082
[ "2863" ]
e171528b8e4a9220dd3b2245a4b2a0a7d1a64a07
diff --git a/ckan/controllers/user.py b/ckan/controllers/user.py --- a/ckan/controllers/user.py +++ b/ckan/controllers/user.py @@ -166,7 +166,8 @@ def new(self, data=None, errors=None, error_summary=None): '''GET to display a form for registering a new user. or POST the form data to actually do the user registration. ''' - context = {'model': model, 'session': model.Session, + context = {'model': model, + 'session': model.Session, 'user': c.user, 'auth_user_obj': c.userobj, 'schema': self._new_form_to_db_schema(), @@ -180,7 +181,7 @@ def new(self, data=None, errors=None, error_summary=None): if context['save'] and not data: return self._save_new(context) - if c.user and not data: + if c.user and not data and not authz.is_sysadmin(c.user): # #1799 Don't offer the registration form if already logged in return render('user/logout_first.html') @@ -264,7 +265,14 @@ def _save_new(self, context): h.flash_success(_('User "%s" is now registered but you are still ' 'logged in as "%s" from before') % (data_dict['name'], c.user)) - return render('user/logout_first.html') + if authz.is_sysadmin(c.user): + # the sysadmin created a new user. We redirect him to the + # activity page for the newly created user + h.redirect_to(controller='user', + action='activity', + id=data_dict['name']) + else: + return render('user/logout_first.html') def edit(self, id=None, data=None, errors=None, error_summary=None): context = {'save': 'save' in request.params,
diff --git a/ckan/tests/controllers/test_user.py b/ckan/tests/controllers/test_user.py --- a/ckan/tests/controllers/test_user.py +++ b/ckan/tests/controllers/test_user.py @@ -59,6 +59,37 @@ def test_register_user_bad_password(self): response = form.submit('save') assert_true('The passwords you entered do not match' in response) + def test_create_user_as_sysadmin(self): + admin_pass = 'pass' + sysadmin = factories.Sysadmin(password=admin_pass) + app = self._get_test_app() + + # Have to do an actual login as this test relies on repoze + # cookie handling. + + # get the form + response = app.get('/user/login') + # ...it's the second one + login_form = response.forms[1] + # fill it in + login_form['login'] = sysadmin['name'] + login_form['password'] = admin_pass + # submit it + login_form.submit('save') + + response = app.get( + url=url_for(controller='user', action='register'), + ) + assert "user-register-form" in response.forms + form = response.forms['user-register-form'] + form['name'] = 'newestuser' + form['fullname'] = 'Newest User' + form['email'] = '[email protected]' + form['password1'] = 'testpassword' + form['password2'] = 'testpassword' + response2 = form.submit('save') + assert '/user/activity' in response2.location + class TestLoginView(helpers.FunctionalTestBase): def test_registered_user_login(self):
Allow Sysadmins to create users with the form (Even if create_user_from_web is false). I've come across several workflows where people wanted a centralised administrator to be the **only** person able to create accounts. This change allows that. Everything else works perfectly. I can offer more detail later on - I'm just in a rush at the moment. Cheers, Carl
This is good, but would you add a small test so that the behaviour doesn't change accidentally in the future. Also, redirecting to the user just created would be better than rendering the logout_first page when a sysadmin finishes creating the user. Yep, will do. And I agree, that makes sense. Will add those changes tomorrow. Thanks for getting back to be so fast! @CarlQLange did you ever get around to doing this? I just created a small test case that makes sure this works. I could provide it unless you already have anything?
2016-06-02T12:42:39
ckan/ckan
3,090
ckan__ckan-3090
[ "3089" ]
debc9fb032a97a24fe1f6c60fe0ad4e3e0f2a9e2
diff --git a/ckan/config/middleware.py b/ckan/config/middleware.py --- a/ckan/config/middleware.py +++ b/ckan/config/middleware.py @@ -88,6 +88,8 @@ def make_pylons_stack(conf, full_stack=True, static_files=True, **app_conf): for plugin in PluginImplementations(IMiddleware): app = plugin.make_middleware(app, config) + app = RootPathMiddleware(app, config) + # Routing/Session/Cache Middleware app = RoutesMiddleware(app, config['routes.map']) # we want to be able to retrieve the routes middleware to be able to update @@ -200,8 +202,6 @@ def make_pylons_stack(conf, full_stack=True, static_files=True, **app_conf): if asbool(config.get('ckan.tracking_enabled', 'false')): app = TrackingMiddleware(app, config) - app = RootPathMiddleware(app, config) - return app
Login fails with 404 when using root_path On master under Apache 2.2.4 and mod_wsgi with CKAN mounted at /data (`WSGIScriptAlias /data ...` and `ckan.root_path = /data`) on submitting the login form user is redirected to `/user/logged_in` (i.e., without the root_path) and Apache returns a 404.
2016-06-04T07:22:56
ckan/ckan
3,099
ckan__ckan-3099
[ "3097", "3097" ]
c148f45647cd7e2c07e9a8ddfb3bd8ac1dfc4c35
diff --git a/ckan/logic/__init__.py b/ckan/logic/__init__.py --- a/ckan/logic/__init__.py +++ b/ckan/logic/__init__.py @@ -343,6 +343,12 @@ def get_action(action): If a ``context`` of ``None`` is passed to the action function then the default context dict will be created. + .. note:: + + Many action functions modify the context dict. It can therefore + not be reused for multiple calls of the same or different action + functions. + :param action: name of the action function to return, eg. ``'package_create'`` :type action: string
package_create keeps re-creating the same package This is on CKAN 2.5.2: ``` python package_create = toolkit.get_action('package_create') context = {'ignore_auth': True} for i in range(10): pkg_dict = package_create(context, { 'name': 'my-package-{}'.format(i), 'owner_org': 'my-org', }) print('{}: {}'.format(i, pkg_dict['id'])) ``` prints ``` 0: 1d6d50df-3c55-434f-ba8f-375e95938830 1: 1d6d50df-3c55-434f-ba8f-375e95938830 2: 1d6d50df-3c55-434f-ba8f-375e95938830 3: 1d6d50df-3c55-434f-ba8f-375e95938830 4: 1d6d50df-3c55-434f-ba8f-375e95938830 5: 1d6d50df-3c55-434f-ba8f-375e95938830 6: 1d6d50df-3c55-434f-ba8f-375e95938830 7: 1d6d50df-3c55-434f-ba8f-375e95938830 8: 1d6d50df-3c55-434f-ba8f-375e95938830 9: 1d6d50df-3c55-434f-ba8f-375e95938830 ``` I was expecting 10 separate packages instead. package_create keeps re-creating the same package This is on CKAN 2.5.2: ``` python package_create = toolkit.get_action('package_create') context = {'ignore_auth': True} for i in range(10): pkg_dict = package_create(context, { 'name': 'my-package-{}'.format(i), 'owner_org': 'my-org', }) print('{}: {}'.format(i, pkg_dict['id'])) ``` prints ``` 0: 1d6d50df-3c55-434f-ba8f-375e95938830 1: 1d6d50df-3c55-434f-ba8f-375e95938830 2: 1d6d50df-3c55-434f-ba8f-375e95938830 3: 1d6d50df-3c55-434f-ba8f-375e95938830 4: 1d6d50df-3c55-434f-ba8f-375e95938830 5: 1d6d50df-3c55-434f-ba8f-375e95938830 6: 1d6d50df-3c55-434f-ba8f-375e95938830 7: 1d6d50df-3c55-434f-ba8f-375e95938830 8: 1d6d50df-3c55-434f-ba8f-375e95938830 9: 1d6d50df-3c55-434f-ba8f-375e95938830 ``` I was expecting 10 separate packages instead.
Never reuse the context dict. There are side effects in the action calls that are carried from one call to the next (that's why ckanapi.LocalCKAN creates a new context for you on every call) Ah, makes a lot of sense, but I never thought about it. My code works fine if I pass a new context dict for each call. I'll prepare a PR for updating the documentation of [`get_action`](http://docs.ckan.org/en/latest/extensions/plugins-toolkit.html#ckan.plugins.toolkit.get_action) to mention this. Never reuse the context dict. There are side effects in the action calls that are carried from one call to the next (that's why ckanapi.LocalCKAN creates a new context for you on every call) Ah, makes a lot of sense, but I never thought about it. My code works fine if I pass a new context dict for each call. I'll prepare a PR for updating the documentation of [`get_action`](http://docs.ckan.org/en/latest/extensions/plugins-toolkit.html#ckan.plugins.toolkit.get_action) to mention this.
2016-06-08T14:18:54
ckan/ckan
3,127
ckan__ckan-3127
[ "3126" ]
9fb9f576003578674223b57cf9175cb07b27a4d9
diff --git a/ckan/lib/util.py b/ckan/lib/util.py deleted file mode 100644 --- a/ckan/lib/util.py +++ /dev/null @@ -1,47 +0,0 @@ -# encoding: utf-8 - -'''Shared utility functions for any Python code to use. - -Unlike :py:mod:`ckan.lib.helpers`, the functions in this module are not -available to templates. - -''' -import subprocess - - -# We implement our own check_output() function because -# subprocess.check_output() isn't in Python 2.6. -# This code is copy-pasted from Python 2.7 and adapted to make it work with -# Python 2.6. -# http://hg.python.org/cpython/file/d37f963394aa/Lib/subprocess.py#l544 -def check_output(*popenargs, **kwargs): - r"""Run command with arguments and return its output as a byte string. - - If the exit code was non-zero it raises a CalledProcessError. The - CalledProcessError object will have the return code in the returncode - attribute and output in the output attribute. - - The arguments are the same as for the Popen constructor. Example: - - >>> check_output(["ls", "-l", "/dev/null"]) - 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' - - The stdout argument is not allowed as it is used internally. - To capture standard error in the result, use stderr=STDOUT. - - >>> check_output(["/bin/sh", "-c", - ... "ls -l non_existent_file ; exit 0"], - ... stderr=STDOUT) - 'ls: non_existent_file: No such file or directory\n' - """ - if 'stdout' in kwargs: - raise ValueError('stdout argument not allowed, it will be overridden.') - process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs) - output, unused_err = process.communicate() - retcode = process.poll() - if retcode: - cmd = kwargs.get("args") - if cmd is None: - cmd = popenargs[0] - raise subprocess.CalledProcessError(retcode, cmd) - return output diff --git a/ckan/model/extension.py b/ckan/model/extension.py --- a/ckan/model/extension.py +++ b/ckan/model/extension.py @@ -4,23 +4,17 @@ Provides bridges between the model and plugin PluginImplementationss """ import logging +from operator import methodcaller from sqlalchemy.orm.interfaces import MapperExtension from sqlalchemy.orm.session import SessionExtension import ckan.plugins as plugins -try: - from operator import methodcaller -except ImportError: - def methodcaller(name, *args, **kwargs): - "Replaces stdlib operator.methodcaller in python <2.6" - def caller(obj): - return getattr(obj, name)(*args, **kwargs) - return caller log = logging.getLogger(__name__) + class ObserverNotifier(object): """ Mixin for hooking into SQLAlchemy @@ -93,7 +87,6 @@ def notify_observers(self, func): for observer in plugins.PluginImplementations(plugins.ISession): func(observer) - def after_begin(self, session, transaction, connection): return self.notify_observers( methodcaller('after_begin', session, transaction, connection) @@ -123,4 +116,3 @@ def after_rollback(self, session): return self.notify_observers( methodcaller('after_rollback', session) ) - diff --git a/doc/conf.py b/doc/conf.py --- a/doc/conf.py +++ b/doc/conf.py @@ -18,8 +18,6 @@ import os import subprocess -import ckan.lib.util as util - # If your extensions (or modules documented by autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. @@ -126,7 +124,7 @@ def latest_release_tag(): This requires git to be installed. ''' - git_tags = util.check_output( + git_tags = subprocess.check_output( ['git', 'tag', '-l'], stderr=subprocess.STDOUT).split() # FIXME: We could do more careful pattern matching against ckan-X.Y.Z here.
diff --git a/ckan/tests/controllers/test_api.py b/ckan/tests/controllers/test_api.py --- a/ckan/tests/controllers/test_api.py +++ b/ckan/tests/controllers/test_api.py @@ -7,10 +7,9 @@ import json from routes import url_for -from nose.tools import assert_equal +from nose.tools import assert_equal, assert_in import ckan.tests.helpers as helpers -from ckan.tests.helpers import assert_in from ckan.tests import factories from ckan import model diff --git a/ckan/tests/controllers/test_group.py b/ckan/tests/controllers/test_group.py --- a/ckan/tests/controllers/test_group.py +++ b/ckan/tests/controllers/test_group.py @@ -1,7 +1,7 @@ # encoding: utf-8 from bs4 import BeautifulSoup -from nose.tools import assert_equal, assert_true +from nose.tools import assert_equal, assert_true, assert_in from routes import url_for @@ -9,7 +9,6 @@ import ckan.model as model from ckan.tests import factories -assert_in = helpers.assert_in webtest_submit = helpers.webtest_submit submit_and_follow = helpers.submit_and_follow diff --git a/ckan/tests/controllers/test_organization.py b/ckan/tests/controllers/test_organization.py --- a/ckan/tests/controllers/test_organization.py +++ b/ckan/tests/controllers/test_organization.py @@ -1,12 +1,12 @@ # encoding: utf-8 from bs4 import BeautifulSoup -from nose.tools import assert_equal, assert_true +from nose.tools import assert_equal, assert_true, assert_in from routes import url_for from mock import patch from ckan.tests import factories, helpers -from ckan.tests.helpers import webtest_submit, submit_and_follow, assert_in +from ckan.tests.helpers import webtest_submit, submit_and_follow class TestOrganizationNew(helpers.FunctionalTestBase): diff --git a/ckan/tests/controllers/test_package.py b/ckan/tests/controllers/test_package.py --- a/ckan/tests/controllers/test_package.py +++ b/ckan/tests/controllers/test_package.py @@ -6,6 +6,7 @@ assert_not_equal, assert_raises, assert_true, + assert_in ) from mock import patch, MagicMock @@ -17,10 +18,8 @@ import ckan.tests.helpers as helpers import ckan.tests.factories as factories -from ckan.tests.helpers import assert_in -assert_in = helpers.assert_in webtest_submit = helpers.webtest_submit submit_and_follow = helpers.submit_and_follow diff --git a/ckan/tests/controllers/test_tags.py b/ckan/tests/controllers/test_tags.py --- a/ckan/tests/controllers/test_tags.py +++ b/ckan/tests/controllers/test_tags.py @@ -3,7 +3,7 @@ import math import string -from nose.tools import assert_equal, assert_true, assert_false +from nose.tools import assert_equal, assert_true, assert_false, assert_in from bs4 import BeautifulSoup from routes import url_for @@ -11,7 +11,6 @@ import ckan.tests.helpers as helpers from ckan.tests import factories -assert_in = helpers.assert_in webtest_submit = helpers.webtest_submit submit_and_follow = helpers.submit_and_follow diff --git a/ckan/tests/helpers.py b/ckan/tests/helpers.py --- a/ckan/tests/helpers.py +++ b/ckan/tests/helpers.py @@ -22,6 +22,7 @@ import webtest from pylons import config import nose.tools +from nose.tools import assert_in, assert_not_in import mock import ckan.lib.search as search @@ -30,17 +31,6 @@ import ckan.logic as logic -try: - from nose.tools import assert_in, assert_not_in -except ImportError: - # Python 2.6 doesn't have these, so define them here - def assert_in(a, b, msg=None): - assert a in b, msg or '%r was not in %r' % (a, b) - - def assert_not_in(a, b, msg=None): - assert a not in b, msg or '%r was in %r' % (a, b) - - def reset_db(): '''Reset CKAN's database. diff --git a/ckan/tests/legacy/__init__.py b/ckan/tests/legacy/__init__.py --- a/ckan/tests/legacy/__init__.py +++ b/ckan/tests/legacy/__init__.py @@ -355,15 +355,6 @@ def skip_test(*args): def clear_flash(res=None): messages = h._flash.pop_messages() -try: - from nose.tools import assert_in, assert_not_in -except ImportError: - def assert_in(a, b, msg=None): - assert a in b, msg or '%r was not in %r' % (a, b) - def assert_not_in(a, b, msg=None): - assert a not in b, msg or '%r was in %r' % (a, b) - - class StatusCodes: STATUS_200_OK = 200 STATUS_201_CREATED = 201 diff --git a/ckan/tests/legacy/functional/api/test_api.py b/ckan/tests/legacy/functional/api/test_api.py --- a/ckan/tests/legacy/functional/api/test_api.py +++ b/ckan/tests/legacy/functional/api/test_api.py @@ -2,10 +2,10 @@ import json +from nose.tools import assert_in + from ckan.tests.legacy.functional.api.base import * -import ckan.tests.legacy -assert_in = ckan.tests.legacy.assert_in class ApiTestCase(ApiTestCase, ControllerTestCase): diff --git a/ckan/tests/legacy/lib/test_dictization.py b/ckan/tests/legacy/lib/test_dictization.py --- a/ckan/tests/legacy/lib/test_dictization.py +++ b/ckan/tests/legacy/lib/test_dictization.py @@ -1,10 +1,10 @@ # encoding: utf-8 -from ckan.tests.legacy import assert_equal, assert_not_in, assert_in +from nose.tools import assert_equal, assert_not_in, assert_in from pprint import pprint, pformat from difflib import unified_diff -import ckan.lib.search as search +import ckan.lib.search as search from ckan.lib.create_test_data import CreateTestData from ckan import model from ckan.lib.dictization import (table_dictize, diff --git a/ckan/tests/legacy/models/test_group.py b/ckan/tests/legacy/models/test_group.py --- a/ckan/tests/legacy/models/test_group.py +++ b/ckan/tests/legacy/models/test_group.py @@ -1,9 +1,12 @@ # encoding: utf-8 -from ckan.tests.legacy import assert_equal, assert_in, assert_not_in, CreateTestData +from nose.tools import assert_in, assert_not_in, assert_equal + +from ckan.tests.legacy import CreateTestData import ckan.model as model + class TestGroup(object): @classmethod diff --git a/ckan/tests/legacy/test_coding_standards.py b/ckan/tests/legacy/test_coding_standards.py --- a/ckan/tests/legacy/test_coding_standards.py +++ b/ckan/tests/legacy/test_coding_standards.py @@ -488,7 +488,6 @@ class TestPep8(object): 'ckan/model/authz.py', 'ckan/model/dashboard.py', 'ckan/model/domain_object.py', - 'ckan/model/extension.py', 'ckan/model/follower.py', 'ckan/model/group.py', 'ckan/model/group_extra.py', diff --git a/ckan/tests/lib/search/test_index.py b/ckan/tests/lib/search/test_index.py --- a/ckan/tests/lib/search/test_index.py +++ b/ckan/tests/lib/search/test_index.py @@ -3,17 +3,13 @@ import datetime import hashlib import json -import nose.tools import nose +from nose.tools import assert_equal, assert_in, assert_not_in from pylons import config import ckan.lib.search as search import ckan.tests.helpers as helpers -assert_equal = nose.tools.assert_equal -assert_in = helpers.assert_in -assert_not_in = helpers.assert_not_in - class TestSearchIndex(object): diff --git a/ckan/tests/lib/test_mailer.py b/ckan/tests/lib/test_mailer.py --- a/ckan/tests/lib/test_mailer.py +++ b/ckan/tests/lib/test_mailer.py @@ -1,6 +1,6 @@ # encoding: utf-8 -from nose.tools import assert_equal, assert_raises +from nose.tools import assert_equal, assert_raises, assert_in from pylons import config from email.mime.text import MIMEText from email.parser import Parser @@ -16,8 +16,6 @@ import ckan.tests.helpers as helpers import ckan.tests.factories as factories -assert_in = helpers.assert_in - class MailerBase(SmtpServerHarness): diff --git a/ckan/tests/test_coding_standards.py b/ckan/tests/test_coding_standards.py --- a/ckan/tests/test_coding_standards.py +++ b/ckan/tests/test_coding_standards.py @@ -15,8 +15,6 @@ import re import subprocess -import ckan.lib.util as util - def test_building_the_docs(): '''There should be no warnings or errors when building the Sphinx docs. @@ -28,8 +26,12 @@ def test_building_the_docs(): ''' try: - output = util.check_output( - ['python', 'setup.py', 'build_sphinx', '--all-files', '--fresh-env'], + output = subprocess.check_output( + ['python', + 'setup.py', + 'build_sphinx', + '--all-files', + '--fresh-env'], stderr=subprocess.STDOUT) except subprocess.CalledProcessError as err: assert False, ( diff --git a/ckanext/datapusher/tests/test.py b/ckanext/datapusher/tests/test.py --- a/ckanext/datapusher/tests/test.py +++ b/ckanext/datapusher/tests/test.py @@ -4,7 +4,6 @@ import httpretty import httpretty.core import nose -import sys import datetime import pylons @@ -56,19 +55,12 @@ def __getattr__(self, attr): httpretty.core.fakesock.socket = HTTPrettyFix -# avoid hanging tests https://github.com/gabrielfalcao/HTTPretty/issues/34 -if sys.version_info < (2, 7, 0): - import socket - socket.setdefaulttimeout(1) - - class TestDatastoreCreate(tests.WsgiAppCase): sysadmin_user = None normal_user = None @classmethod def setup_class(cls): - wsgiapp = middleware.make_app(config['global_conf'], **config) cls.app = paste.fixture.TestApp(wsgiapp) if not tests.is_datastore_supported(): @@ -84,20 +76,11 @@ def setup_class(cls): set_url_type( model.Package.get('annakarenina').resources, cls.sysadmin_user) - # Httpretty crashes with Solr on Python 2.6, - # skip the tests - if (sys.version_info[0] == 2 and sys.version_info[1] == 6): - raise nose.SkipTest() - @classmethod def teardown_class(cls): rebuild_all_dbs(cls.Session) p.unload('datastore') p.unload('datapusher') - # Reenable Solr indexing - if (sys.version_info[0] == 2 and sys.version_info[1] == 6 - and not p.plugin_loaded('synchronous_search')): - p.load('synchronous_search') def test_create_ckan_resource_in_package(self): package = model.Package.get('annakarenina') diff --git a/ckanext/datastore/tests/test_create.py b/ckanext/datastore/tests/test_create.py --- a/ckanext/datastore/tests/test_create.py +++ b/ckanext/datastore/tests/test_create.py @@ -22,12 +22,6 @@ from ckanext.datastore.tests.helpers import rebuild_all_dbs, set_url_type -# avoid hanging tests https://github.com/gabrielfalcao/HTTPretty/issues/34 -if sys.version_info < (2, 7, 0): - import socket - socket.setdefaulttimeout(1) - - class TestDatastoreCreateNewTests(object): @classmethod def setup_class(cls): diff --git a/ckanext/example_igroupform/tests/test_controllers.py b/ckanext/example_igroupform/tests/test_controllers.py --- a/ckanext/example_igroupform/tests/test_controllers.py +++ b/ckanext/example_igroupform/tests/test_controllers.py @@ -1,6 +1,6 @@ # encoding: utf-8 -from nose.tools import assert_equal +from nose.tools import assert_equal, assert_in from routes import url_for import ckan.plugins as plugins @@ -8,7 +8,6 @@ import ckan.model as model from ckan.tests import factories -assert_in = helpers.assert_in webtest_submit = helpers.webtest_submit submit_and_follow = helpers.submit_and_follow diff --git a/ckanext/example_iuploader/test/test_plugin.py b/ckanext/example_iuploader/test/test_plugin.py --- a/ckanext/example_iuploader/test/test_plugin.py +++ b/ckanext/example_iuploader/test/test_plugin.py @@ -6,6 +6,7 @@ from mock import patch from nose.tools import ( assert_equal, + assert_in, assert_is_instance ) from pyfakefs import fake_filesystem @@ -19,7 +20,6 @@ import ckan.tests.helpers as helpers import ckanext.example_iuploader.plugin as plugin -assert_in = helpers.assert_in webtest_submit = helpers.webtest_submit submit_and_follow = helpers.submit_and_follow diff --git a/ckanext/example_theme/custom_emails/tests.py b/ckanext/example_theme/custom_emails/tests.py --- a/ckanext/example_theme/custom_emails/tests.py +++ b/ckanext/example_theme/custom_emails/tests.py @@ -11,10 +11,7 @@ from ckan.tests.lib.test_mailer import MailerBase import ckan.tests.helpers as helpers -from nose.tools import assert_equal - - -assert_in = helpers.assert_in +from nose.tools import assert_equal, assert_in class TestExampleCustomEmailsPlugin(MailerBase): diff --git a/ckanext/resourceproxy/tests/test_proxy.py b/ckanext/resourceproxy/tests/test_proxy.py --- a/ckanext/resourceproxy/tests/test_proxy.py +++ b/ckanext/resourceproxy/tests/test_proxy.py @@ -1,6 +1,5 @@ # encoding: utf-8 -import sys import requests import unittest import json @@ -60,20 +59,12 @@ def setup_class(cls): wsgiapp = middleware.make_app(config['global_conf'], **config) cls.app = paste.fixture.TestApp(wsgiapp) create_test_data.CreateTestData.create() - # Httpretty crashes with Solr on Python 2.6, - # skip the tests - if (sys.version_info[0] == 2 and sys.version_info[1] == 6): - raise nose.SkipTest() @classmethod def teardown_class(cls): config.clear() config.update(cls._original_config) model.repo.rebuild_db() - # Reenable Solr indexing - if (sys.version_info[0] == 2 and sys.version_info[1] == 6 - and not p.plugin_loaded('synchronous_search')): - p.load('synchronous_search') def setUp(self): self.url = 'http://www.ckan.org/static/example.json'
Drop Python 2.6 support It was announced to the mailing list by @amercader in January that support for python 2.6 was going to be dropped with ckan 2.6 (what a wonderful coincidence). https://lists.okfn.org/pipermail/ckan-dev/2016-January/009608.html > Starting from the next CKAN 2.6 version, the minimum Python version > required for CKAN will be Python 2.7 (we recommend using the latest > Python patch release). There still are some backports and workaraounds for 2.6 in the code and the documentation needs upgrading. ## Grep for `2.6` ### Python files ``` ckan/lib/util.py 13:# subprocess.check_output() isn't in Python 2.6. 15:# Python 2.6. ckan/model/extension.py 17: "Replaces stdlib operator.methodcaller in python <2.6" ckan/tests/helpers.py 36: # Python 2.6 doesn't have these, so define them here ckanext/datapusher/tests/test.py 87: # Httpretty crashes with Solr on Python 2.6, ckanext/resourceproxy/tests/test_proxy.py 63: # Httpretty crashes with Solr on Python 2.6, ``` ### Documentation: ``` doc/contributing/python.rst 77:We use `the Python standard library's logging module <http://docs.python.org/2.6/library/logging.html>`_ doc/contributing/string-i18n.rst 339: Worse (doesn't work in Python 2.6): doc/maintaining/installing/install-from-source.rst 36:Python `The Python programming language, v2.6 or 2.7 <http://www.python.org/getit/>`_ ``` I'll prepare a PR to remove all of those things.
2016-06-17T15:44:01
ckan/ckan
3,133
ckan__ckan-3133
[ "2661" ]
a10edd33ee4e097068f5f4295167c15899a0be3c
diff --git a/ckan/logic/action/create.py b/ckan/logic/action/create.py --- a/ckan/logic/action/create.py +++ b/ckan/logic/action/create.py @@ -197,6 +197,7 @@ def package_create(context, data_dict): context_org_update = context.copy() context_org_update['ignore_auth'] = True context_org_update['defer_commit'] = True + context_org_update['add_revision'] = False _get_action('package_owner_org_update')(context_org_update, {'id': pkg.id, 'organization_id': pkg.owner_org}) diff --git a/ckan/logic/action/update.py b/ckan/logic/action/update.py --- a/ckan/logic/action/update.py +++ b/ckan/logic/action/update.py @@ -292,6 +292,7 @@ def package_update(context, data_dict): context_org_update = context.copy() context_org_update['ignore_auth'] = True context_org_update['defer_commit'] = True + context_org_update['add_revision'] = False _get_action('package_owner_org_update')(context_org_update, {'id': pkg.id, 'organization_id': pkg.owner_org}) @@ -1020,6 +1021,7 @@ def package_owner_org_update(context, data_dict): :type id: string ''' model = context['model'] + user = context['user'] name_or_id = data_dict.get('id') organization_id = data_dict.get('organization_id') @@ -1039,10 +1041,17 @@ def package_owner_org_update(context, data_dict): org = None pkg.owner_org = None + if context.get('add_revision', True): + rev = model.repo.new_revision() + rev.author = user + if 'message' in context: + rev.message = context['message'] + else: + rev.message = _(u'REST API: Update object %s') % pkg.get("name") members = model.Session.query(model.Member) \ - .filter(model.Member.table_id == pkg.id) \ - .filter(model.Member.capacity == 'organization') + .filter(model.Member.table_id == pkg.id) \ + .filter(model.Member.capacity == 'organization') need_update = True for member_obj in members:
diff --git a/ckan/tests/logic/action/test_update.py b/ckan/tests/logic/action/test_update.py --- a/ckan/tests/logic/action/test_update.py +++ b/ckan/tests/logic/action/test_update.py @@ -858,3 +858,63 @@ def test_user_create_password_hash_not_for_normal_users(self): user_obj = model.User.get(user['id']) assert user_obj.password != 'pretend-this-is-a-valid-hash' + + +class TestPackageOwnerOrgUpdate(object): + + @classmethod + def teardown_class(cls): + helpers.reset_db() + + def setup(self): + helpers.reset_db() + + def test_package_owner_org_added(self): + '''A package without an owner_org can have one added.''' + sysadmin = factories.Sysadmin() + org = factories.Organization() + dataset = factories.Dataset() + context = { + 'user': sysadmin['name'], + } + assert dataset['owner_org'] is None + helpers.call_action('package_owner_org_update', + context=context, + id=dataset['id'], + organization_id=org['id']) + dataset_obj = model.Package.get(dataset['id']) + assert dataset_obj.owner_org == org['id'] + + def test_package_owner_org_changed(self): + '''A package with an owner_org can have it changed.''' + + sysadmin = factories.Sysadmin() + org_1 = factories.Organization() + org_2 = factories.Organization() + dataset = factories.Dataset(owner_org=org_1['id']) + context = { + 'user': sysadmin['name'], + } + assert dataset['owner_org'] == org_1['id'] + helpers.call_action('package_owner_org_update', + context=context, + id=dataset['id'], + organization_id=org_2['id']) + dataset_obj = model.Package.get(dataset['id']) + assert dataset_obj.owner_org == org_2['id'] + + def test_package_owner_org_removed(self): + '''A package with an owner_org can have it removed.''' + sysadmin = factories.Sysadmin() + org = factories.Organization() + dataset = factories.Dataset(owner_org=org['id']) + context = { + 'user': sysadmin['name'], + } + assert dataset['owner_org'] == org['id'] + helpers.call_action('package_owner_org_update', + context=context, + id=dataset['id'], + organization_id=None) + dataset_obj = model.Package.get(dataset['id']) + assert dataset_obj.owner_org is None
package_owner_org_update doesn't work When calling package owner work the API returns a 500 Server error. On the server end the log says: ``` Error - <type 'exceptions.AssertionError'>: No revision is currently set for this Session ``` I haven't debugged further
2016-06-24T15:04:19
ckan/ckan
3,158
ckan__ckan-3158
[ "2952" ]
e2162f0a42b093f0b5ddc50a92af9fd0088112c1
diff --git a/ckan/lib/cli.py b/ckan/lib/cli.py --- a/ckan/lib/cli.py +++ b/ckan/lib/cli.py @@ -31,6 +31,18 @@ # Otherwise loggers get disabled. +def deprecation_warning(message=None): + ''' + Print a deprecation warning to STDERR. + + If ``message`` is given it is also printed to STDERR. + ''' + sys.stderr.write(u'WARNING: This function is deprecated.') + if message: + sys.stderr.write(u' ' + message.strip()) + sys.stderr.write(u'\n') + + def parse_db_config(config_key='sqlalchemy.url'): ''' Takes a config key for a database connection url and parses it into a dictionary. Expects a url like: @@ -187,10 +199,10 @@ class ManageDb(CkanCommand): search index db upgrade [version no.] - Data migrate db version - returns current version of data schema - db dump FILE_PATH - dump to a pg_dump file - db load FILE_PATH - load a pg_dump from a file + db dump FILE_PATH - dump to a pg_dump file [DEPRECATED] + db load FILE_PATH - load a pg_dump from a file [DEPRECATED] db load-only FILE_PATH - load a pg_dump from a file but don\'t do - the schema upgrade or search indexing + the schema upgrade or search indexing [DEPRECATED] db create-from-model - create database from the model (indexes not made) db migrate-filestore - migrate all uploaded data from the 2.1 filesore. ''' @@ -291,6 +303,7 @@ def _run_cmd(self, command_line): raise SystemError('Command exited with errorcode: %i' % retcode) def dump(self): + deprecation_warning(u"Use PostgreSQL's pg_dump instead.") if len(self.args) < 2: print 'Need pg_dump filepath' return @@ -300,6 +313,7 @@ def dump(self): pg_cmd = self._postgres_dump(dump_path) def load(self, only_load=False): + deprecation_warning(u"Use PostgreSQL's pg_restore instead.") if len(self.args) < 2: print 'Need pg_dump filepath' return
Escape special characters in password while db loading CKAN doesn't escape special symbols within password. Restore procedure: ``` paster db load -c /etc/ckan/default/production.ini my_database_dump.sql ``` in my case produces the following invalid command: ``` PGPASSWORD=Ab1239idap&u && psql -U ckan_default -h localhost -d ckan_default -f /mnt/portal/tmp/ckan.pg_dump [1] 26628 -bash: u: command not found ```
I'd prefer to remove the "db load" command and instead just document how to dump and restore using the postgres tools directly. @wardi: According to [the documentation](http://docs.ckan.org/en/latest/maintaining/paster.html#dumping-and-loading-databases-to-from-a-file), `db load` also automatically performs DB migrations if the data comes from an older CKAN version. That is a really nice feature that you won't get by using the raw postgres tools. This command prevents users from using a bunch of the useful options available in pg_dump/pg_restore and I don't think it's really much of a burden to run `paster db upgrade` after restoring the db. If you really like `db load` and are willing to fix this issue I won't refuse the fix. I think it's really useful to know that you don't _need_ ckan in order to perform a backup or restore, though. Ah, I wasn't aware of the `db upgrade` command (the [online documentation](http://docs.ckan.org/en/latest/maintaining/paster.html) doesn't mention it explicitly and I never checked `paster db --help` before). In that case you're probably right and `db load` can be removed. A section in the docs describing the full database dump/restore/upgrade cycle would be useful then. +1 for removing `db load` in favour of improved documentation. @torfsen, it is documented where it needs to be though, albeit slightly hidden: http://docs.ckan.org/en/latest/maintaining/upgrading/upgrade-source.html#upgrading-a-source-install @mattfullerton: Yeah, it's also described at [database migrations](http://docs.ckan.org/en/latest/contributing/database-migrations.html). However, the [command line interface page](http://docs.ckan.org/en/latest/maintaining/paster.html) always had an "exhaustive" look and feel to me. From there I learned that `db load` does the necessary migrations and that's all that I've ever needed :wink: Perhaps the paster reference could be auto-generated so that the reference and `paster --help` / `paster command --help` contain the same information. Hi, I'm having the same password problem but with `paster pg dump`. Is that fixed already? If not, I fixed it on my CKAN and can submit a fix for the `paster pg dump`. Please let me know. Thanks Can this be re-opened until the discussed documentation improvements have been implemented? This is still affecting users, see for example [this Stack Overflow question that was posted today](http://stackoverflow.com/questions/38242908/dump-the-ckan-database-and-load-it-in-another-ckan-instance/38248006#38248006).
2016-07-08T13:08:56
ckan/ckan
3,200
ckan__ckan-3200
[ "3162" ]
5694d09546f875fc29e7dd541e3b77af5d145241
diff --git a/ckanext/reclineview/plugin.py b/ckanext/reclineview/plugin.py --- a/ckanext/reclineview/plugin.py +++ b/ckanext/reclineview/plugin.py @@ -5,6 +5,7 @@ from ckan.common import json import ckan.plugins as p import ckan.plugins.toolkit as toolkit +from pylons import config log = getLogger(__name__) ignore_empty = p.toolkit.get_validator('ignore_empty') @@ -12,6 +13,15 @@ Invalid = p.toolkit.Invalid +def get_mapview_config(): + ''' + Extracts and returns map view configuration of the reclineview extension. + ''' + namespace = 'ckanext.spatial.common_map.' + return dict([(k.replace(namespace, ''), v) for k, v in config.iteritems() + if k.startswith(namespace)]) + + def in_list(list_possible_values): ''' Validator that checks that the input value is one of the given @@ -77,6 +87,8 @@ class ReclineView(ReclineViewBase): This extension views resources using a Recline MultiView. ''' + p.implements(p.ITemplateHelpers, inherit=True) + def info(self): return {'name': 'recline_view', 'title': 'Data Explorer', @@ -98,6 +110,11 @@ def can_view(self, data_dict): else: return False + def get_helpers(self): + return { + 'get_map_config': get_mapview_config + } + class ReclineGridView(ReclineViewBase): ''' @@ -174,6 +191,8 @@ class ReclineMapView(ReclineViewBase): This extension views resources using a Recline map. ''' + p.implements(p.ITemplateHelpers, inherit=True) + map_field_types = [{'value': 'lat_long', 'text': 'Latitude / Longitude fields'}, {'value': 'geojson', 'text': 'GeoJSON'}] @@ -234,3 +253,8 @@ def setup_template_variables(self, context, data_dict): def form_template(self, context, data_dict): return 'recline_map_form.html' + + def get_helpers(self): + return { + 'get_mapview_config': get_mapview_config + }
DataStore Map and Explorer not displaying map tiles since 11 July 2016 Direct tile access to MapQuest maps has been discontinued as of 11 July 2016 and the DataStore Map and Explorer previews no longer display map tiles. The issue actually lies with recline.js and it has been logged https://github.com/okfn/recline/issues/500 and there is a referenced patch to replace MapQuest with Open Street Map frodrigo/recline@3df0c2a2bb8897124bdbbca715b2be1fd99cb08f Thought it would be useful to have a record here and request the packaged recline.js should be updated.
2016-08-10T22:38:49
ckan/ckan
3,210
ckan__ckan-3210
[ "3204" ]
e26bf5604df65c86a93070a62e8fb1ec60ffa94c
diff --git a/ckan/lib/search/__init__.py b/ckan/lib/search/__init__.py --- a/ckan/lib/search/__init__.py +++ b/ckan/lib/search/__init__.py @@ -7,7 +7,6 @@ import xml.dom.minidom import urllib2 -from ckan.common import config from paste.deploy.converters import asbool import ckan.model as model @@ -23,7 +22,6 @@ log = logging.getLogger(__name__) - def text_traceback(): with warnings.catch_warnings(): warnings.simplefilter("ignore") @@ -32,7 +30,6 @@ def text_traceback(): ).strip() return res -SIMPLE_SEARCH = asbool(config.get('ckan.simple_search', False)) SUPPORTED_SCHEMA_VERSIONS = ['2.3'] @@ -60,11 +57,6 @@ def text_traceback(): SOLR_SCHEMA_FILE_OFFSET = '/admin/file/?file=schema.xml' -if SIMPLE_SEARCH: - import sql as sql - _INDICES['package'] = NoopSearchIndex - _QUERIES['package'] = sql.PackageSearchQuery - def _normalize_type(_type): if isinstance(_type, model.domain_object.DomainObject): @@ -219,6 +211,7 @@ def commit(): package_index.commit() log.info('Commited pending changes on the search index') + def check(): package_query = query_for(model.Package) @@ -249,10 +242,9 @@ def clear(package_reference): def clear_all(): - if not SIMPLE_SEARCH: - package_index = index_for(model.Package) - log.debug("Clearing search index...") - package_index.clear() + package_index = index_for(model.Package) + log.debug("Clearing search index...") + package_index.clear() def check_solr_schema_version(schema_file=None): @@ -276,11 +268,6 @@ def check_solr_schema_version(schema_file=None): be only used for testing purposes (Default is None) ''' - - if SIMPLE_SEARCH: - # Not using the SOLR search backend - return False - if not is_available(): # Something is wrong with the SOLR server log.warn('Problems were found while connecting to the SOLR server') diff --git a/ckan/lib/search/sql.py b/ckan/lib/search/sql.py deleted file mode 100644 --- a/ckan/lib/search/sql.py +++ /dev/null @@ -1,42 +0,0 @@ -# encoding: utf-8 - -from sqlalchemy import or_ -from ckan.lib.search.query import SearchQuery -import ckan.model as model - -class PackageSearchQuery(SearchQuery): - def get_all_entity_ids(self, max_results=100): - """ - Return a list of the IDs of all indexed packages. - """ - # could make this a pure sql query which would be much more efficient! - q = model.Session.query(model.Package).filter_by(state='active').limit(max_results) - - return [r.id for r in q] - - def run(self, query): - assert isinstance(query, dict) - # no support for faceting atm - self.facets = {} - limit = min(1000, int(query.get('rows', 10))) - - q = query.get('q') - ourq = model.Session.query(model.Package.id).filter_by(state='active') - - def makelike(field): - _attr = getattr(model.Package, field) - return _attr.ilike('%' + term + '%') - if q and q not in ('""', "''", '*:*'): - terms = q.split() - # TODO: tags ...? - fields = ['name', 'title', 'notes'] - for term in terms: - args = [makelike(field) for field in fields] - subq = or_(*args) - ourq = ourq.filter(subq) - self.count = ourq.count() - ourq = ourq.limit(limit) - self.results = [{'id': r[0]} for r in ourq.all()] - - return {'results': self.results, 'count': self.count} -
diff --git a/ckan/tests/legacy/lib/test_simple_search.py b/ckan/tests/legacy/lib/test_simple_search.py deleted file mode 100644 --- a/ckan/tests/legacy/lib/test_simple_search.py +++ /dev/null @@ -1,37 +0,0 @@ -# encoding: utf-8 - -from nose.tools import assert_equal - -from ckan import model -from ckan.lib.create_test_data import CreateTestData -from ckan.lib.search.sql import PackageSearchQuery - -class TestSimpleSearch: - @classmethod - def setup_class(cls): - CreateTestData.create() - - @classmethod - def teardown_class(cls): - model.repo.rebuild_db() - - def test_get_all_entity_ids(self): - ids = PackageSearchQuery().get_all_entity_ids() - anna = model.Package.by_name(u'annakarenina') - assert anna.id in ids - assert len(ids) >= 2, len(ids) - - def test_run_query_basic(self): - res = PackageSearchQuery().run({'q':'annakarenina'}) - anna = model.Package.by_name(u'annakarenina') - assert_equal(res, {'results': [{'id': anna.id}], 'count': 1}) - - def test_run_query_home(self): - # This is the query from the CKAN home page - res = PackageSearchQuery().run({'q': '*:*'}) - assert res['count'] >= 2, res['count'] - - def test_run_query_all(self): - # This is the default query from the search page - res = PackageSearchQuery().run({'q': u''}) - assert res['count'] >= 2, res['count']
ckan.simple_search setting being ignored ### CKAN Version if known (or site URL) 2.5.2 ### Please describe the expected behaviour When `ckan.simple_search` is set to `true` or `1`, CKAN should start up without complaining about a lost connection to SOLR. ### Please describe the actual behaviour CKAN logs errors regarding being unable to connect to the SOLR server: ``` 2016-08-17 19:01:43,150 WARNI [ckan.lib.search] Problems were found while connecting to the SOLR server 2016-08-17 19:01:43,447 ERROR [ckan.lib.search.common] [Errno 111] Connection refused Traceback (most recent call last): File "/usr/lib/ckan/default/src/ckan/ckan/lib/search/common.py", line 51, in is_available conn.query("*:*", rows=1) File "/usr/local/lib/python2.7/dist-packages/solr/core.py", line 703, in query return self.select(*args, **params) File "/usr/local/lib/python2.7/dist-packages/solr/core.py", line 798, in __call__ xml = self.raw(**params) File "/usr/local/lib/python2.7/dist-packages/solr/core.py", line 823, in raw rsp = conn._post(self.selector, request, conn.form_headers) File "/usr/local/lib/python2.7/dist-packages/solr/core.py", line 646, in _post self._reconnect() File "/usr/local/lib/python2.7/dist-packages/solr/core.py", line 625, in _reconnect self.conn.connect() File "/usr/lib/python2.7/httplib.py", line 778, in connect self.timeout, self.source_address) File "/usr/lib/python2.7/socket.py", line 571, in create_connection raise err error: [Errno 111] Connection refused 2016-08-17 19:01:43,448 WARNI [ckan.lib.search] Problems were found while connecting to the SOLR server ``` ### What steps can be taken to reproduce the issue? Consult [the documentation](http://docs.ckan.org/en/latest/maintaining/configuration.html) regarding the `ckan.simple_search` option: > ckan.simple_search > Example: > > ckan.simple_search = true > Default value: false > > Switching this on tells CKAN search functionality to just query the database, (rather than using Solr). In this setup, search is crude and limited, e.g. no full-text search, no faceting, etc. However, this might be very useful for getting up and running quickly with CKAN. Set the `ckan.simple_search` option to true in the configuration ini file, and comment out the `solr`url` setting, then restart CKAN and observe the logged output.
2016-08-19T08:54:01
ckan/ckan
3,240
ckan__ckan-3240
[ "2882" ]
45b8e4f964fd3631866fce0630d3d15fbeff9abd
diff --git a/ckan/lib/formatters.py b/ckan/lib/formatters.py --- a/ckan/lib/formatters.py +++ b/ckan/lib/formatters.py @@ -99,12 +99,10 @@ def months_between(date1, date2): return months if not show_date: - now = datetime.datetime.utcnow() - if datetime_.tzinfo is not None: - now = now.replace(tzinfo=datetime_.tzinfo) - else: - now = now.replace(tzinfo=pytz.utc) + now = datetime.datetime.now(pytz.utc) + if datetime_.tzinfo is None: datetime_ = datetime_.replace(tzinfo=pytz.utc) + date_diff = now - datetime_ days = date_diff.days if days < 1 and now > datetime_: diff --git a/ckan/migration/versions/085_adjust_activity_timestamps.py b/ckan/migration/versions/085_adjust_activity_timestamps.py new file mode 100644 --- /dev/null +++ b/ckan/migration/versions/085_adjust_activity_timestamps.py @@ -0,0 +1,16 @@ +# encoding: utf-8 + +import datetime + + +def upgrade(migrate_engine): + u""" + The script assumes that the current timestamp was + recorded with the server's current set timezone + """ + utc_now = datetime.datetime.utcnow() + local_now = datetime.datetime.now() + + with migrate_engine.begin() as connection: + sql = u"update activity set timestamp = timestamp + (%s - %s);" + connection.execute(sql, utc_now, local_now) diff --git a/ckan/model/activity.py b/ckan/model/activity.py --- a/ckan/model/activity.py +++ b/ckan/model/activity.py @@ -40,7 +40,7 @@ class Activity(domain_object.DomainObject): def __init__(self, user_id, object_id, revision_id, activity_type, data=None): self.id = _types.make_uuid() - self.timestamp = datetime.datetime.now() + self.timestamp = datetime.datetime.utcnow() self.user_id = user_id self.object_id = object_id self.revision_id = revision_id
Activity timestamps are stored in local time instead of UTC https://github.com/ckan/ckan/blob/master/ckan/model/activity.py#L41 If server has local time set to some timezone that differs from UTC, activity streams show -1 days ago instead of just now, since datetime.now() return local time instead of UTC. There probably are others as well which use local time instead of UTC, at least based on a quick search https://github.com/ckan/ckan/search?utf8=%E2%9C%93&q=datetime.now%28%29&type=Code
That's not good. A fix would include a migration that updates the times in the db (using the current time offset should be close enough for the activity stream) and updating the templates to use the snippet that adjusts the display to the client's time zone @wardi and apparently "-1 days ago" is returned from here https://github.com/ckan/ckan/blob/master/ckan/lib/formatters.py#L71 if server time is in UTC but ckan.display_timezone is something else like Europe/Helsinki I confirm that activity timestamps are always stored in server local timezone guessing it is UTC. Given server timezone is `America/Sao_Paulo` (-03:00). When `ckan.display_timezone` is `server` then a difference of -6 hours is shown. When `ckan.display_timezone` is `UTC` then the difference becomes -3 hours (still incorrect). According to this ticket the issue may be more than 4 years old: http://trac.ckan.org/ticket/331.html
2016-09-12T22:51:03
ckan/ckan
3,247
ckan__ckan-3247
[ "3243" ]
e0fdb8dcd279857890a301f90d82d18293983a32
diff --git a/ckan/config/environment.py b/ckan/config/environment.py --- a/ckan/config/environment.py +++ b/ckan/config/environment.py @@ -251,17 +251,9 @@ def update_config(): # CONFIGURATION OPTIONS HERE (note: all config options will override # any Pylons config options) - # for postgresql we want to enforce utf-8 - sqlalchemy_url = config.get('sqlalchemy.url', '') - if sqlalchemy_url.startswith('postgresql://'): - extras = {'client_encoding': 'utf8'} - else: - extras = {} - - engine = sqlalchemy.engine_from_config(config, 'sqlalchemy.', **extras) - - if not model.meta.engine: - model.init_model(engine) + # Initialize SQLAlchemy + engine = sqlalchemy.engine_from_config(config, client_encoding='utf8') + model.init_model(engine) for plugin in p.PluginImplementations(p.IConfigurable): plugin.configure(config) diff --git a/ckan/lib/jobs.py b/ckan/lib/jobs.py --- a/ckan/lib/jobs.py +++ b/ckan/lib/jobs.py @@ -28,6 +28,7 @@ from ckan.lib.redis import connect_to_redis from ckan.common import config +from ckan.config.environment import load_environment log = logging.getLogger(__name__) @@ -249,3 +250,9 @@ def handle_exception(self, job, *exc_info): log.exception(u'Job {} on worker {} raised an exception: {}'.format( job.id, self.key, exc_info[1])) return super(Worker, self).handle_exception(job, *exc_info) + + def main_work_horse(self, job, queue): + # This method is called in a worker's work horse process right + # after forking. + load_environment(config[u'global_conf'], config) + return super(Worker, self).main_work_horse(job, queue) diff --git a/ckan/plugins/interfaces.py b/ckan/plugins/interfaces.py --- a/ckan/plugins/interfaces.py +++ b/ckan/plugins/interfaces.py @@ -1,32 +1,38 @@ # encoding: utf-8 -'''A collection of interfaces that CKAN plugins can implement to customize and +u'''A collection of interfaces that CKAN plugins can implement to customize and extend CKAN. ''' __all__ = [ - 'Interface', - 'IRoutes', - 'IMapper', 'ISession', - 'IMiddleware', - 'IAuthFunctions', - 'IDomainObjectModification', 'IGroupController', - 'IOrganizationController', - 'IPackageController', 'IPluginObserver', - 'IConfigurable', 'IConfigurer', - 'IActions', 'IResourceUrlChange', 'IDatasetForm', - 'IValidators', - 'IResourcePreview', - 'IResourceView', - 'IResourceController', - 'IGroupForm', - 'ITagController', - 'ITemplateHelpers', - 'IFacets', - 'IAuthenticator', - 'ITranslation', - 'IUploader', - 'IPermissionLabels', + u'Interface', + u'IRoutes', + u'IMapper', + u'ISession', + u'IMiddleware', + u'IAuthFunctions', + u'IDomainObjectModification', + u'IGroupController', + u'IOrganizationController', + u'IPackageController', + u'IPluginObserver', + u'IConfigurable', + u'IConfigurer', + u'IActions', + u'IResourceUrlChange', + u'IDatasetForm', + u'IValidators', + u'IResourcePreview', + u'IResourceView', + u'IResourceController', + u'IGroupForm', + u'ITagController', + u'ITemplateHelpers', + u'IFacets', + u'IAuthenticator', + u'ITranslation', + u'IUploader', + u'IPermissionLabels', ] from inspect import isclass @@ -42,7 +48,7 @@ def provided_by(cls, instance): @classmethod def implemented_by(cls, other): if not isclass(other): - raise TypeError("Class expected", other) + raise TypeError(u'Class expected', other) try: return cls in other._implements except AttributeError: @@ -50,47 +56,47 @@ def implemented_by(cls, other): class IMiddleware(Interface): - '''Hook into Pylons middleware stack + u'''Hook into Pylons middleware stack ''' def make_middleware(self, app, config): - '''Return an app configured with this middleware + u'''Return an app configured with this middleware ''' return app def make_error_log_middleware(self, app, config): - '''Return an app configured with this error log middleware + u'''Return an app configured with this error log middleware ''' return app class IRoutes(Interface): - """ + u''' Plugin into the setup of the routes map creation. - """ + ''' def before_map(self, map): - """ + u''' Called before the routes map is generated. ``before_map`` is before any other mappings are created so can override all other mappings. :param map: Routes map object :returns: Modified version of the map object - """ + ''' return map def after_map(self, map): - """ + u''' Called after routes map is set up. ``after_map`` can be used to add fall-back handlers. :param map: Routes map object :returns: Modified version of the map object - """ + ''' return map class IMapper(Interface): - """ + u''' A subset of the SQLAlchemy mapper extension hooks. See http://docs.sqlalchemy.org/en/rel_0_9/orm/deprecated.html#sqlalchemy.orm.interfaces.MapperExtension @@ -101,125 +107,125 @@ class IMapper(Interface): ... implements(IMapper) ... ... def after_update(self, mapper, connection, instance): - ... log("Updated: %r", instance) - """ + ... log(u'Updated: %r', instance) + ''' def before_insert(self, mapper, connection, instance): - """ + u''' Receive an object instance before that instance is INSERTed into its table. - """ + ''' def before_update(self, mapper, connection, instance): - """ + u''' Receive an object instance before that instance is UPDATEed. - """ + ''' def before_delete(self, mapper, connection, instance): - """ + u''' Receive an object instance before that instance is PURGEd. (whereas usually in ckan 'delete' means to change the state property to deleted, so use before_update for that case.) - """ + ''' def after_insert(self, mapper, connection, instance): - """ + u''' Receive an object instance after that instance is INSERTed. - """ + ''' def after_update(self, mapper, connection, instance): - """ + u''' Receive an object instance after that instance is UPDATEed. - """ + ''' def after_delete(self, mapper, connection, instance): - """ + u''' Receive an object instance after that instance is PURGEd. (whereas usually in ckan 'delete' means to change the state property to deleted, so use before_update for that case.) - """ + ''' class ISession(Interface): - """ + u''' A subset of the SQLAlchemy session extension hooks. - """ + ''' def after_begin(self, session, transaction, connection): - """ + u''' Execute after a transaction is begun on a connection - """ + ''' def before_flush(self, session, flush_context, instances): - """ + u''' Execute before flush process has started. - """ + ''' def after_flush(self, session, flush_context): - """ + u''' Execute after flush has completed, but before commit has been called. - """ + ''' def before_commit(self, session): - """ + u''' Execute right before commit is called. - """ + ''' def after_commit(self, session): - """ + u''' Execute after a commit has occured. - """ + ''' def after_rollback(self, session): - """ + u''' Execute after a rollback has occured. - """ + ''' class IDomainObjectModification(Interface): - """ + u''' Receives notification of new, changed and deleted datasets. - """ + ''' def notify(self, entity, operation): - """ + u''' Send a notification on entity modification. :param entity: instance of module.Package. :param operation: 'new', 'changed' or 'deleted'. - """ + ''' pass def notify_after_commit(self, entity, operation): - """ + u''' Send a notification after entity modification. :param entity: instance of module.Package. :param operation: 'new', 'changed' or 'deleted'. - """ + ''' pass class IResourceUrlChange(Interface): - """ + u''' Receives notification of changed urls. - """ + ''' def notify(self, resource): - """ + u''' Give user a notify is resource url has changed. :param resource, instance of model.Resource - """ + ''' pass class IResourceView(Interface): - '''Add custom view renderings for different resource types. + u'''Add custom view renderings for different resource types. ''' def info(self): - ''' + u''' Returns a dictionary with configuration options for the view. The available keys are: @@ -275,10 +281,10 @@ def info(self): .. _Font Awesome: http://fortawesome.github.io/Font-Awesome/3.2.1/icons ''' - return {'name': self.__class__.__name__} + return {u'name': self.__class__.__name__} def can_view(self, data_dict): - ''' + u''' Returns whether the plugin can render a particular resource. The ``data_dict`` contains the following keys: @@ -292,7 +298,7 @@ def can_view(self, data_dict): ''' def setup_template_variables(self, context, data_dict): - ''' + u''' Adds variables to be passed to the template being rendered. This should return a new dict instead of updating the input @@ -309,7 +315,7 @@ def setup_template_variables(self, context, data_dict): ''' def view_template(self, context, data_dict): - ''' + u''' Returns a string representing the location of the template to be rendered when the view is displayed @@ -327,7 +333,7 @@ def view_template(self, context, data_dict): ''' def form_template(self, context, data_dict): - ''' + u''' Returns a string representing the location of the template to be rendered when the edit view form is displayed @@ -346,7 +352,7 @@ def form_template(self, context, data_dict): class IResourcePreview(Interface): - ''' + u''' .. warning:: This interface is deprecated, and is only kept for backwards compatibility with the old resource preview code. Please @@ -356,7 +362,7 @@ class IResourcePreview(Interface): ''' def can_preview(self, data_dict): - '''Return info on whether the plugin can preview the resource. + u'''Return info on whether the plugin can preview the resource. This can be done in two ways: @@ -389,7 +395,7 @@ def can_preview(self, data_dict): ''' def setup_template_variables(self, context, data_dict): - ''' + u''' Add variables to c just prior to the template being rendered. The ``data_dict`` contains the resource and the package. @@ -397,21 +403,21 @@ def setup_template_variables(self, context, data_dict): ''' def preview_template(self, context, data_dict): - ''' + u''' Returns a string representing the location of the template to be rendered for the read page. The ``data_dict`` contains the resource and the package. ''' class ITagController(Interface): - ''' + u''' Hook into the Tag controller. These will usually be called just before committing or returning the respective object, i.e. all validation, synchronization and authorization setup are complete. ''' def before_view(self, tag_dict): - ''' + u''' Extensions will recieve this before the tag gets displayed. The dictionary passed will be the one that gets sent to the template. @@ -420,12 +426,12 @@ def before_view(self, tag_dict): class IGroupController(Interface): - """ + u''' Hook into the Group controller. These will usually be called just before committing or returning the respective object, i.e. all validation, synchronization and authorization setup are complete. - """ + ''' def read(self, entity): pass @@ -446,7 +452,7 @@ def delete(self, entity): pass def before_view(self, pkg_dict): - ''' + u''' Extensions will recieve this before the group gets displayed. The dictionary passed will be the one that gets sent to the template. @@ -455,12 +461,12 @@ def before_view(self, pkg_dict): class IOrganizationController(Interface): - """ + u''' Hook into the Organization controller. These will usually be called just before committing or returning the respective object, i.e. all validation, synchronization and authorization setup are complete. - """ + ''' def read(self, entity): pass @@ -481,7 +487,7 @@ def delete(self, entity): pass def before_view(self, pkg_dict): - ''' + u''' Extensions will recieve this before the organization gets displayed. The dictionary passed will be the one that gets sent to the template. @@ -490,10 +496,10 @@ def before_view(self, pkg_dict): class IPackageController(Interface): - """ + u''' Hook into the package controller. (see IGroupController) - """ + ''' def read(self, entity): pass @@ -514,7 +520,7 @@ def delete(self, entity): pass def after_create(self, context, pkg_dict): - ''' + u''' Extensions will receive the validated data dict after the package has been created (Note that the create method will return a package domain object, which may not include all fields). Also the newly @@ -523,7 +529,7 @@ def after_create(self, context, pkg_dict): pass def after_update(self, context, pkg_dict): - ''' + u''' Extensions will receive the validated data dict after the package has been updated (Note that the edit method will return a package domain object, which may not include all fields). @@ -531,14 +537,14 @@ def after_update(self, context, pkg_dict): pass def after_delete(self, context, pkg_dict): - ''' + u''' Extensions will receive the data dict (tipically containing just the package id) after the package has been deleted. ''' pass def after_show(self, context, pkg_dict): - ''' + u''' Extensions will receive the validated data dict after the package is ready for display (Note that the read method will return a package domain object, which may not include all fields). @@ -546,7 +552,7 @@ def after_show(self, context, pkg_dict): pass def before_search(self, search_params): - ''' + u''' Extensions will receive a dictionary with the query parameters, and should return a modified (or not) version of it. @@ -558,7 +564,7 @@ def before_search(self, search_params): return search_params def after_search(self, search_results, search_params): - ''' + u''' Extensions will receive the search results, as well as the search parameters, and should return a modified (or not) object with the same structure: @@ -577,7 +583,7 @@ def after_search(self, search_results, search_params): return search_results def before_index(self, pkg_dict): - ''' + u''' Extensions will receive what will be given to the solr for indexing. This is essentially a flattened dict (except for multli-valued fields such as tags) of all the terms sent to @@ -587,7 +593,7 @@ def before_index(self, pkg_dict): return pkg_dict def before_view(self, pkg_dict): - ''' + u''' Extensions will recieve this before the dataset gets displayed. The dictionary passed will be the one that gets sent to the template. @@ -596,12 +602,12 @@ def before_view(self, pkg_dict): class IResourceController(Interface): - """ + u''' Hook into the resource controller. - """ + ''' def before_create(self, context, resource): - """ + u''' Extensions will receive this before a resource is created. :param context: The context object of the current request, this @@ -610,11 +616,11 @@ def before_create(self, context, resource): :param resource: An object representing the resource to be added to the dataset (the one that is about to be created). :type resource: dictionary - """ + ''' pass def after_create(self, context, resource): - """ + u''' Extensions will receive this after a resource is created. :param context: The context object of the current request, this @@ -626,11 +632,11 @@ def after_create(self, context, resource): set to ``upload`` when the resource file is uploaded instead of linked. :type resource: dictionary - """ + ''' pass def before_update(self, context, current, resource): - """ + u''' Extensions will receive this before a resource is updated. :param context: The context object of the current request, this @@ -641,11 +647,11 @@ def before_update(self, context, current, resource): :param resource: An object representing the updated resource which will replace the ``current`` one. :type resource: dictionary - """ + ''' pass def after_update(self, context, resource): - """ + u''' Extensions will receive this after a resource is updated. :param context: The context object of the current request, this @@ -657,11 +663,11 @@ def after_update(self, context, resource): ``url_type`` which is set to ``upload`` when the resource file is uploaded instead of linked. :type resource: dictionary - """ + ''' pass def before_delete(self, context, resource, resources): - """ + u''' Extensions will receive this before a previously created resource is deleted. @@ -676,11 +682,11 @@ def before_delete(self, context, resource, resources): be deleted (including the resource to be deleted if it existed in the package). :type resources: list - """ + ''' pass def after_delete(self, context, resources): - """ + u''' Extensions will receive this after a previously created resource is deleted. @@ -690,11 +696,11 @@ def after_delete(self, context, resources): :param resources: A list of objects representing the remaining resources after a resource has been removed. :type resource: list - """ + ''' pass def before_show(self, resource_dict): - ''' + u''' Extensions will receive the validated data dict before the resource is ready for display. @@ -706,61 +712,77 @@ def before_show(self, resource_dict): class IPluginObserver(Interface): - """ + u''' Plugin to the plugin loading mechanism - """ + ''' def before_load(self, plugin): - """ + u''' Called before a plugin is loaded This method is passed the plugin class. - """ + ''' def after_load(self, service): - """ + u''' Called after a plugin has been loaded. This method is passed the instantiated service object. - """ + ''' def before_unload(self, plugin): - """ + u''' Called before a plugin is loaded This method is passed the plugin class. - """ + ''' def after_unload(self, service): - """ + u''' Called after a plugin has been unloaded. This method is passed the instantiated service object. - """ + ''' class IConfigurable(Interface): - """ - Pass configuration to plugins and extensions - """ + u''' + Initialization hook for plugins. + See also :py:class:`IConfigurer`. + ''' def configure(self, config): - """ - Called by load_environment - """ + u''' + Called during CKAN's initialization. + + This function allows plugins to initialize themselves during + CKAN's initialization. It is called after most of the + environment (e.g. the database) is already set up. + + Note that this function is not only called during the + initialization of the main CKAN process but also during the + execution of paster commands and background jobs, since these + run in separate processes and are therefore initialized + independently. + + :param config: dict-like configuration object + :type config: :py:class:`ckan.common.CKANConfig` + ''' class IConfigurer(Interface): - """ + u''' Configure CKAN environment via the ``config`` object - """ + + See also :py:class:`IConfigurable`. + ''' def update_config(self, config): - """ + u''' Called by load_environment at earliest point when config is available to plugins. The config should be updated in place. :param config: ``config`` object - """ + ''' def update_config_schema(self, schema): - ''' + u''' Return a schema with the runtime-editable config options CKAN will use the returned schema to decide which configuration options @@ -787,27 +809,27 @@ def update_config_schema(self, schema): class IActions(Interface): - """ + u''' Allow adding of actions to the logic layer. - """ + ''' def get_actions(self): - """ + u''' Should return a dict, the keys being the name of the logic function and the values being the functions themselves. By decorating a function with the `ckan.logic.side_effect_free` decorator, the associated action will be made available by a GET request (as well as the usual POST request) through the action API. - """ + ''' class IValidators(Interface): - """ + u''' Add extra validators to be returned by :py:func:`ckan.plugins.toolkit.get_validator`. - """ + ''' def get_validators(self): - """Return the validator functions provided by this plugin. + u'''Return the validator functions provided by this plugin. Return a dictionary mapping validator names (strings) to validator functions. For example:: @@ -817,14 +839,14 @@ def get_validators(self): These validator functions would then be available when a plugin calls :py:func:`ckan.plugins.toolkit.get_validator`. - """ + ''' class IAuthFunctions(Interface): - '''Override CKAN's authorization functions, or add new auth functions.''' + u'''Override CKAN's authorization functions, or add new auth functions.''' def get_auth_functions(self): - '''Return the authorization functions provided by this plugin. + u'''Return the authorization functions provided by this plugin. Return a dictionary mapping authorization function names (strings) to functions. For example:: @@ -891,7 +913,7 @@ def my_create_action(context, data_dict): class ITemplateHelpers(Interface): - '''Add custom template helper functions. + u'''Add custom template helper functions. By implementing this plugin interface plugins can provide their own template helper functions, which custom templates can then access via the @@ -901,7 +923,7 @@ class ITemplateHelpers(Interface): ''' def get_helpers(self): - '''Return a dict mapping names to helper functions. + u'''Return a dict mapping names to helper functions. The keys of the dict should be the names with which the helper functions will be made available to templates, and the values should be @@ -916,7 +938,7 @@ def get_helpers(self): class IDatasetForm(Interface): - '''Customize CKAN's dataset (package) schemas and forms. + u'''Customize CKAN's dataset (package) schemas and forms. By implementing this interface plugins can customise CKAN's dataset schema, for example to add new custom fields to datasets. @@ -936,7 +958,7 @@ class IDatasetForm(Interface): ''' def package_types(self): - '''Return an iterable of package types that this plugin handles. + u'''Return an iterable of package types that this plugin handles. If a request involving a package of one of the returned types is made, then this plugin instance will be delegated to. @@ -949,7 +971,7 @@ def package_types(self): ''' def is_fallback(self): - '''Return ``True`` if this plugin is the fallback plugin. + u'''Return ``True`` if this plugin is the fallback plugin. When no IDatasetForm plugin's ``package_types()`` match the ``type`` of the package being processed, the fallback plugin is delegated to @@ -967,7 +989,7 @@ def is_fallback(self): ''' def create_package_schema(self): - '''Return the schema for validating new dataset dicts. + u'''Return the schema for validating new dataset dicts. CKAN will use the returned schema to validate and convert data coming from users (via the dataset form or API) when creating new datasets, @@ -990,7 +1012,7 @@ def create_package_schema(self): ''' def update_package_schema(self): - '''Return the schema for validating updated dataset dicts. + u'''Return the schema for validating updated dataset dicts. CKAN will use the returned schema to validate and convert data coming from users (via the dataset form or API) when updating datasets, before @@ -1013,7 +1035,7 @@ def update_package_schema(self): ''' def show_package_schema(self): - ''' + u''' Return a schema to validate datasets before they're shown to the user. CKAN will use the returned schema to validate and convert data coming @@ -1039,7 +1061,7 @@ def show_package_schema(self): ''' def setup_template_variables(self, context, data_dict): - '''Add variables to the template context for use in templates. + u'''Add variables to the template context for use in templates. This function is called before a dataset template is rendered. If you have custom dataset templates that require some additional variables, @@ -1050,7 +1072,7 @@ def setup_template_variables(self, context, data_dict): ''' def new_template(self): - '''Return the path to the template for the new dataset page. + u'''Return the path to the template for the new dataset page. The path should be relative to the plugin's templates dir, e.g. ``'package/new.html'``. @@ -1060,7 +1082,7 @@ def new_template(self): ''' def read_template(self): - '''Return the path to the template for the dataset read page. + u'''Return the path to the template for the dataset read page. The path should be relative to the plugin's templates dir, e.g. ``'package/read.html'``. @@ -1077,7 +1099,7 @@ def read_template(self): ''' def edit_template(self): - '''Return the path to the template for the dataset edit page. + u'''Return the path to the template for the dataset edit page. The path should be relative to the plugin's templates dir, e.g. ``'package/edit.html'``. @@ -1087,7 +1109,7 @@ def edit_template(self): ''' def search_template(self): - '''Return the path to the template for use in the dataset search page. + u'''Return the path to the template for use in the dataset search page. This template is used to render each dataset that is listed in the search results on the dataset search page. @@ -1100,7 +1122,7 @@ def search_template(self): ''' def history_template(self): - '''Return the path to the template for the dataset history page. + u'''Return the path to the template for the dataset history page. The path should be relative to the plugin's templates dir, e.g. ``'package/history.html'``. @@ -1110,7 +1132,7 @@ def history_template(self): ''' def resource_template(self): - '''Return the path to the template for the resource read page. + u'''Return the path to the template for the resource read page. The path should be relative to the plugin's templates dir, e.g. ``'package/resource_read.html'``. @@ -1120,7 +1142,7 @@ def resource_template(self): ''' def package_form(self): - '''Return the path to the template for the dataset form. + u'''Return the path to the template for the dataset form. The path should be relative to the plugin's templates dir, e.g. ``'package/form.html'``. @@ -1130,7 +1152,7 @@ def package_form(self): ''' def resource_form(self): - '''Return the path to the template for the resource form. + u'''Return the path to the template for the resource form. The path should be relative to the plugin's templates dir, e.g. ``'package/snippets/resource_form.html'`` @@ -1139,7 +1161,7 @@ def resource_form(self): ''' def validate(self, context, data_dict, schema, action): - """Customize validation of datasets. + u'''Customize validation of datasets. When this method is implemented it is used to perform all validation for these datasets. The default implementation calls and returns the @@ -1167,11 +1189,11 @@ def validate(self, context, data_dict, schema, action): dataset and errors is a dictionary with keys matching data_dict and lists-of-string-error-messages as values :rtype: (dictionary, dictionary) - """ + ''' class IGroupForm(Interface): - """ + u''' Allows customisation of the group controller as a plugin. The behaviour of the plugin is determined by 5 method hooks: @@ -1197,12 +1219,12 @@ class IGroupForm(Interface): ckan.lib.plugins.DefaultGroupForm which provides default behaviours for the 5 method hooks. - """ + ''' ##### These methods control when the plugin is delegated to ##### def is_fallback(self): - """ + u''' Returns true if this provides the fallback behaviour, when no other plugin instance matches a group's type. @@ -1210,10 +1232,10 @@ def is_fallback(self): register more than one will throw an exception at startup. If there's no fallback registered at startup the ckan.lib.plugins.DefaultGroupForm used as the fallback. - """ + ''' def group_types(self): - """ + u''' Returns an iterable of group type strings. If a request involving a group of one of those types is made, then @@ -1222,10 +1244,10 @@ def group_types(self): There must only be one plugin registered to each group type. Any attempts to register more than one plugin instance to a given group type will raise an exception at startup. - """ + ''' def group_controller(self): - """ + u''' Returns the name of the group controller. The group controller is the controller, that is used to handle requests @@ -1233,76 +1255,76 @@ def group_controller(self): If this method is not provided, the default group controller is used (`group`). - """ + ''' ##### End of control methods ##### Hooks for customising the GroupController's behaviour ##### ##### TODO: flesh out the docstrings a little more. ##### def new_template(self): - """ + u''' Returns a string representing the location of the template to be rendered for the 'new' page. Uses the default_group_type configuration option to determine which plugin to use the template from. - """ + ''' def index_template(self): - """ + u''' Returns a string representing the location of the template to be rendered for the index page. Uses the default_group_type configuration option to determine which plugin to use the template from. - """ + ''' def read_template(self): - """ + u''' Returns a string representing the location of the template to be rendered for the read page - """ + ''' def history_template(self): - """ + u''' Returns a string representing the location of the template to be rendered for the history page - """ + ''' def edit_template(self): - """ + u''' Returns a string representing the location of the template to be rendered for the edit page - """ + ''' def group_form(self): - """ + u''' Returns a string representing the location of the template to be - rendered. e.g. "group/new_group_form.html". - """ + rendered. e.g. ``group/new_group_form.html``. + ''' def form_to_db_schema(self): - """ + u''' Returns the schema for mapping group data from a form to a format suitable for the database. - """ + ''' def db_to_form_schema(self): - """ + u''' Returns the schema for mapping group data from the database into a format suitable for the form (optional) - """ + ''' def check_data_dict(self, data_dict): - """ + u''' Check if the return data is correct. raise a DataError if not. - """ + ''' def setup_template_variables(self, context, data_dict): - """ + u''' Add variables to c just prior to the template being rendered. - """ + ''' def validate(self, context, data_dict, schema, action): - """Customize validation of groups. + u'''Customize validation of groups. When this method is implemented it is used to perform all validation for these groups. The default implementation calls and returns the @@ -1331,12 +1353,12 @@ def validate(self, context, data_dict, schema, action): group and errors is a dictionary with keys matching data_dict and lists-of-string-error-messages as values :rtype: (dictionary, dictionary) - """ + ''' ##### End of hooks ##### class IFacets(Interface): - '''Customize the search facets shown on search pages. + u'''Customize the search facets shown on search pages. By implementing this interface plugins can customize the search facets that are displayed for filtering search results on the dataset search page, @@ -1377,7 +1399,7 @@ class IFacets(Interface): ''' def dataset_facets(self, facets_dict, package_type): - '''Modify and return the ``facets_dict`` for the dataset search page. + u'''Modify and return the ``facets_dict`` for the dataset search page. The ``package_type`` is the type of package that these facets apply to. Plugins can provide different search facets for different types of @@ -1396,7 +1418,7 @@ def dataset_facets(self, facets_dict, package_type): return facets_dict def group_facets(self, facets_dict, group_type, package_type): - '''Modify and return the ``facets_dict`` for a group's page. + u'''Modify and return the ``facets_dict`` for a group's page. The ``package_type`` is the type of package that these facets apply to. Plugins can provide different search facets for different types of @@ -1422,7 +1444,7 @@ def group_facets(self, facets_dict, group_type, package_type): return facets_dict def organization_facets(self, facets_dict, organization_type, package_type): - '''Modify and return the ``facets_dict`` for an organization's page. + u'''Modify and return the ``facets_dict`` for an organization's page. The ``package_type`` is the type of package that these facets apply to. Plugins can provide different search facets for different types of @@ -1451,13 +1473,13 @@ def organization_facets(self, facets_dict, organization_type, package_type): class IAuthenticator(Interface): - '''EXPERIMENTAL + u'''EXPERIMENTAL Allows custom authentication methods to be integrated into CKAN. Currently it is experimental and the interface may change.''' def identify(self): - '''called to identify the user. + u'''called to identify the user. If the user is identified then it should set c.user: The id of the user @@ -1467,36 +1489,36 @@ def identify(self): ''' def login(self): - '''called at login.''' + u'''called at login.''' def logout(self): - '''called at logout.''' + u'''called at logout.''' def abort(self, status_code, detail, headers, comment): - '''called on abort. This allows aborts due to authorization issues + u'''called on abort. This allows aborts due to authorization issues to be overriden''' return (status_code, detail, headers, comment) class ITranslation(Interface): def i18n_directory(self): - '''Change the directory of the .mo translation files''' + u'''Change the directory of the .mo translation files''' def i18n_locales(self): - '''Change the list of locales that this plugin handles ''' + u'''Change the list of locales that this plugin handles ''' def i18n_domain(self): - '''Change the gettext domain handled by this plugin''' + u'''Change the gettext domain handled by this plugin''' class IUploader(Interface): - ''' + u''' Extensions implementing this interface can provide custom uploaders to upload resources and group images. ''' def get_uploader(self, upload_to, old_filename): - '''Return an uploader object to upload general files that must + u'''Return an uploader object to upload general files that must implement the following methods: ``__init__(upload_to, old_filename=None)`` @@ -1540,7 +1562,7 @@ def get_uploader(self, upload_to, old_filename): ''' def get_resource_uploader(self): - '''Return an uploader object used to upload resource files that must + u'''Return an uploader object used to upload resource files that must implement the following methods: ``__init__(resource)`` @@ -1572,7 +1594,7 @@ def get_resource_uploader(self): class IPermissionLabels(Interface): - ''' + u''' Extensions implementing this interface can override the permission labels applied to datasets to precisely control which datasets are visible to each user. @@ -1585,7 +1607,7 @@ class IPermissionLabels(Interface): ''' def get_dataset_labels(self, dataset_obj): - ''' + u''' Return a list of unicode strings to be stored in the search index as the permission lables for a dataset dict. @@ -1597,7 +1619,7 @@ def get_dataset_labels(self, dataset_obj): ''' def get_user_dataset_labels(self, user_obj): - ''' + u''' Return the permission labels that give a user permission to view a dataset. If any of the labels returned from this method match any of the labels returned from :py:meth:`.get_dataset_labels`
diff --git a/ckan/tests/config/test_environment.py b/ckan/tests/config/test_environment.py --- a/ckan/tests/config/test_environment.py +++ b/ckan/tests/config/test_environment.py @@ -40,10 +40,14 @@ def _setup_env_vars(self): # plugin.load() will force the config to update p.load() + def setup(self): + self._old_config = dict(config) + def teardown(self): for env_var, _ in self.ENV_VAR_LIST: if os.environ.get(env_var, None): del os.environ[env_var] + config.update(self._old_config) # plugin.load() will force the config to update p.load() diff --git a/ckan/tests/lib/test_jobs.py b/ckan/tests/lib/test_jobs.py --- a/ckan/tests/lib/test_jobs.py +++ b/ckan/tests/lib/test_jobs.py @@ -10,8 +10,12 @@ import rq import ckan.lib.jobs as jobs -from ckan.tests.helpers import changed_config, recorded_logs, RQTestBase from ckan.common import config +from ckan.logic import NotFound +from ckan import model + +from ckan.tests.helpers import (call_action, changed_config, recorded_logs, + RQTestBase) class TestQueueNamePrefixes(RQTestBase): @@ -141,6 +145,17 @@ def failing_job(): raise RuntimeError(u'JOB FAILURE') +def database_job(pkg_id, pkg_title): + u''' + A background job that uses the PostgreSQL database. + + Appends ``pkg_title`` to the title of package ``pkg_id``. + ''' + pkg_dict = call_action(u'package_show', id=pkg_id) + pkg_dict[u'title'] += pkg_title + pkg_dict = call_action(u'package_update', **pkg_dict) + + class TestWorker(RQTestBase): def test_worker_logging_lifecycle(self): @@ -199,3 +214,45 @@ def test_worker_multiple_queues(self): assert_equal(len(all_jobs), 1) assert_equal(jobs.remove_queue_name_prefix(all_jobs[0].origin), jobs.DEFAULT_QUEUE_NAME) + + def test_worker_database_access(self): + u''' + Test database access from within the worker. + ''' + # See https://github.com/ckan/ckan/issues/3243 + pkg_name = u'test-worker-database-access' + try: + pkg_dict = call_action(u'package_show', id=pkg_name) + except NotFound: + pkg_dict = call_action(u'package_create', name=pkg_name) + pkg_dict[u'title'] = u'foo' + pkg_dict = call_action(u'package_update', **pkg_dict) + titles = u'1 2 3'.split() + for title in titles: + self.enqueue(database_job, args=[pkg_dict[u'id'], title]) + jobs.Worker().work(burst=True) + # Aside from ensuring that the jobs succeeded, this also checks + # that database access still works in the main process. + pkg_dict = call_action(u'package_show', id=pkg_name) + assert_equal(pkg_dict[u'title'], u'foo' + u''.join(titles)) + + def test_fork_within_a_transaction(self): + u''' + Test forking a worker horse within a database transaction. + + The horse should get a new SQLAlchemy session but leave the + original session alone. + ''' + pkg_name = u'test-fork-within-a-transaction' + model.repo.new_revision() + pkg = model.Package.get(pkg_name) + if not pkg: + pkg = model.Package(name=pkg_name) + pkg.title = u'foo' + pkg.save() + pkg.title = u'bar' + self.enqueue(database_job, [pkg.id, u'foo']) + jobs.Worker().work(burst=True) + assert_equal(pkg.title, u'bar') # Original session is unchanged + pkg.Session.refresh(pkg) + assert_equal(pkg.title, u'foofoo') # Worker only saw committed changes diff --git a/ckan/tests/test_coding_standards.py b/ckan/tests/test_coding_standards.py --- a/ckan/tests/test_coding_standards.py +++ b/ckan/tests/test_coding_standards.py @@ -428,7 +428,6 @@ def find_unprefixed_string_literals(filename): u'ckan/model/vocabulary.py', u'ckan/pastertemplates/__init__.py', u'ckan/plugins/core.py', - u'ckan/plugins/interfaces.py', u'ckan/plugins/toolkit.py', u'ckan/plugins/toolkit_sphinx_extension.py', u'ckan/tests/config/test_environment.py',
Multiple background jobs that access the database fail (This problem was originally reported by @wardi in #3165) Accessing the database from a background job succeeds once, but subsequent runs of the same job fail: ``` DatabaseError: (DatabaseError) SSL error: decryption failed or bad record mac ```
An `engine.dispose()` at the start of the task should be the "quick" fix. Ideally each worker gets its own engine and thus its own pool. @TkTech I tried that but it didn't work for me. Certainly possible I disposed the wrong engine or something silly like that though. For me, calling `ckan.model.meta.engine.dispose()` in the worker's child process after forking solves the problem within the worker, but afterwards database access in the main process fails with a ``` OperationalError: (OperationalError) SSL connection has been closed unexpectedly ``` Not sure if we also need to reset some stuff in the main process, although I don't see a reason why that should be necessary as of now. However, in addition to SQLAlchemy's non-support for forks (which requires the call to `engine.dispose`), there may be [issues with SSL and forking](https://github.com/ui/django-rq/issues/123). I haven't examined that in detail, yet.
2016-09-20T11:23:35
ckan/ckan
3,258
ckan__ckan-3258
[ "2345" ]
a5408647c18bcc3a6317a8c83cfb37c72068e90c
diff --git a/ckanext/datastore/plugin.py b/ckanext/datastore/plugin.py --- a/ckanext/datastore/plugin.py +++ b/ckanext/datastore/plugin.py @@ -120,7 +120,6 @@ def configure(self, config): 'of _table_metadata are skipped.') else: self._check_urls_and_permissions() - self._create_alias_table() def notify(self, entity, operation=None): if not isinstance(entity, model.Package) or self.legacy_mode: @@ -216,34 +215,6 @@ def _read_connection_has_correct_privileges(self): write_connection.close() return True - def _create_alias_table(self): - mapping_sql = ''' - SELECT DISTINCT - substr(md5(dependee.relname || COALESCE(dependent.relname, '')), 0, 17) AS "_id", - dependee.relname AS name, - dependee.oid AS oid, - dependent.relname AS alias_of - -- dependent.oid AS oid - FROM - pg_class AS dependee - LEFT OUTER JOIN pg_rewrite AS r ON r.ev_class = dependee.oid - LEFT OUTER JOIN pg_depend AS d ON d.objid = r.oid - LEFT OUTER JOIN pg_class AS dependent ON d.refobjid = dependent.oid - WHERE - (dependee.oid != dependent.oid OR dependent.oid IS NULL) AND - (dependee.relname IN (SELECT tablename FROM pg_catalog.pg_tables) - OR dependee.relname IN (SELECT viewname FROM pg_catalog.pg_views)) AND - dependee.relnamespace = (SELECT oid FROM pg_namespace WHERE nspname='public') - ORDER BY dependee.oid DESC; - ''' - create_alias_table_sql = u'CREATE OR REPLACE VIEW "_table_metadata" AS {0}'.format(mapping_sql) - try: - connection = db._get_engine( - {'connection_url': self.write_url}).connect() - connection.execute(create_alias_table_sql) - finally: - connection.close() - def get_actions(self): actions = {'datastore_create': action.datastore_create, 'datastore_upsert': action.datastore_upsert,
Datastore _table_metadata view recreated on every startup We fixed the read/write test having conflicting table names by randomizing them (https://github.com/ckan/ckan/pull/1397, https://github.com/ckan/ckan/issues/2082) but there's still another database call that can cause problems on busy sites: creating the _table_metadata view. https://github.com/ckan/ckan/blob/b1c12f74b09c4703407563861e089e37ec0e19e2/ckanext/datastore/plugin.py#L80 My understanding of PostgreSQL views was once it's created, they update automatically without any further interaction. And if it's being recreated, all read queries against that view are locked until it is done? Does this view really need to be created and/or recreated every time the plugin is loaded? Could it be done once on installation (either with documentation for a paster command or checking that it does not exist/is not the right structure before proceeding)?
@maxious You're right, this doesn't seem to make sense. Should we introduce migrations for the datastore database to avoid this "live migration" thing we seem to be doing now? Maybe start a directory under the datastore extension.
2016-09-27T10:06:03
ckan/ckan
3,261
ckan__ckan-3261
[ "3076" ]
a5408647c18bcc3a6317a8c83cfb37c72068e90c
diff --git a/ckanext/datastore/plugin.py b/ckanext/datastore/plugin.py --- a/ckanext/datastore/plugin.py +++ b/ckanext/datastore/plugin.py @@ -48,6 +48,7 @@ class DatastoreException(Exception): class DatastorePlugin(p.SingletonPlugin): p.implements(p.IConfigurable, inherit=True) + p.implements(p.IConfigurer) p.implements(p.IActions) p.implements(p.IAuthFunctions) p.implements(p.IResourceUrlChange) @@ -71,6 +72,9 @@ def __new__(cls, *args, **kwargs): return super(cls, cls).__new__(cls, *args, **kwargs) + def update_config(self, config): + p.toolkit.add_template_directory(config, 'templates') + def configure(self, config): self.config = config # check for ckan.datastore.write_url and ckan.datastore.read_url
Datastore API Demo modal window encourages robots to make needless queries ### CKAN Version if known (or site URL) 2.1 ---> 2.5.2 http://demo.ckan.org/dataset/gold-prices/resource/b9aae52b-b082-4159-b46f-7bb9c158d013 ### Please describe the expected behaviour the CKAN Data API modal window designed to demonstrate the syntax for using the datastore API should not encourage robots to make queries against the database ### Please describe the actual behaviour the modal window includes hyperlinked text for all resources ... ``` Query example (first 5 results) http://demo.ckan.org/api/action/datastore_search?resource_id=b9aae52b-b082-4159-b46f-7bb9c158d013&limit=5 Query example (results containing 'jones') http://demo.ckan.org/api/action/datastore_search?resource_id=b9aae52b-b082-4159-b46f-7bb9c158d013&q=jones Query example (via SQL statement) http://demo.ckan.org/api/action/datastore_search_sql?sql=SELECT * from "b9aae52b-b082-4159-b46f-7bb9c158d013" WHERE title LIKE 'jones' ``` These hyperlinks encourage robots - that do not follow robots.txt instructions - to conduct needless queries that result in db errors against all the data resources. ### What steps can be taken to reproduce the issue? The modal window [page template ](https://github.com/ckan/ckan/blob/b7204bb307abb1f488b5d409262db40b1e840d59/ckan/templates/ajax_snippets/api_info.html) should be redone to remove the hyperlinks.
2016-09-29T16:48:52
ckan/ckan
3,284
ckan__ckan-3284
[ "3265" ]
c02e1d0ddc47a67dddf02319fd28a92780db41b4
diff --git a/ckan/lib/cli.py b/ckan/lib/cli.py --- a/ckan/lib/cli.py +++ b/ckan/lib/cli.py @@ -861,12 +861,9 @@ def remove(self): return username = self.args[1] - user = model.User.by_name(unicode(username)) - if not user: - print 'Error: user "%s" not found!' % username - return - user.delete() - model.repo.commit_and_remove() + p.toolkit.get_action('user_delete')( + {'model': model, 'ignore_auth': True}, + {'id': username}) print('Deleted user: %s' % username) diff --git a/ckan/logic/action/delete.py b/ckan/logic/action/delete.py --- a/ckan/logic/action/delete.py +++ b/ckan/logic/action/delete.py @@ -56,7 +56,7 @@ def user_delete(context, data_dict): user.delete() user_memberships = model.Session.query(model.Member).filter( - model.Member.table_id == user_id).all() + model.Member.table_id == user.id).all() for membership in user_memberships: membership.delete()
diff --git a/ckan/tests/logic/action/test_delete.py b/ckan/tests/logic/action/test_delete.py --- a/ckan/tests/logic/action/test_delete.py +++ b/ckan/tests/logic/action/test_delete.py @@ -491,6 +491,74 @@ def test_bad_id_returns_404(self): helpers.call_action, 'dataset_purge', id='123') +class TestUserDelete(object): + def setup(self): + helpers.reset_db() + + def test_user_delete(self): + user = factories.User() + context = {} + params = {u'id': user[u'id']} + + helpers.call_action(u'user_delete', context, **params) + + # It is still there but with state=deleted + user_obj = model.User.get(user[u'id']) + assert_equals(user_obj.state, u'deleted') + + def test_user_delete_removes_memberships(self): + user = factories.User() + factories.Organization( + users=[{u'name': user[u'id'], u'capacity': u'admin'}]) + + factories.Group( + users=[{u'name': user[u'id'], u'capacity': u'admin'}]) + + user_memberships = model.Session.query(model.Member).filter( + model.Member.table_id == user[u'id']).all() + + assert_equals(len(user_memberships), 2) + + assert_equals([m.state for m in user_memberships], + [u'active', u'active']) + + context = {} + params = {u'id': user[u'id']} + + helpers.call_action(u'user_delete', context, **params) + + user_memberships = model.Session.query(model.Member).filter( + model.Member.table_id == user[u'id']).all() + + # Member objects are still there, but flagged as deleted + assert_equals(len(user_memberships), 2) + + assert_equals([m.state for m in user_memberships], + [u'deleted', u'deleted']) + + def test_user_delete_removes_memberships_when_using_name(self): + user = factories.User() + factories.Organization( + users=[{u'name': user[u'id'], u'capacity': u'admin'}]) + + factories.Group( + users=[{u'name': user[u'id'], u'capacity': u'admin'}]) + + context = {} + params = {u'id': user[u'name']} + + helpers.call_action(u'user_delete', context, **params) + + user_memberships = model.Session.query(model.Member).filter( + model.Member.table_id == user[u'id']).all() + + # Member objects are still there, but flagged as deleted + assert_equals(len(user_memberships), 2) + + assert_equals([m.state for m in user_memberships], + [u'deleted', u'deleted']) + + class TestJobClear(helpers.FunctionalRQTestBase): def test_all_queues(self):
Users are not removed in related tables (i.e. Institution users) if the main user entry is deleted ### CKAN Version if known (or site URL) 2.4 ### Please describe the expected behaviour An user assigned to different organisations / roles should be removed from each group / role if the user is deleted. If not, zombie user entries persist in the system. ### Please describe the actual behaviour The users are not deleted from groups / roles if the main user entry is deleted. ### What steps can be taken to reproduce the issue? Check the relations between main user tables and the related tables. In detail, is the relation a real relational one or not (is the delete flag set or not)?
2016-10-21T12:55:04
ckan/ckan
3,285
ckan__ckan-3285
[ "3282" ]
c02e1d0ddc47a67dddf02319fd28a92780db41b4
diff --git a/ckan/lib/i18n.py b/ckan/lib/i18n.py --- a/ckan/lib/i18n.py +++ b/ckan/lib/i18n.py @@ -27,8 +27,9 @@ def get_locales_from_config(): the config AND also the locals available subject to the config. ''' locales_offered = config.get('ckan.locales_offered', '').split() filtered_out = config.get('ckan.locales_filtered_out', '').split() - locale_default = config.get('ckan.locale_default', 'en') + locale_default = [config.get('ckan.locale_default', 'en')] locale_order = config.get('ckan.locale_order', '').split() + known_locales = get_locales() all_locales = (set(known_locales) | set(locales_offered) |
LanguageError: IOError: [Errno 2] No translation file found for domain: 'ckan' Hi, We are noticing some 500 errors are being generated when /e or /n are being passed instead of /en Passing other letters such as /a /b /c will trigger a 404 ### CKAN Version if known (or site URL) Ckan 2.3.X - 2.5.2+ ### Please describe the expected behaviour http://demo.ckan.org/en = 200 http://demo.ckan.org/e = 404 http://demo.ckan.org/n = 404 ### Please describe the actual behaviour http://demo.ckan.org/en = 200 http://demo.ckan.org/e = 500 http://demo.ckan.org/n = 500 ### What steps can be taken to reproduce the issue? pass /e or /n in any ckan instance url and you can trigger a 500 internal server error. http://demo.ckan.org/en/dataset = 200 http://demo.ckan.org/e/dataset = 500
2016-10-21T13:52:25
ckan/ckan
3,301
ckan__ckan-3301
[ "3292" ]
65e49562bdde004879c1233af5b2c5f5ff852b10
diff --git a/ckan/plugins/interfaces.py b/ckan/plugins/interfaces.py --- a/ckan/plugins/interfaces.py +++ b/ckan/plugins/interfaces.py @@ -1618,6 +1618,12 @@ def get_resource_uploader(self): :param resource: resource dict :type resource: dictionary + Optionally, this method can set the following two attributes + on the class instance so they are set in the resource object: + + filesize (int): Uploaded file filesize. + mimetype (str): Uploaded file mimetype. + ``upload(id, max_size)`` Perform the actual upload.
Create a file filesize function as a part of iUploader interface ### CKAN Version if known (or site URL) ### Please describe the expected behaviour This PR was merge https://github.com/ckan/ckan/pull/3205 recently, and it works great! The only problem is that other extensions that override the default upload functionality don't have those alts, and it would be cool to implement a function that would be a part of an interface so that further extensions development will require this function. ### Please describe the actual behaviour ### What steps can be taken to reproduce the issue?
@gleb-rudenko If I remember correctly, the IUploader interface just returns an Uploader class. In the default uploader that was modified in #3205 the `self.filesize` and `self.mimetype` properties are set on the `__init__()` method, so I guess that any custom implementation could do the same, using whatever logic applies to their backend. I don't think we need to have a separate function, just [document on the interface](https://github.com/ckan/ckan/blob/master/ckan/plugins/interfaces.py#L1610:L1639) that extensions can set these two properties if they want to support it. Does this make sense? Do you want to send a quick PR with these changes? @amercader , sounds good
2016-11-04T07:25:23
ckan/ckan
3,334
ckan__ckan-3334
[ "3316" ]
d6fb44b655918f80abec7e36996cd7b439c4aeaa
diff --git a/ckan/i18n/check_po_files.py b/ckan/i18n/check_po_files.py --- a/ckan/i18n/check_po_files.py +++ b/ckan/i18n/check_po_files.py @@ -6,11 +6,6 @@ paster check-po-files --help for usage. - -Requires polib <http://pypi.python.org/pypi/polib>: - - pip install polib - ''' import polib import re
Module 'polib' missing from requirements.txt ### CKAN Version if known (or site URL) latest (originally reported as 2.6.0) ### Please describe the expected behaviour I have a copy of contrib/docker/docker-compose.yml, modified to fix #3075. When I run 'docker-compose up', I expect a running set of containers to be launched. ### Please describe the actual behaviour When I run 'docker-compose up', this error shows up ``` ckan | from ckan.config.environment import load_environment ckan | File "/usr/lib/ckan/default/src/ckan/ckan/config/environment.py", line 17, in <module> ckan | import ckan.lib.helpers as helpers ckan | File "/usr/lib/ckan/default/src/ckan/ckan/lib/helpers.py", line 33, in <module> ckan | import i18n ckan | File "/usr/lib/ckan/default/src/ckan/ckan/lib/i18n.py", line 52, in <module> ckan | import polib ckan | ImportError: No module named polib ``` ### What steps can be taken to reproduce the issue? run 'docker-compose up' It looks like you need to recreate the requirements.txt file.
2016-11-25T23:40:35
ckan/ckan
3,337
ckan__ckan-3337
[ "3332" ]
82a12f28ac9e2e30210426c97bbdb97fc2f78c56
diff --git a/ckan/config/environment.py b/ckan/config/environment.py --- a/ckan/config/environment.py +++ b/ckan/config/environment.py @@ -284,6 +284,8 @@ def update_config(): except sqlalchemy.exc.InternalError: # The database is not initialised. Travis hits this pass - # if an extension or our code does not finish - # transaction properly db cli commands can fail + + # Close current session and open database connections to ensure a clean + # clean environment even if an error occurs later on model.Session.remove() + model.Session.bind.dispose() diff --git a/ckan/lib/jobs.py b/ckan/lib/jobs.py --- a/ckan/lib/jobs.py +++ b/ckan/lib/jobs.py @@ -29,6 +29,7 @@ from ckan.lib.redis import connect_to_redis from ckan.common import config from ckan.config.environment import load_environment +from ckan.model import meta log = logging.getLogger(__name__) @@ -256,3 +257,18 @@ def main_work_horse(self, job, queue): # after forking. load_environment(config[u'global_conf'], config) return super(Worker, self).main_work_horse(job, queue) + + def perform_job(self, *args, **kwargs): + result = super(Worker, self).perform_job(*args, **kwargs) + # rq.Worker.main_work_horse does a hard exit via os._exit directly + # after its call to perform_job returns. Hence here is the correct + # location to clean up. + try: + meta.Session.remove() + except Exception: + log.exception(u'Error while closing database session') + try: + meta.engine.dispose() + except Exception: + log.exception(u'Error while disposing database engine') + return result
[CircleCI] - Test fails - SSL connection has been closed unexpectedly Sometimes CircleCI test fails, the cause is that SSL connection has been closed unexpectedly.
2016-11-28T12:37:51
ckan/ckan
3,340
ckan__ckan-3340
[ "3328" ]
356c6452b57b1ca50db3e39871c8a742bd7607f9
diff --git a/ckan/config/routing.py b/ckan/config/routing.py --- a/ckan/config/routing.py +++ b/ckan/config/routing.py @@ -93,6 +93,10 @@ def make_map(): map.minimization = False map.explicit = True + # CUSTOM ROUTES HERE + for plugin in p.PluginImplementations(p.IRoutes): + map = plugin.before_map(map) + # The ErrorController route (handles 404/500 error pages); it should # likely stay at the top, ensuring it can always be resolved. map.connect('/error/{action}', controller='error', ckan_core=True) @@ -101,10 +105,6 @@ def make_map(): map.connect('*url', controller='home', action='cors_options', conditions=OPTIONS, ckan_core=True) - # CUSTOM ROUTES HERE - for plugin in p.PluginImplementations(p.IRoutes): - map = plugin.before_map(map) - # Mark all routes added from extensions on the `before_map` extension point # as non-core for route in map.matchlist:
Ckan creates ErrorHandler route before calling plugins before_map method, making it impossible to customize error handling. Ckan documentation states [here](http://docs.ckan.org/en/latest/extensions/plugin-interfaces.html?highlight=before_map#ckan.plugins.interfaces.IRoutes.before_map) that IRoutes.before_map gets called before the routes map is generated. However, in routing.make_map code, the error handler route is generated before calling the IRoute methods : # The ErrorController route (handles 404/500 error pages); it should # likely stay at the top, ensuring it can always be resolved. map.connect('/error/{action}', controller='error', ckan_core=True) map.connect('/error/{action}/{id}', controller='error', ckan_core=True) map.connect('*url', controller='home', action='cors_options', conditions=OPTIONS, ckan_core=True) # CUSTOM ROUTES HERE for plugin in p.PluginImplementations(p.IRoutes): map = plugin.before_map(map) This prevents connecting error actions to a customized error controller.
That sounds reasonable. Do you want to submit a PR that moves the routes below the extension point? Sure, I will make the changes and I will do the PR.
2016-11-29T20:23:21
ckan/ckan
3,353
ckan__ckan-3353
[ "3352" ]
d87e2d731a4a5afe7573b62ab274b7f686a90422
diff --git a/ckan/logic/action/get.py b/ckan/logic/action/get.py --- a/ckan/logic/action/get.py +++ b/ckan/logic/action/get.py @@ -818,6 +818,9 @@ def user_list(context, data_dict): :param order_by: which field to sort the list by (optional, default: ``'name'``). Can be any user field or ``edits`` (i.e. number_of_edits). :type order_by: string + :param all_fields: return full user dictionaries instead of just names. + (optional, default: ``True``) + :type all_fields: boolean :rtype: list of user dictionaries. User properties include: ``number_of_edits`` which counts the revisions by the user and @@ -831,26 +834,30 @@ def user_list(context, data_dict): q = data_dict.get('q', '') order_by = data_dict.get('order_by', 'name') + all_fields = asbool(data_dict.get('all_fields', True)) - query = model.Session.query( - model.User, - model.User.name.label('name'), - model.User.fullname.label('fullname'), - model.User.about.label('about'), - model.User.about.label('email'), - model.User.created.label('created'), - _select([_func.count(model.Revision.id)], - _or_( - model.Revision.author == model.User.name, - model.Revision.author == model.User.openid - )).label('number_of_edits'), - _select([_func.count(model.Package.id)], - _and_( - model.Package.creator_user_id == model.User.id, - model.Package.state == 'active', - model.Package.private == False, - )).label('number_created_packages') - ) + if all_fields: + query = model.Session.query( + model.User, + model.User.name.label('name'), + model.User.fullname.label('fullname'), + model.User.about.label('about'), + model.User.about.label('email'), + model.User.created.label('created'), + _select([_func.count(model.Revision.id)], + _or_( + model.Revision.author == model.User.name, + model.Revision.author == model.User.openid + )).label('number_of_edits'), + _select([_func.count(model.Package.id)], + _and_( + model.Package.creator_user_id == model.User.id, + model.Package.state == 'active', + model.Package.private == False, + )).label('number_created_packages') + ) + else: + query = model.Session.query(model.User.name) if q: query = model.User.search(q, query, user_name=context.get('user')) @@ -861,7 +868,6 @@ def user_list(context, data_dict): _or_( model.Revision.author == model.User.name, model.Revision.author == model.User.openid)))) - else: query = query.order_by( _case([( @@ -879,9 +885,13 @@ def user_list(context, data_dict): users_list = [] - for user in query.all(): - result_dict = model_dictize.user_dictize(user[0], context) - users_list.append(result_dict) + if all_fields: + for user in query.all(): + result_dict = model_dictize.user_dictize(user[0], context) + users_list.append(result_dict) + else: + for user in query.all(): + users_list.append(user[0]) return users_list
diff --git a/ckan/tests/logic/action/test_get.py b/ckan/tests/logic/action/test_get.py --- a/ckan/tests/logic/action/test_get.py +++ b/ckan/tests/logic/action/test_get.py @@ -570,6 +570,16 @@ def test_user_list_excludes_deleted_users(self): assert len(got_users) == 1 assert got_users[0]['name'] == user['name'] + def test_user_list_not_all_fields(self): + + user = factories.User() + + got_users = helpers.call_action('user_list', all_fields=False) + + assert len(got_users) == 1 + got_user = got_users[0] + assert got_user == user['name'] + class TestUserShow(helpers.FunctionalTestBase):
Add a user_list option that returns just names instead of dicts user_list currently returns a dict for each user and the enhancement is to add an option to allow returning the user names. DGU has 30k users and it takes 3 minutes, which is no good for a web request. Whereas returning just the names takes 10 seconds, skipping the dictization and the additional parts of the query that adds up revisions by the user. package_list and group_list both return either names or dicts, depending on the `all_fields` parameter, so the proposal is to do the same, the only difference being that the default is True, for backward compatibility. (Other list actions just return dicts.)
2016-12-06T10:51:59
ckan/ckan
3,355
ckan__ckan-3355
[ "3354" ]
d87e2d731a4a5afe7573b62ab274b7f686a90422
diff --git a/ckan/model/__init__.py b/ckan/model/__init__.py --- a/ckan/model/__init__.py +++ b/ckan/model/__init__.py @@ -255,6 +255,8 @@ def delete_all(self): else: tables = reversed(self.metadata.sorted_tables) for table in tables: + if table.name == 'migrate_version': + continue connection.execute('delete from "%s"' % table.name) self.session.commit() log.info('Database table data deleted')
Initializing test db is not idempotent Running nosetests deletes the `migrate_version` table, which means that subsequent runs of `paster db init -c test-core.ini` [don't work](https://gist.github.com/davidread/af650b9227e5ed54d891dbeeb0e2c254). This is an issue when you are writing provision scripts, because the easiest thing is for these commands to be idempotent so they can be run repeatedly without harmful effect or error. So it is helpful if our tests don't delete the `migrate_version` table. How to reproduce: ``` dropdb ckan_test createdb ckan_test -O ckan_default paster --plugin=ckan db init -c test-core.ini nosetests --ckan --with-pylons=test-core.ini ckan/tests/controllers/test_admin.py:TestTrashView.test_trash_purge_deleted_datasets # or any test # You can see the table is gone with this: sudo -u postgres psql ckan_test -c 'select * from migrate_version;' # Now run init again, as if you are running the provision script again paster --plugin=ckan db init -c test-core.ini # That didn't work - see the error here: https://gist.github.com/davidread/af650b9227e5ed54d891dbeeb0e2c254 ``` Because of this issue, my ansible play is: ``` shell: psql ckan_test -c 'select name from package limit 1' | grep row && echo TestDatabaseAlreadyInitialized || /usr/lib/ckan/bin/paster --plugin=ckan db init -c /usr/lib/ckan/src/ckan/test-core.ini sudo: true sudo_user: postgres register: cmd_result changed_when: cmd_result.stdout.find('TestDatabaseAlreadyInitialized') == -1 ``` whereas with this fix it can simply be: ``` command: /usr/lib/ckan/bin/paster --plugin=ckan db init -c /usr/lib/ckan/src/ckan/test-core.ini ```
2016-12-06T11:54:49
ckan/ckan
3,420
ckan__ckan-3420
[ "3419" ]
4d588e000a620ff0fa12533e751ea8957a8c1aa8
diff --git a/ckan/config/environment.py b/ckan/config/environment.py --- a/ckan/config/environment.py +++ b/ckan/config/environment.py @@ -256,7 +256,6 @@ def update_config(): env.install_gettext_callables(_, ungettext, newstyle=True) # custom filters env.filters['empty_and_escape'] = jinja_extensions.empty_and_escape - env.filters['truncate'] = jinja_extensions.truncate config['pylons.app_globals'].jinja_env = env # CONFIGURATION OPTIONS HERE (note: all config options will override diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py --- a/ckan/config/middleware/flask_app.py +++ b/ckan/config/middleware/flask_app.py @@ -86,7 +86,6 @@ def make_flask_stack(conf, **app_conf): app.jinja_env.add_extension(extension) app.jinja_env.filters['empty_and_escape'] = \ jinja_extensions.empty_and_escape - app.jinja_env.filters['truncate'] = jinja_extensions.truncate # Common handlers for all requests app.before_request(ckan_before_request) diff --git a/ckan/lib/jinja_extensions.py b/ckan/lib/jinja_extensions.py --- a/ckan/lib/jinja_extensions.py +++ b/ckan/lib/jinja_extensions.py @@ -9,7 +9,6 @@ from jinja2 import ext from jinja2.exceptions import TemplateNotFound from jinja2.utils import open_if_exists, escape -from jinja2.filters import do_truncate from jinja2 import Environment import ckan.lib.base as base @@ -27,19 +26,6 @@ def empty_and_escape(value): else: return escape(value) -def truncate(value, length=255, killwords=None, end='...'): - ''' A more clever truncate. If killwords is supplied we use the default - truncate. Otherwise we try to truncate using killwords=False, if this - truncates the whole value we try again with killwords=True ''' - if value is None: - return None - if killwords is not None: - return do_truncate(value, length=length, killwords=killwords, end=end) - result = do_truncate(value, length=length, killwords=False, end=end) - if result != end: - return result - return do_truncate(value, length=length, killwords=True, end=end) - ### Tags def regularise_html(html):
TypeError: do_truncate() takes at least 2 arguments (4 given) ### CKAN Version if known (or site URL) 2.6.0 and 2.7.1a (Master Branch) ### Please describe the expected behaviour User can view any object via a get request, examples are user, organization or dataset, but basically trying to view any overview page of a CKAN 'thing'. ### Please describe the actual behaviour Jinja template throws 500 error performing the do_truncate operation (see screenshot). For example, if I click on my username in the header toolbar or on the name of a dataset the error occurs. ![screen shot 2017-01-30 at 12 03 30](https://cloud.githubusercontent.com/assets/6863551/22423991/5a95ebfe-e6ec-11e6-9a1d-318b8f9c4df7.png) ### What steps can be taken to reproduce the issue? So far I've built docker images with both 2.6.0 and the master branch built from source. The Jinja repository released a 2.8.1 on 29 December which could be the root cause of this issue. The CKAN requirements list a dependency on Jinja 2.8, so it's possible a breaking change was introduced in 2.8.1. I'm going to try to update to Jinja 2.9 to see if that helps.
Using version 2.9.5 of Jinja with CKAN 2.6.0 has the same issue One moment.
2017-01-30T14:13:50
ckan/ckan
3,442
ckan__ckan-3442
[ "2866" ]
b582c7a9501d0241458790ba9c4b2e7734d2cf41
diff --git a/ckanext/datapusher/logic/action.py b/ckanext/datapusher/logic/action.py --- a/ckanext/datapusher/logic/action.py +++ b/ckanext/datapusher/logic/action.py @@ -9,6 +9,7 @@ import requests +import ckan.lib.helpers as h import ckan.lib.navl.dictization_functions import ckan.logic as logic import ckan.plugins as p @@ -59,8 +60,8 @@ def datapusher_submit(context, data_dict): datapusher_url = config.get('ckan.datapusher.url') - site_url = config['ckan.site_url'] - callback_url = site_url.rstrip('/') + '/api/3/action/datapusher_hook' + site_url = h.url_for('/', qualified=True) + callback_url = h.url_for('/api/3/action/datapusher_hook', qualified=True) user = p.toolkit.get_action('user_show')(context, {'id': context['user']})
Datapusher error when root_path is set Hi, After setting **root_path** variable in CKAN config file, Datapusher no longer works. We always get: ``` Error: Process completed but unable to post to result_url ``` Contents of datapusher.error.log: ``` [Fri Feb 05 09:20:00.905675 2016] [:error] [pid 5997:tid 140341959157632] Exception AttributeError: "'NoneType' object has no attribute 'Error'" in <generator object raw at 0x7fa3d9384410> ignored [Fri Feb 05 11:16:52.104411 2016] [:error] [pid 1502:tid 140224457529088] /usr/lib/ckan/datapusher/lib/python2.7/site-packages/sqlalchemy/sql/sqltypes.py:185: SAWarning: Unicode type received non-unicode bind param value 'ca8c86c6-ca87-4b36-b6bb-3...'. (this warning may be suppressed after 10 occurrences) [Fri Feb 05 11:16:52.119255 2016] [:error] [pid 1502:tid 140224457529088] (util.ellipses_string(value),)) [Fri Feb 05 11:16:57.624008 2016] [:error] [pid 1502:tid 140224457529088] Job "push_to_datastore (trigger: RunTriggerNow, run = True, next run at: None)" raised an exception [Fri Feb 05 11:16:57.624065 2016] [:error] [pid 1502:tid 140224457529088] Traceback (most recent call last): [Fri Feb 05 11:16:57.624096 2016] [:error] [pid 1502:tid 140224457529088] File "/usr/lib/ckan/datapusher/lib/python2.7/site-packages/apscheduler/scheduler.py", line 512, in _run_job [Fri Feb 05 11:16:57.624106 2016] [:error] [pid 1502:tid 140224457529088] retval = job.func(*job.args, **job.kwargs) [Fri Feb 05 11:16:57.624116 2016] [:error] [pid 1502:tid 140224457529088] File "/usr/lib/ckan/datapusher/src/datapusher/datapusher/jobs.py", line 287, in push_to_datastore [Fri Feb 05 11:16:57.624125 2016] [:error] [pid 1502:tid 140224457529088] resource = get_resource(resource_id, ckan_url, api_key) [Fri Feb 05 11:16:57.624134 2016] [:error] [pid 1502:tid 140224457529088] File "/usr/lib/ckan/datapusher/src/datapusher/datapusher/jobs.py", line 233, in get_resource [Fri Feb 05 11:16:57.624143 2016] [:error] [pid 1502:tid 140224457529088] check_response(r, url, 'CKAN') [Fri Feb 05 11:16:57.624151 2016] [:error] [pid 1502:tid 140224457529088] File "/usr/lib/ckan/datapusher/src/datapusher/datapusher/jobs.py", line 144, in check_response [Fri Feb 05 11:16:57.624160 2016] [:error] [pid 1502:tid 140224457529088] response=response.text) [Fri Feb 05 11:16:57.624168 2016] [:error] [pid 1502:tid 140224457529088] HTTPError ``` If we don't use the root_path variable and set our subpath in site_url then Datapusher works again but some CKAN extensions like **archiver/qa** get broken as they need the **root_path** variable to get the subpath. We think this is related to #2599 Any help to fix this would be appreciated. Thank you in advance.
The `result_url` is the callback URL that CKAN tells the DataPusher to ping once it has finished its importing. It should point to the `/api/3/action/datapusher_hook` endpoint. Right now this URL is constructed using [`ckan.site_url`](https://github.com/ckan/ckan/blob/master/ckanext/datapusher/logic/action.py#L52:L53) and my gut feeling is that this is the correct approach. I think there is definitely some confusion regarding `ckan.site_url` and `ckan.root_path`. @wardi [here](https://github.com/ckan/ckanext-qa/issues/20#issuecomment-153342639) you seem to suggest that `ckan.site_url` should not have path components but that's not what the [docs](http://docs.ckan.org/en/ckan-2.5.1/maintaining/configuration.html#ckan-site-url) say and a quick grep over the code shows that is generally used as being the full base url of the CKAN site ([eg](https://github.com/ckan/ckan/blob/master/ckan/lib/mailer.py#L138:L139)). I'm not sure what `ckan.root_path` was intended for (I guess for some i18n stuff) but I think that if extensions are relying on it to build URLs that's probably wrong http://docs.ckan.org/en/ckan-2.5.1/maintaining/configuration.html#ckan-site-url @amercader here's where I learned about root_path: https://github.com/ckan/ckan/pull/2599#issuecomment-134595167 Given that routes supports defining the structure of the complete url from hostname down with this variable, it's incorrect to build urls with site_url alone. We need to use url_for which should take root_path into account. I'd say the docs and other places in the code where urls are constructed manually need to be updated. So, which is the best approach? Setting `ckan.site_url` (then some extensions don't work) or setting `ckan.root_path` (then DataPusher fails)? I'm facing with the same issue.
2017-02-17T14:40:36
ckan/ckan
3,449
ckan__ckan-3449
[ "3443" ]
e9d58bbef27a0ad4e6ee5c6958104e99754b5911
diff --git a/ckan/lib/celery_app.py b/ckan/lib/celery_app.py --- a/ckan/lib/celery_app.py +++ b/ckan/lib/celery_app.py @@ -10,10 +10,14 @@ import logging import os -from celery import Celery from ckan.common import config as ckan_config from pkg_resources import iter_entry_points, VersionConflict +from celery import __version__ as celery_version, Celery +if not celery_version.startswith(u'3.'): + raise ImportError(u'Only Celery version 3.x is supported.') + + log = logging.getLogger(__name__) log.warning('ckan.lib.celery_app is deprecated, use ckan.lib.jobs instead.')
diff --git a/ckan/tests/lib/test_celery_app.py b/ckan/tests/lib/test_celery_app.py new file mode 100644 --- /dev/null +++ b/ckan/tests/lib/test_celery_app.py @@ -0,0 +1,27 @@ +# encoding: utf-8 + +u''' +Tests for ``ckan.lib.celery_app``. +''' + +from nose.tools import raises +import mock + + +class TestCeleryVersion(object): + u''' + Make sure that Celery's version is checked. + ''' + @mock.patch.dict(u'sys.modules', {u'celery': mock.MagicMock()}) + def check_celery_version(self, version): + import celery + celery.__version__ = version + import ckan.lib.celery_app + reload(ckan.lib.celery_app) + + def test_3x(self): + self.check_celery_version(u'3.1.25') + + @raises(ImportError) + def test_4x(self): + self.check_celery_version(u'4.0.0')
Missing requirement for Celery `requirements.in` and `requirements.txt` currently don't contain an entry for `celery`. While use of Celery [is optional](https://github.com/ckan/ckan/blob/727fe76a4da67fb590e87ce75c5284f145a6e495/ckan/model/__init__.py#L191) it is the [documented background job system for CKAN](http://docs.ckan.org/en/ckan-2.6.0/maintaining/background-tasks.html) as of CKAN 2.6. The problem is that CKAN's Celery code is incompatible with newer versions of Celery. For example, `pip install celery` pulls in 4.0.2, and using that within CKAN raises the following exception when initializing the database: ```$ /usr/lib/ckan/default/bin/paster --plugin=ckan db init -c /etc/ckan/default/production.ini Traceback (most recent call last): File "/usr/lib/ckan/default/bin/paster", line 11, in <module> sys.exit(run()) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/script/command.py", line 102, in run invoke(command, command_name, options, args[1:]) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/script/command.py", line 141, in invoke exit_code = runner.run(args) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/script/command.py", line 236, in run result = self.command() File "/usr/lib/ckan/default/src/ckan/ckan/lib/cli.py", line 223, in command model.repo.init_db() File "/usr/lib/ckan/default/src/ckan/ckan/model/__init__.py", line 192, in init_db import ckan.lib.celery_app as celery_app File "/usr/lib/ckan/default/src/ckan/ckan/lib/celery_app.py", line 65, in <module> celery.loader.conf.update(default_config) AttributeError: 'NoneType' object has no attribute 'update' ``` Reverting to the latest Celery 3.x version (3.1.25) solves the problem. We should therefore add a requirement for Celery and pin it to version 3.1.25. Given that CKAN 2.7 introduces a new system based on RQ and deprecates the Celery system I don't think we need to update our Celery code to work with Celery 4.x.
I'm -1 for adding the celery requirement if we haven't required up until now and are eventually going to drop support for it. We can either document that you need to `pip install celery==3.x.y` or update the code to support 4.x. The actual line that is failing seems [trivial](http://docs.celeryproject.org/en/latest/whatsnew-4.0.html#modules) to update (there might be other more subtle changes needed). Hm. I'm -1 on relying on documentation when all other requirements are taken care off automatically. A possible alternative would be to raise an `ImportError` in `celery_app` upon import if Celery's version is 4.x or later. That way nothing changes for people that don't use Celery and those who do get a meaningful error message. Changing the code to support 4.x may look trivial but would need to be properly tested. Since there are basically no tests for CKAN's celery system, adding support for 4.x might break non-obvious things. In my opinion that's too much risk or effort for a system that's going to be deprecated in the next version. OK, failing if Celery >= 4.x is very reasonable and sounds like the best option. We can use `pkg_resources` or check for a Celery 4 only property ```python import pkg_resources pkg_resources.get_distribution("construct").version ``` Or we simply use `celery.__version__` :wink: duh, I was being slow first thing I tried was `from celery import Celery; Celery.__version__` :upside_down_face:
2017-02-20T14:00:31
ckan/ckan
3,463
ckan__ckan-3463
[ "3195" ]
28c68abbe38700e26296c57986b92606cf27ba6a
diff --git a/ckan/config/middleware/pylons_app.py b/ckan/config/middleware/pylons_app.py --- a/ckan/config/middleware/pylons_app.py +++ b/ckan/config/middleware/pylons_app.py @@ -55,6 +55,8 @@ def make_pylons_stack(conf, full_stack=True, static_files=True, for plugin in PluginImplementations(IMiddleware): app = plugin.make_middleware(app, config) + app = common_middleware.RootPathMiddleware(app, config) + # Routing/Session/Cache Middleware app = RoutesMiddleware(app, config['routes.map']) # we want to be able to retrieve the routes middleware to be able to update @@ -173,8 +175,6 @@ def make_pylons_stack(conf, full_stack=True, static_files=True, if asbool(config.get('ckan.tracking_enabled', 'false')): app = common_middleware.TrackingMiddleware(app, config) - app = common_middleware.RootPathMiddleware(app, config) - # Add a reference to the actual Pylons app so it's easier to access app._wsgi_app = pylons_app
Fanstatic not honouring root_path ### CKAN Version if known (or site URL) master( 5f4949c924f3a95c59ab4faf0026629804b83f7a ) ### Please describe the expected behaviour Setting root_path to "/testing/{{LANG}} should make all links and resources fetched from www.site_url/testing/ ### Please describe the actual behaviour Most of the stuff is linked to /testing but js, css and the like is fetched from /fanstatic/... ### What steps can be taken to reproduce the issue? set `ckan.root_path = /testing/{{LANG}}/` Might be needed to look at my web setup as well. Using chef to setup apache2 and nginx as reverseproxy **nginx site:** ``` proxy_cache_path /tmp/nginx_cache levels=1:2 keys_zone=cache:30m max_size=250m; proxy_temp_path /tmp/nginx_proxy 1 2; server { client_max_body_size 100M; location /testing/ { proxy_pass http://127.0.0.1:8080/; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header Host $host; proxy_cache cache; proxy_cache_bypass $cookie_auth_tkt; proxy_no_cache $cookie_auth_tkt; proxy_cache_valid 30m; proxy_cache_key $host$scheme$proxy_host$request_uri; # In emergency comment out line to force caching # proxy_ignore_headers X-Accel-Expires Expires Cache-Control; } } ``` **apache2 site:** ``` <VirtualHost 127.0.0.1:8080> ServerName <%= @server_name %> ServerAlias <%= @server_alias %> WSGIScriptAlias / <%= @config_dir %>/apache.wsgi # Pass authorization info on (needed for rest api). WSGIPassAuthorization On # Deploy as a daemon (avoids conflicts between CKAN instances). WSGIDaemonProcess ckan_<%= @project_name %> display-name=ckan_<%= @project_name %> processes=2 threads=15 WSGIProcessGroup ckan_<%= @project_name %> ErrorLog /var/log/apache2/ckan_<%= @project_name %>.error.log CustomLog /var/log/apache2/ckan_<%= @project_name %>.custom.log combined <IfModule mod_rpaf.c> RPAFenable On RPAFsethostname On RPAFproxy_ips 127.0.0.1 </IfModule> <Directory /> Require all granted </Directory> </VirtualHost> ```
I can reproduce this in master and 2.6.0 using both paster serve and apache 2.4 w/mod_wsgi (without nginx) on Fedora 23 . The other config difference between my apache setup and @erlingbo's is I have `WSGIScriptAlias /data /etck/ckan/default/apache.wsgi` The problem for me is that the RootPathMiddleware has been moved back to the bottom of the WSGI stack in d9f3a5036a99c5e447ad93977e99ba745e2868c3 and it is messing up the environment for the Fanstatic middleware, i.e., Fanstatic is passed an empty `SCRIPT_NAME` and it doesn't know about `ckan.root_path`. Moving the RootPathMiddleware higher up the stack, as in #3090, resolves the issue for me. I am running ckan-2.5.3 and when I upgrade to master or to 2.6.0 my theme breaks in development. I am running paster serve with the following setting for root url in the config [composite:nonroot] use = egg:Paste#urlmap /ckan = main Basically everything being served by fanstatic is still being served from /fanstatic and not /ckan/fanstatic whis is obviously causing issues, above is very similar issue and I have tried adding the ckan.root_path but that does not seem to be working either. any advice would be appreciated as we are looking to upgrade to 2.6.0 in the very near future and need to rectify the themes first. The exact same settings as I describe above work fine with 2.5.3 @merkelct does the patch in #3090 fix your issue. By the way, that PR says merged but it was overwritten and so (I think) it doesn't exist in 2.6.0 or master @MrkGrgsn I believe that does solve my issue is their a plan to get it into master and 2.6.0? probably a bad merge of some of the flask work :-( looks like this code has moved to https://github.com/ckan/ckan/blob/master/ckan/config/middleware/pylons_app.py#L176 would you mind submitting a PR to restore the fix? no issue creating a PR but it says nothing to compare when trying to add the PR for #3090 into master or anything else for that matter it thinks it has already been merged ? might be as simple as a re-order in the pylons_app.py
2017-02-27T11:56:18
ckan/ckan
3,486
ckan__ckan-3486
[ "3230" ]
9c67d7ef8d7bcc219008394484fcc03f23293b2d
diff --git a/ckan/lib/mailer.py b/ckan/lib/mailer.py --- a/ckan/lib/mailer.py +++ b/ckan/lib/mailer.py @@ -144,11 +144,11 @@ def get_invite_body(user, group_dict=None, role=None): def get_reset_link(user): - return urljoin(config.get('site_url'), - h.url_for(controller='user', - action='perform_reset', - id=user.id, - key=user.reset_key)) + return h.url_for(controller='user', + action='perform_reset', + id=user.id, + key=user.reset_key, + qualified=True) def send_reset_link(user):
Reset link not including site_url ### CKAN Version if known (or site URL) master ### Please describe the expected behaviour The reset email should include the complete link to reset a users password. e.g http://mydomain.com/user/reset/<id>?key=<somekey> ### Please describe the actual behaviour The email only includes the subpath. e.g /user/reset/<id>?key=<somekey> ### What steps can be taken to reproduce the issue? Try to send a password recovery email. I think the fix lies in https://github.com/ckan/ckan/blob/master/ckan/lib/mailer.py#L147 Shouldn't it use `ckan.site_url` instead of just `site_url`
The code should probably just pass `qualified=True` to `url_for` instead of manually adding the host.
2017-03-15T16:06:58
ckan/ckan
3,514
ckan__ckan-3514
[ "3513" ]
711e42609ae62c5ad671ea812e35f983740c21fe
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -6,15 +6,31 @@ del os.link try: - from setuptools import setup, find_packages + from setuptools import (setup, find_packages, + __version__ as setuptools_version) except ImportError: from ez_setup import use_setuptools use_setuptools() - from setuptools import setup, find_packages + from setuptools import (setup, find_packages, + __version__ as setuptools_version) from ckan import (__version__, __description__, __long_description__, __license__) +MIN_SETUPTOOLS_VERSION = 20.4 +assert setuptools_version >= str(MIN_SETUPTOOLS_VERSION) and \ + int(setuptools_version.split('.')[0]) >= int(MIN_SETUPTOOLS_VERSION),\ + ('setuptools version error' + '\nYou need a newer version of setuptools.\n' + 'You have {current}, you need at least {minimum}' + '\nInstall the recommended version:\n' + ' pip install -r requirement-setuptools.txt\n' + 'and then try again to install ckan into your python environment.'.format( + current=setuptools_version, + minimum=MIN_SETUPTOOLS_VERSION + )) + + entry_points = { 'nose.plugins.0.10': [ 'main = ckan.ckan_nose_plugin:CkanNose',
Minimum setuptools version CKAN requires a recent version of setuptools ever since some of CKAN's dependencies were upgraded. However there's nothing in the install instructions to sort this out. The default setuptools for our recommended distro, Ubuntu Trusty 14.04, is 2.2, which is too old. Specifically: * repoze.who needs setuptools 11.3 or later https://github.com/repoze/repoze.who/issues/26 * html5lib needs setuptools 18.5 or later https://github.com/ckan/ckan/issues/3232
2017-03-28T11:31:27
ckan/ckan
3,521
ckan__ckan-3521
[ "3520" ]
f9f70173da31548a70aa39975bbd8959d1005401
diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py --- a/ckan/config/middleware/flask_app.py +++ b/ckan/config/middleware/flask_app.py @@ -1,7 +1,6 @@ # encoding: utf-8 import os -import importlib import inspect import itertools import pkgutil @@ -13,7 +12,6 @@ from werkzeug.exceptions import HTTPException from werkzeug.routing import Rule -from flask_debugtoolbar import DebugToolbarExtension from beaker.middleware import SessionMiddleware from paste.deploy.converters import asbool @@ -70,6 +68,7 @@ def make_flask_stack(conf, **app_conf): ' with the SECRET_KEY config option') if debug: + from flask_debugtoolbar import DebugToolbarExtension app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False DebugToolbarExtension(app)
flask_debugtoolbar dependency A clean install of ckan (master), following [docs](http://docs.ckan.org/en/latest/maintaining/installing/install-from-source.html#installing-ckan-from-source) suffers this exception: ``` (default)vagrant@vagrant-ubuntu-trusty-64:/usr/lib/ckan/default/src/ckan$ paster db init -c /etc/ckan/default/development.ini Traceback (most recent call last): File "/usr/lib/ckan/default/bin/paster", line 11, in <module> sys.exit(run()) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/script/command.py", line 102, in run invoke(command, command_name, options, args[1:]) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/script/command.py", line 141, in invoke exit_code = runner.run(args) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/script/command.py", line 236, in run result = self.command() File "/usr/lib/ckan/default/src/ckan/ckan/lib/cli.py", line 231, in command self._load_config(cmd!='upgrade') File "/usr/lib/ckan/default/src/ckan/ckan/lib/cli.py", line 170, in _load_config conf = self._get_config() File "/usr/lib/ckan/default/src/ckan/ckan/lib/cli.py", line 167, in _get_config return appconfig('config:' + self.filename) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/deploy/loadwsgi.py", line 261, in appconfig global_conf=global_conf) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/deploy/loadwsgi.py", line 296, in loadcontext global_conf=global_conf) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/deploy/loadwsgi.py", line 320, in _loadconfig return loader.get_context(object_type, name, global_conf) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/deploy/loadwsgi.py", line 454, in get_context section) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/deploy/loadwsgi.py", line 476, in _context_from_use object_type, name=use, global_conf=global_conf) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/deploy/loadwsgi.py", line 406, in get_context global_conf=global_conf) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/deploy/loadwsgi.py", line 296, in loadcontext global_conf=global_conf) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/deploy/loadwsgi.py", line 328, in _loadegg return loader.get_context(object_type, name, global_conf) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/deploy/loadwsgi.py", line 620, in get_context object_type, name=name) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/deploy/loadwsgi.py", line 646, in find_egg_entry_point possible.append((entry.load(), protocol, entry.name)) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 2203, in load return self.resolve() File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 2209, in resolve module = __import__(self.module_name, fromlist=['__name__'], level=0) File "/usr/lib/ckan/default/src/ckan/ckan/config/middleware/__init__.py", line 10, in <module> from ckan.config.middleware.flask_app import make_flask_stack File "/usr/lib/ckan/default/src/ckan/ckan/config/middleware/flask_app.py", line 16, in <module> from flask_debugtoolbar import DebugToolbarExtension ImportError: No module named flask_debugtoolbar ``` It looks like flask_debugtoolbar has been added to the dev-requirements.txt when it is actually required for all installs, so should be in requirements.txt. Or do you @amercader want to move the import to only occur when you use it, so that only people running in test mode require it?
@davidread yes, this should only be loaded if you are on debug mode. I'll submit a PR.
2017-03-30T11:43:22
ckan/ckan
3,526
ckan__ckan-3526
[ "2334" ]
1c40b381ccbfab7756c01d986fd80092e0d7ca5b
diff --git a/ckanext/datapusher/logic/action.py b/ckanext/datapusher/logic/action.py --- a/ckanext/datapusher/logic/action.py +++ b/ckanext/datapusher/logic/action.py @@ -84,18 +84,34 @@ def datapusher_submit(context, data_dict): 'error': '{}', } try: - task_id = p.toolkit.get_action('task_status_show')(context, { + existing_task = p.toolkit.get_action('task_status_show')(context, { 'entity_id': res_id, 'task_type': 'datapusher', 'key': 'datapusher' - })['id'] - task['id'] = task_id + }) + assume_task_stale_after = datetime.timedelta(seconds=int( + config.get('ckan.datapusher.assume_task_stale_after', 3600))) + if existing_task.get('state') == 'pending': + updated = datetime.datetime.strptime( + existing_task['last_updated'], '%Y-%m-%dT%H:%M:%S.%f') + time_since_last_updated = datetime.datetime.now() - updated + if time_since_last_updated > assume_task_stale_after: + # it's been a while since the job was last updated - it's more + # likely something went wrong with it and the state wasn't + # updated than its still in progress. Let it be restarted. + log.info('A pending task was found %r, but it is only %s hours' + 'old', existing_task['id'], time_since_last_updated) + else: + log.info('A pending task was found %s for this resource, so ' + 'skipping this duplicate task', existing_task['id']) + return False + + task['id'] = existing_task['id'] except logic.NotFound: pass context['ignore_auth'] = True - result = p.toolkit.get_action('task_status_update')(context, task) - task_id = result['id'] + p.toolkit.get_action('task_status_update')(context, task) try: r = requests.post(
diff --git a/ckanext/datapusher/tests/test_action.py b/ckanext/datapusher/tests/test_action.py --- a/ckanext/datapusher/tests/test_action.py +++ b/ckanext/datapusher/tests/test_action.py @@ -3,6 +3,7 @@ import datetime from nose.tools import eq_ +import mock import ckan.plugins as p from ckan.tests import helpers, factories @@ -278,3 +279,21 @@ def test_does_not_resubmit_if_a_dataset_field_changes_in_the_meantime( # Not called eq_(len(mock_datapusher_submit.mock_calls), 1) + + def test_duplicated_tasks(self): + def submit(res, user): + return helpers.call_action( + 'datapusher_submit', context=dict(user=user['name']), + resource_id=res['id']) + + user = factories.User() + res = factories.Resource(user=user) + with mock.patch('requests.post') as r_mock: + r_mock().json = mock.Mock( + side_effect=lambda: dict.fromkeys( + ['job_id', 'job_key'])) + r_mock.reset_mock() + submit(res, user) + submit(res, user) + + eq_(1, r_mock.call_count)
DatapusherPlugin implementation of notify() can call 'datapusher_submit' multiple times Hi, Currently `DatapusherPlugin` implements `notify()` from `IDomainObjectModification` & `IResourceUrlChange`. On our CKAN 2.3 portal this this means it's called twice; the first time, because operation == model.domain_object.DomainObjectOperation.new (IDomainObjectModification) and the second time because operation is not passed (IResourceUrlChange). It's been like that for a [long time](https://github.com/ckan/ckan/blame/8f298cd9e658d788b031a4059271210aff6a3d94/ckanext/datapusher/plugin.py) and I wonder it this has not been picked up before because it has not been tested with extensions that implement other interfaces leading to notify being called multiple times ? In my case implementing IResourceUrlChange sounds like a quick fix, but I'm wondering if this doesn't highlight that the logic in DatapusherPlugin should be re-considered? What do you think?
I think I've come up with a better answer to that problem. The datapusher doesn't check is there is a pending task before submitting a new one, so rather than fixing the hook, I've fixed that. ``` diff diff --git a/ckanext/datapusher/logic/action.py b/ckanext/datapusher/logic/action.py index 1af23c3..3ced61e 100644 --- a/ckanext/datapusher/logic/action.py +++ b/ckanext/datapusher/logic/action.py @@ -64,19 +64,23 @@ def datapusher_submit(context, data_dict): 'error': '{}', } try: - task_id = p.toolkit.get_action('task_status_show')(context, { + existing_task = p.toolkit.get_action('task_status_show')(context, { 'entity_id': res_id, 'task_type': 'datapusher', 'key': 'datapusher' - })['id'] - task['id'] = task_id + }) + + if existing_task is not None and existing_task.get('state') == 'pending': + log.info("A pending task was found %r, ignoring" % existing_task.get('id')) + return True + + task['id'] = existing_task.get('id') except logic.NotFound: pass - + context['ignore_auth'] = True - result = p.toolkit.get_action('task_status_update')(context, task) - task_id = result['id'] - + p.toolkit.get_action('task_status_update')(context, task) + try: r = requests.post( urlparse.urljoin(datapusher_url, 'job'), ``` What do you think? Will you take a PR for that?
2017-04-04T10:44:57
ckan/ckan
3,544
ckan__ckan-3544
[ "3543" ]
eee6decdbab330e0926942a0299754f33fceaa79
diff --git a/doc/conf.py b/doc/conf.py --- a/doc/conf.py +++ b/doc/conf.py @@ -52,7 +52,7 @@ .. |storage_path| replace:: |storage_parent_dir|/default .. |reload_apache| replace:: sudo service apache2 reload .. |restart_apache| replace:: sudo service apache2 restart -.. |restart_solr| replace:: sudo service jetty restart +.. |restart_solr| replace:: sudo service jetty8 restart .. |solr| replace:: Solr .. |restructuredtext| replace:: reStructuredText .. |nginx| replace:: Nginx
Ubuntu 16.04 Xenial compatibility 16.04 has been out a while, so it would be good to tweak the ckan install instructions to be compatible with it.
2017-04-14T21:57:37
ckan/ckan
3,559
ckan__ckan-3559
[ "3558" ]
bfc5fbd8406fb6b29e0e9bbd2c729082ab4cddea
diff --git a/ckan/controllers/group.py b/ckan/controllers/group.py --- a/ckan/controllers/group.py +++ b/ckan/controllers/group.py @@ -186,6 +186,7 @@ def index(self): 'type': group_type or 'group', 'limit': items_per_page, 'offset': items_per_page * (page - 1), + 'include_extras': True } page_results = self._action('group_list')(context, data_dict_page_results)
Groups should support multilingual schema fields Group templates are missing translation support for multilingual fields. E.g. templates should call get_translated for displayed group fields. I'll provide suggestions with a PR in a minute.
2017-05-09T12:48:16
ckan/ckan
3,596
ckan__ckan-3596
[ "3569" ]
b8368d0a33df5e50e3b244c8ac19736248efc491
diff --git a/ckan/config/environment.py b/ckan/config/environment.py --- a/ckan/config/environment.py +++ b/ckan/config/environment.py @@ -95,13 +95,13 @@ def find_controller(self, controller): for msg in msgs: warnings.filterwarnings('ignore', msg, sqlalchemy.exc.SAWarning) + # load all CKAN plugins + p.load_all() + # Check Redis availability if not is_redis_available(): log.critical('Could not connect to Redis.') - # load all CKAN plugins - p.load_all() - app_globals.reset() # issue #3260: remove idle transaction
[DOCKER] docker-compose up not working Running `docker-compose up -d` on the `docker-compose.yml` file in `contrib/docker` seems to result in the `ckan` container not running? When inspecting the `ckan` container logs it shows me this: ``` Distribution already installed: ckan 2.7.0a0 from /usr/lib/ckan/default/src/ckan Creating /etc/ckan/default/ckan.ini Now you should edit the config files /etc/ckan/default/ckan.ini 2017-05-18 17:46:43,354 ERROR [ckan.lib.redis] Redis is not available Traceback (most recent call last): File "/usr/lib/ckan/default/src/ckan/ckan/lib/redis.py", line 61, in is_redis_available return redis_conn.ping() File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/redis/client.py", line 682, in ping return self.execute_command('PING') File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/redis/client.py", line 578, in execute_command connection.send_command(*args) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/redis/connection.py", line 563, in send_command self.send_packed_command(self.pack_command(*args)) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/redis/connection.py", line 538, in send_packed_command self.connect() File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/redis/connection.py", line 442, in connect raise ConnectionError(self._error_message(e)) ConnectionError: Error 111 connecting to localhost:6379. Connection refused. 2017-05-18 17:46:43,355 CRITI [ckan.config.environment] Could not connect to Redis. Traceback (most recent call last): File "/usr/local/bin/ckan-paster", line 11, in <module> sys.exit(run()) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/script/command.py", line 102, in run invoke(command, command_name, options, args[1:]) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/script/command.py", line 141, in invoke exit_code = runner.run(args) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/script/command.py", line 236, in run result = self.command() File "/usr/lib/ckan/default/src/ckan/ckan/lib/cli.py", line 334, in command self._load_config(cmd!='upgrade') File "/usr/lib/ckan/default/src/ckan/ckan/lib/cli.py", line 303, in _load_config load_config(self.options.config, load_site_user) File "/usr/lib/ckan/default/src/ckan/ckan/lib/cli.py", line 221, in load_config load_environment(conf.global_conf, conf.local_conf) File "/usr/lib/ckan/default/src/ckan/ckan/config/environment.py", line 103, in load_environment p.load_all() File "/usr/lib/ckan/default/src/ckan/ckan/plugins/core.py", line 129, in load_all unload_all() File "/usr/lib/ckan/default/src/ckan/ckan/plugins/core.py", line 182, in unload_all unload(*reversed(_PLUGINS)) File "/usr/lib/ckan/default/src/ckan/ckan/plugins/core.py", line 210, in unload plugins_update() File "/usr/lib/ckan/default/src/ckan/ckan/plugins/core.py", line 121, in plugins_update environment.update_config() File "/usr/lib/ckan/default/src/ckan/ckan/config/environment.py", line 266, in update_config model.init_model(engine) File "/usr/lib/ckan/default/src/ckan/ckan/model/__init__.py", line 157, in init_model version_table = Table('migrate_version', meta.metadata, autoload=True) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/sqlalchemy/sql/schema.py", line 352, in __new__ table._init(name, metadata, *args, **kw) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/sqlalchemy/sql/schema.py", line 425, in _init self._autoload(metadata, autoload_with, include_columns) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/sqlalchemy/sql/schema.py", line 448, in _autoload self, include_columns, exclude_columns File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1670, in run_callable with self.contextual_connect() as conn: File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1737, in contextual_connect self.pool.connect(), File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/sqlalchemy/pool.py", line 332, in connect return _ConnectionFairy._checkout(self) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/sqlalchemy/pool.py", line 630, in _checkout fairy = _ConnectionRecord.checkout(pool) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/sqlalchemy/pool.py", line 433, in checkout rec = pool._do_get() File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/sqlalchemy/pool.py", line 949, in _do_get return self._create_connection() File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/sqlalchemy/pool.py", line 278, in _create_connection return _ConnectionRecord(self) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/sqlalchemy/pool.py", line 404, in __init__ self.connection = self.__connect() File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/sqlalchemy/pool.py", line 530, in __connect connection = self.__pool._creator() File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/sqlalchemy/engine/strategies.py", line 95, in connect connection_invalidated=invalidated File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 189, in raise_from_cause reraise(type(exception), exception, tb=exc_tb) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/sqlalchemy/engine/strategies.py", line 89, in connect return dialect.connect(*cargs, **cparams) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 376, in connect return self.dbapi.connect(*cargs, **cparams) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/psycopg2/__init__.py", line 179, in connect connection_factory=connection_factory, async=async) sqlalchemy.exc.OperationalError: (OperationalError) could not connect to server: Connection refused Is the server running on host "172.17.0.3" and accepting TCP/IP connections on port 5432? None None ``` Any ideas on what goes wrong?
@mattfullerton is this related to the ports issue you were discussion recently? Ok; so I made one little change which I didn't tell you all about, and apparently reverting this change solved my problem. It does pose a different challenge though. The change I made was to the binding of port 80 to port 5000 for the `ckan` container. I changed this line to: ``` - "8083:5000" ``` Apparently this breaks the whole setup. Which is a bad thing because you can't assume CKAN to be installed on a server which doesn't already use port 80 (e.g., we already bind port 80 via Docker to an Nginx load balancer). So my next question is, how can I change `docker-compose.yml` to not be dependent on binding port 80? @amercader yes - as you can see its trying to reach redis at localhost (this is in the code as a default - it can and should be overriden in the .ini for docker-compose) What I can't explain off the top of my head is why CKAN is trying to reach Postgres at 172.17.0.3 - that's a docker IP... but ideally it should be using the container name. I will try to get a look at this on a suitable machine ASAP. @mattfullerton I guess you see the Postgres docker container IP address because it already resolved it from the container name? I'm still not sure why changing the binding of port 80 causes the whole thing the break down. https://github.com/ckan/ckan/pull/3572 you should port docker-compose to version 3. now its in version 1 so binding works only via env vars @mattfullerton given your pull request, what values should I set for the environment variables in order to run `docker-compose up -d` without binding port 80? For that it's even easier: just change this line https://github.com/ckan/ckan/blob/master/contrib/docker/docker-compose.yml#L10 to something else instead of 80. That said, we need a way of piping through a site url. This is bad: https://github.com/ckan/ckan/blob/master/Dockerfile#L9 @mattfullerton I tried changing/removing that line but that still results in the errors shown at the top of this issue. update: I didn't try out your change in a correct way, so it might work. I'll try to test it later again.
2017-06-08T08:23:41
ckan/ckan
3,611
ckan__ckan-3611
[ "2228" ]
54d6c9b751f83d19084c2ebe49c498849b4c0741
diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py --- a/ckan/lib/helpers.py +++ b/ckan/lib/helpers.py @@ -1176,6 +1176,24 @@ def render_datetime(datetime_, date_format=None, with_hours=False): # if date_format was supplied we use it if date_format: + + # See http://bugs.python.org/issue1777412 + if datetime_.year < 1900: + year = str(datetime_.year) + + date_format = re.sub('(?<!%)((%%)*)%y', + r'\g<1>{year}'.format(year=year[-2:]), + date_format) + date_format = re.sub('(?<!%)((%%)*)%Y', + r'\g<1>{year}'.format(year=year), + date_format) + + datetime_ = datetime.datetime(2016, datetime_.month, datetime_.day, + datetime_.hour, datetime_.minute, + datetime_.second) + + return datetime_.strftime(date_format) + return datetime_.strftime(date_format) # the localised date return formatters.localised_nice_date(datetime_, show_date=True,
diff --git a/ckan/tests/legacy/lib/test_helpers.py b/ckan/tests/legacy/lib/test_helpers.py --- a/ckan/tests/legacy/lib/test_helpers.py +++ b/ckan/tests/legacy/lib/test_helpers.py @@ -39,6 +39,20 @@ def test_render_datetime_blank(self): res = h.render_datetime(None) assert_equal(res, '') + def test_render_datetime_year_before_1900(self): + res = h.render_datetime('1875-04-13T20:40:20.123456', date_format='%Y') + assert_equal(res, '1875') + + res = h.render_datetime('1875-04-13T20:40:20.123456', date_format='%y') + assert_equal(res, '75') + + def test_render_datetime_year_before_1900_escape_percent(self): + res = h.render_datetime('1875-04-13', date_format='%%%y') + assert_equal(res, '%75') + + res = h.render_datetime('1875-04-13', date_format='%%%Y') + assert_equal(res, '%1875') + def test_datetime_to_date_str(self): res = datetime.datetime(2008, 4, 13, 20, 40, 20, 123456).isoformat() assert_equal(res, '2008-04-13T20:40:20.123456')
Render_datetime can't handle dates before year 1900 Due to the python 2.7 feature datetime.strftime won't handle dates before year 1900 (http://bugs.python.org/issue1777412) https://github.com/ckan/ckan/blob/master/ckan/lib/helpers.py#L947
What are the chances users would accept rendering ISO8601 format all the time? We wouldn't need strftime for that. At least it should be documented that if users are allowed to input dates, use of render_datetime might create issues. @Zharktas at the developer meeting today it was suggested to catch the exception for such dates and fall back to a manual rendering of YYYY-MM-DD in this helper. What do you think? Sounds good, at least it would not cause an error anymore. We went with manual date render in our implementation: https://github.com/yhteentoimivuuspalvelut/ytp/blob/master/modules/ckanext-ytp-main/ckanext/ytp/common/helpers.py#L47 since we only need one date format. @wardi, what is the progress of this one? can it be closed? Still not fixed, and a really easy thing to contribute. I'll mark it as such @wardi Can I take this one? @klikstermkd absolutely! anything marked good for contribution is up for grabs
2017-06-16T20:00:51
ckan/ckan
3,614
ckan__ckan-3614
[ "2804" ]
54d6c9b751f83d19084c2ebe49c498849b4c0741
diff --git a/ckanext/datastore/backend/postgres.py b/ckanext/datastore/backend/postgres.py --- a/ckanext/datastore/backend/postgres.py +++ b/ckanext/datastore/backend/postgres.py @@ -855,6 +855,20 @@ def create_table(context, data_dict): field_ids = _pluck('id', supplied_fields) records = data_dict.get('records') + fields_errors = [] + + for field_id in field_ids: + # Postgres has a limit of 63 characters for a column name + if len(field_id) > 63: + message = 'Column heading "{0}" exceeds limit of 63 '\ + 'characters.'.format(field_id) + fields_errors.append(message) + + if fields_errors: + raise ValidationError({ + 'fields': fields_errors + }) + # if type is field is not given try and guess or throw an error for field in supplied_fields: if 'type' not in field:
diff --git a/ckanext/datastore/tests/test_create.py b/ckanext/datastore/tests/test_create.py --- a/ckanext/datastore/tests/test_create.py +++ b/ckanext/datastore/tests/test_create.py @@ -240,6 +240,21 @@ def test_sets_datastore_active_on_resource_on_delete(self): assert_equal(resource['datastore_active'], False) + @raises(p.toolkit.ValidationError) + def test_create_exceeds_column_name_limit(self): + package = factories.Dataset() + data = { + 'resource': { + 'package_id': package['id'] + }, + 'fields': [{ + 'id': 'This is a really long name for a column. Column names ' + 'in Postgres have a limit of 63 characters', + 'type': 'text' + }] + } + result = helpers.call_action('datastore_create', **data) + class TestDatastoreCreate(tests.WsgiAppCase): sysadmin_user = None
Column name length limit for datastore upload I'm running a pretty vanilla instance of CKAN 2.3, and am happily uploading CSV files into the datastore. I then hit this error on one of my CSV files: Error: CKAN DataStore bad response. Status code: 409 Conflict. At: http://localhost:8080/api/3/action/datastore_create. HTTP status code: 409 Response: {"help": "http://localhost:8080/api/3/action/help_show?name=datastore_create", "success": false, "error": {"records": ["row \"1\" has extra keys \"yjFai PSsU iTcJHt (mnCceKYD mO czqaAIa NboYAkitvNiU R... Requested URL: http://localhost:8080/api/3/action/datastore_create As it turns out, one of the column headings exceeded 63 characters. When I reduce the number of characters for that column, it uploads fine. The CSV I am using is a bit sensitive, so I have sanitized it. The structure however is preserved and this particular CSV causes the problem also: YJdpEvm,EoaU,sduZzPFs,PkQpw gnTwE YpbXCM (Fysaa zjYbgaF) (f),yjFai PSsU iTcJHt (mnCceKYD mO czqaAIa NboYAkitvNiU Ropv) (FUEnda) pIBYzL,19 WFKNmKL 1417,MFTZU,2.71,1.74 tvqVeL,35 lAcFOPY 3899,PEpOtKH PcE,7,-5.2 NLLKtc,32 BPUlrhQ 7605,RqYiTmB ymWTc,3.79,8.36 qNByi,78 ngSvYFO 1078,JMikZ jIEMHQc,4.3,7.35 UOvnE,94 XwwsknD 3620,CksWVV lOri,9.8,0.00 Zpg,PrZZB 8694,IAlZxEm,3.55,-4.8 CpzUty,56 JdDKDqHQ 4203,uJtxSFw uuq,3.1,2.4 lWmVUT,62 fhDDVahO 1141,LHHP ltvn,2,-9.63 If you change the last word in the heading line (FUEnda) to simply (F), it uploads fine. So, two questions: Is there a hard limit for column headings for the datastorer function? If so, is that configurable? Much thanks for any assistance. Logs are below: Snippet from datapusher.error.log: [Mon Dec 21 11:45:26 2015] [error] Deleting "indicator-4-2-0-5-1" from datastore. [Mon Dec 21 11:45:26 2015] [error] Determined headers and types: [{'type': u'text', 'id': u'YJdpEvm'}, {'type': u'text', 'id': u'EoaU'}, {'type': u'text', 'id': u'sduZzPFs'}, {'type': u'numeric', 'id': u'PkQpw gnTwE YpbXCM (Fysaa zjYbgaF) (f)'}, {'type': u'numeric', 'id': u'yjFai PSsU iTcJHt (mnCceKYD mO czqaAIa NboYAkitvNiU Ropv) (FUEnda)'}] [Mon Dec 21 11:45:26 2015] [error] Saving chunk 0 [Mon Dec 21 11:45:26 2015] [error] Job "push_to_datastore (trigger: RunTriggerNow, run = True, next run at: None)" raised an exception [Mon Dec 21 11:45:26 2015] [error] Traceback (most recent call last): [Mon Dec 21 11:45:26 2015] [error] File "/usr/lib/ckan/datapusher/lib/python2.7/site-packages/apscheduler/scheduler.py", line 512, in _run_job [Mon Dec 21 11:45:26 2015] [error] retval = job.func(_job.args, *_job.kwargs) [Mon Dec 21 11:45:26 2015] [error] File "/usr/lib/ckan/datapusher/src/datapusher/datapusher/jobs.py", line 387, in push_to_datastore [Mon Dec 21 11:45:26 2015] [error] records, api_key, ckan_url) [Mon Dec 21 11:45:26 2015] [error] File "/usr/lib/ckan/datapusher/src/datapusher/datapusher/jobs.py", line 203, in send_resource_to_datastore [Mon Dec 21 11:45:26 2015] [error] check_response(r, url, 'CKAN DataStore') [Mon Dec 21 11:45:26 2015] [error] File "/usr/lib/ckan/datapusher/src/datapusher/datapusher/jobs.py", line 137, in check_response [Mon Dec 21 11:45:26 2015] [error] request_url=request_url, response=response.text) [Mon Dec 21 11:45:26 2015] [error] HTTPError Snippet from ckan_default.error.log: [Mon Dec 21 11:49:56 2015] [error] 2015-12-21 11:49:56,820 ERROR [ckan.controllers.api] Validation error: '{\'records\': [u\'row "1" has extra keys "yjFai PSsU iTcJHt (mnCceKYD mO czqaAIa NboYAkitvNiU Ropv) (FUEnda)"\'], \'__type\': \'Validation Error\'}' [Mon Dec 21 11:49:56 2015] [error] 2015-12-21 11:49:56,821 INFO [ckan.lib.base] /api/3/action/datastore_create render time 0.051 seconds [Mon Dec 21 11:49:56 2015] [error] 2015-12-21 11:49:56,885 INFO [ckan.lib.base] /dataset/soe2015-storm-tide-inundation-4-2-0-5/resource_data/indicator-4-2-0-5-1 render time 0.290 seconds ... [Mon Dec 21 11:50:04 2015] [error] [client 127.0.0.1] mod_wsgi (pid=19910): Exception occurred processing WSGI script '/etc/ckan/default/apache.wsgi'. [Mon Dec 21 11:50:04 2015] [error] [client 127.0.0.1] IOError: failed to write data [Mon Dec 21 11:50:04 2015] [error] [client 127.0.0.1] mod_wsgi (pid=19911): Exception occurred processing WSGI script '/etc/ckan/default/apache.wsgi'. [Mon Dec 21 11:50:04 2015] [error] [client 127.0.0.1] IOError: failed to write data [Mon Dec 21 11:50:04 2015] [error] [client 127.0.0.1] mod_wsgi (pid=19911): Exception occurred processing WSGI script '/etc/ckan/default/apache.wsgi'. [Mon Dec 21 11:50:04 2015] [error] [client 127.0.0.1] IOError: failed to write data [Mon Dec 21 11:50:04 2015] [error] [client 127.0.0.1] mod_wsgi (pid=19911): Exception occurred processing WSGI script '/etc/ckan/default/apache.wsgi'. [Mon Dec 21 11:50:04 2015] [error] [client 127.0.0.1] IOError: failed to write data
The postgres maximum length for a column name is 63 characters, this probably isn't a coincidence. Not sure what could be done about it, other than warning the user. Thanks. Good to know. During the tech call we decided that pretty much all we can do about this is to clarify the error. I'll leave it open for now in case somebody would like to contribute a fix. Hey folks, what about ckan shows a fat error message in the UI saying "Column headers cannot contain more than 63 characters" when a user attempts uploading such a file. I just hit this, and it sure wasn't easy tracking the errors all the way here. Thanks! @rossjones I'll work on this.
2017-06-17T15:25:19
ckan/ckan
3,630
ckan__ckan-3630
[ "3629" ]
214ccf6924c59b918366c207fdc8cda0f2e0064f
diff --git a/ckan/controllers/group.py b/ckan/controllers/group.py --- a/ckan/controllers/group.py +++ b/ckan/controllers/group.py @@ -170,14 +170,24 @@ def index(self): context['user_id'] = c.userobj.id context['user_is_admin'] = c.userobj.sysadmin - data_dict_global_results = { - 'all_fields': False, - 'q': q, - 'sort': sort_by, - 'type': group_type or 'group', - } - global_results = self._action('group_list')(context, - data_dict_global_results) + try: + data_dict_global_results = { + 'all_fields': False, + 'q': q, + 'sort': sort_by, + 'type': group_type or 'group', + } + global_results = self._action('group_list')( + context, data_dict_global_results) + except ValidationError as e: + if e.error_dict and e.error_dict.get('message'): + msg = e.error_dict['message'] + else: + msg = str(e) + h.flash_error(msg) + c.page = h.Page([], 0) + return render(self._index_template(group_type), + extra_vars={'group_type': group_type}) data_dict_page_results = { 'all_fields': True,
diff --git a/ckan/tests/controllers/test_group.py b/ckan/tests/controllers/test_group.py --- a/ckan/tests/controllers/test_group.py +++ b/ckan/tests/controllers/test_group.py @@ -53,6 +53,20 @@ def test_page_thru_list_of_groups_preserves_sort_order(self): assert groups[-1]['title'] not in response2 assert groups[0]['title'] in response2 + def test_invalid_sort_param_does_not_crash(self): + app = self._get_test_app() + group_url = url_for(controller='group', + action='index', + sort='title desc nope') + + app.get(url=group_url) + + group_url = url_for(controller='group', + action='index', + sort='title nope desc nope') + + app.get(url=group_url) + def _get_group_new_page(app): user = factories.User()
Exception when providing a wrong sort param on group/org page Providing a sort param like `sort=title xx desc` or `sort=title xx` causes an exception due to an uncaught `ValidationError`
2017-06-23T10:04:42
ckan/ckan
3,631
ckan__ckan-3631
[ "3308" ]
214ccf6924c59b918366c207fdc8cda0f2e0064f
diff --git a/ckan/logic/auth/create.py b/ckan/logic/auth/create.py --- a/ckan/logic/auth/create.py +++ b/ckan/logic/auth/create.py @@ -195,7 +195,7 @@ def _check_group_auth(context, data_dict): groups = groups - set(pkg_groups) for group in groups: - if not authz.has_user_permission_for_group_or_org(group.id, user, 'update'): + if not authz.has_user_permission_for_group_or_org(group.id, user, 'manage_group'): return False return True
Problem adding datasets to a group on package_create, the user has 'Editor' capacity ### CKAN Version if known (or site URL) Found in 2.2.2 and later ### Please describe the expected behaviour I manage a customized CKAN for a client. The create dataset page is changed in a way it is possible to add all metadata to a dataset on 'package_create'. Also it should be possible to add the dataset direktly to groups. The user has the capacity 'Editor' on the group. ### Please describe the actual behaviour The auth function 'package_create' always does the `check2 = _check_group_auth(context,data_dict)`, which is a different approach than in 'package_update' auth function. That leads to using the call to `authz.has_user_permission_for_group_or_org(group.id, user, 'update')`. Later this leads to a comparison of permission '**update**' with the permissions of 'Editor' role ('editor', ['read', 'delete_dataset', 'create_dataset', 'update_dataset', 'manage_group']). `if 'admin' in perms or permission in perms: return True` In my opinion this can never be true and thus is bug. Could you please check this? Regards, Daniel
Since CKAN 2.2 the available roles for Group members are `Admin` and `Member`. Perhaps this was migrated from an even older CKAN version. Can you try and manually change the entries for `editor` to `admin` on the `member` and `member_revision` tables and see if that helps? Make sure to do a backup and if you also are using organizations you should only update rows related to groups, not orgs. Indeed we migrated from CKAN 1.8 to 2.2.2. The only documentation I could find is > Organizations and authorization at http://docs.ckan.org/en/ckan-2.2.3/authorization.html. It mainly speaks about organizations but groups are mentioned and as organizations are groups, why should it be different? Anyway having admin rights for every user on every group is not what we want. It should be possible to add datasets to groups without being able to modify the group metadata or delete it. It remains strange that the originally mentioned `authz.has_user_permission_for_group_or_org(group.id, user, 'update')` never evaluate to true at `if 'admin' in perms or permission in perms` with the possible `perms` ``` ROLE_PERMISSIONS = OrderedDict([ ('admin', ['admin']), ('editor', ['read', 'delete_dataset', 'create_dataset', 'update_dataset', 'manage_group']), ('member', ['read', 'manage_group']), ]) ``` runtime example: `if 'admin' in ['read', 'delete_dataset', 'create_dataset', 'update_dataset', 'manage_group'] or 'update' in ['read', 'delete_dataset', 'create_dataset', 'update_dataset', 'manage_group']` Another problem seems to be `def _check_group_auth(context, data_dict):` in ckan/logic/auth/create.py called on package_update. In all cases I can reproduce, the block ``` if pkg: pkg_groups = pkg.get_groups() groups = groups - set(pkg_groups) ``` removes all groups from the package and returns always true. @amercader This line was added [long time ago](https://github.com/ckan/ckan/blob/de9eeaeef74343e37757996f2410a66955dfc4ec/ckan/new_authz.py#L63-L67) and now it not actual. I think, that we should change `update` to `manage_group` in this check, so that users, who are members of group will be able to add dataset into it(member has this permission). And in that case we avoid giving permission to edit group metadata with adding new datasets. PS I've created pull request with small fix slightly related to this situation - #3351 - if you don't mind, i can change permission check there as well
2017-06-23T10:17:58
ckan/ckan
3,634
ckan__ckan-3634
[ "3633" ]
214ccf6924c59b918366c207fdc8cda0f2e0064f
diff --git a/ckan/model/modification.py b/ckan/model/modification.py --- a/ckan/model/modification.py +++ b/ckan/model/modification.py @@ -24,22 +24,11 @@ class DomainObjectModificationExtension(plugins.SingletonPlugin): plugins.implements(plugins.ISession, inherit=True) - def notify_observers(self, func): - """ - Call func(observer) for all registered observers. - - :param func: Any callable, which will be called for each observer - :returns: EXT_CONTINUE if no errors encountered, otherwise EXT_STOP - """ - for observer in plugins.PluginImplementations( - plugins.IDomainObjectModification): - func(observer) - def before_commit(self, session): self.notify_observers(session, self.notify) def after_commit(self, session): - self.notify_observers(session, self.notify_after_commit) + pass def notify_observers(self, session, method): session.flush() @@ -95,18 +84,3 @@ def notify(self, entity, operation): log.exception(ex) # Don't reraise other exceptions since they are generally of # secondary importance so shouldn't disrupt the commit. - - def notify_after_commit(self, entity, operation): - for observer in plugins.PluginImplementations( - plugins.IDomainObjectModification): - try: - observer.notify_after_commit(entity, operation) - except SearchIndexError, search_error: - log.exception(search_error) - # Reraise, since it's pretty crucial to ckan if it can't index - # a dataset - raise - except Exception, ex: - log.exception(ex) - # Don't reraise other exceptions since they are generally of - # secondary importance so shouldn't disrupt the commit. diff --git a/ckan/plugins/interfaces.py b/ckan/plugins/interfaces.py --- a/ckan/plugins/interfaces.py +++ b/ckan/plugins/interfaces.py @@ -239,7 +239,10 @@ def notify(self, entity, operation): def notify_after_commit(self, entity, operation): u''' - Send a notification after entity modification. + ** DEPRECATED ** + + Supposed to send a notification after entity modification, but it + doesn't work. :param entity: instance of module.Package. :param operation: 'new', 'changed' or 'deleted'.
Deprecate notify_after_commit Because it doesn't work. notify_after_commit (from interface IDomainObjectModification) never gets called because session._object_cache is blank for this sort of SessionExtension event, so CKAN don't know what object has been committed. I see there are no tests for it, and no-one (on Github) has used it.
2017-06-23T11:30:11
ckan/ckan
3,642
ckan__ckan-3642
[ "3641" ]
8890ebee92719a36ff5e7fd0ca4893c6806a1ac1
diff --git a/doc/conf.py b/doc/conf.py --- a/doc/conf.py +++ b/doc/conf.py @@ -168,13 +168,24 @@ def latest_package_name(distro='trusty'): version=latest_minor_version, distro=distro) -def write_latest_release_file(): - '''Write a file in the doc/ dir containing reStructuredText substitutions - for the latest release tag name and version number. +def min_setuptools_version(): + ''' + Get the minimum setuptools version as defined in requirement-setuptools.txt. + ''' + filename = os.path.join(os.path.dirname(__file__), '..', + 'requirement-setuptools.txt') + with open(filename) as f: + return f.read().split('==')[1].strip() + + +def write_substitutions_file(**kwargs): + ''' + Write a file in the doc/ dir containing reStructuredText substitutions. + Any keyword argument is stored as a substitution. ''' - filename = '_latest_release.rst' - template = ''':orphan: + filename = '_substitutions.rst' + header = ''':orphan: .. Some common reStructuredText substitutions. @@ -189,22 +200,21 @@ def write_latest_release_file(): |latest_release_version| -.. |latest_release_tag| replace:: {latest_tag} -.. |latest_release_version| replace:: {latest_version} -.. |latest_package_name_precise| replace:: {package_name_precise} -.. |latest_package_name_trusty| replace:: {package_name_trusty} - ''' - open(filename, 'w').write(template.format( - filename=filename, - latest_tag=latest_release_tag(), - latest_version=latest_release_version(), - package_name_precise=latest_package_name('precise'), - package_name_trusty=latest_package_name('trusty'), - )) - - -write_latest_release_file() + with open(filename, 'w') as f: + f.write(header.format(filename=filename)) + for name, substitution in kwargs.items(): + f.write('.. |{name}| replace:: {substitution}\n'.format( + name=name, substitution=substitution)) + + +write_substitutions_file( + latest_release_tag=latest_release_tag(), + latest_release_version=latest_release_version(), + latest_package_name_precise=latest_package_name('precise'), + latest_package_name_trusty=latest_package_name('trusty'), + min_setuptools_version=min_setuptools_version(), +) # The language for content autogenerated by Sphinx. Refer to documentation diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -1,7 +1,9 @@ # encoding: utf-8 -# Avoid problem releasing to pypi from vagrant import os +import os.path + +# Avoid problem releasing to pypi from vagrant if os.environ.get('USER', '') == 'vagrant': del os.link @@ -17,18 +19,26 @@ from ckan import (__version__, __description__, __long_description__, __license__) -MIN_SETUPTOOLS_VERSION = 20.4 -assert setuptools_version >= str(MIN_SETUPTOOLS_VERSION) and \ - int(setuptools_version.split('.')[0]) >= int(MIN_SETUPTOOLS_VERSION),\ - ('setuptools version error' - '\nYou need a newer version of setuptools.\n' - 'You have {current}, you need at least {minimum}' - '\nInstall the recommended version:\n' - ' pip install -r requirement-setuptools.txt\n' - 'and then try again to install ckan into your python environment.'.format( - current=setuptools_version, - minimum=MIN_SETUPTOOLS_VERSION - )) + +# +# Check setuptools version +# + +def parse_version(s): + return map(int, s.split('.')) + +HERE = os.path.dirname(__file__) +with open(os.path.join(HERE, 'requirement-setuptools.txt')) as f: + setuptools_requirement = f.read().strip() +min_setuptools_version = parse_version(setuptools_requirement.split('==')[1]) +if parse_version(setuptools_version) < min_setuptools_version: + raise AssertionError( + 'setuptools version error\n' + 'You need a newer version of setuptools.\n' + 'Install the recommended version:\n' + ' pip install -r requirement-setuptools.txt\n' + 'and then try again to install ckan into your python environment.' + ) entry_points = {
No such file or directory: '/usr/lib/ckan/default/src/ckan/requirement-setuptools.txt' during installation from source ### CKAN Version if known (or site URL) Latest (setting up development environment) ### Please describe the expected behaviour When following the CKAN [installation from source](http://docs.ckan.org/en/latest/maintaining/installing/install-from-source.html) instructions, I should be able to complete the development setup on Ubuntu 16.04. This implies that all requisite steps should be fully documented. ### Please describe the actual behaviour I get the following error when creating the virtualenv: ``` $ virtualenv --no-site-packages /usr/lib/ckan/default Using base prefix '/home/brylie/anaconda3' New python executable in /usr/lib/ckan/default/bin/python /usr/lib/ckan/default/bin/python: error while loading shared libraries: libpython3.6m.so.1.0: cannot open shared object file: No such file or directory ERROR: The executable /usr/lib/ckan/default/bin/python is not functioning ERROR: It thinks sys.prefix is '/home/brylie' (should be '/usr/lib/ckan/default') ERROR: virtualenv is not compatible with this system or executable ``` I am getting an error on the step **2b: Install the recommended version of ‘setuptools’:** ``` pip install -r /usr/lib/ckan/default/src/ckan/requirement-setuptools.txt Could not open requirements file: [Errno 2] No such file or directory: '/usr/lib/ckan/default/src/ckan/requirement-setuptools.txt' ``` ### What steps can be taken to reproduce the issue? Follow the steps on [Installing CKAN from source](http://docs.ckan.org/en/latest/maintaining/installing/install-from-source.html)
<s>Which CKAN version are you installing? The docs you're quoting are for the current development version, which [does include the `requirement-setuptools.txt` file](https://github.com/ckan/ckan/blob/master/requirement-setuptools.txt). If you're installing a specific release version then make sure that you use that version's documentation. For example [the instructions for installing CKAN 2.6.2 from source](http://docs.ckan.org/en/ckan-2.6.2/maintaining/installing/install-from-source.html), which doesn't mention `requirement-setuptools.txt`.</s> OK, so aside from not reading your question completely I also gave the wrong answer... Let's try again: The problem is that you're told in step `b` to use a file which only gets installed in the latter step `c`. This obviously makes no sense. Unfortunately, simply switching the steps probably won't help, because the goal of step `b` is to prepare the environment for a correct execution of step `c`. So instead of relying on a not-yet-existing file, the docs should simply spell out the desired version of `setuptools` in step `b`: pip install setuptools==20.4 This needs to be fixed in docs.
2017-06-26T09:34:38
ckan/ckan
3,652
ckan__ckan-3652
[ "3647" ]
4261bf4c2b3a29da4bb8dbd796e895c9a338b608
diff --git a/ckan/logic/action/create.py b/ckan/logic/action/create.py --- a/ckan/logic/action/create.py +++ b/ckan/logic/action/create.py @@ -120,7 +120,8 @@ def package_create(context, data_dict): :param owner_org: the id of the dataset's owning organization, see :py:func:`~ckan.logic.action.get.organization_list` or :py:func:`~ckan.logic.action.get.organization_list_for_user` for - available values (optional) + available values. This parameter can be made optional if the config + option :ref:`ckan.auth.create_unowned_dataset` is set to ``True``. :type owner_org: string :returns: the newly created dataset (unless 'return_id_only' is set to True
In API docs "package_create" lists "owner_org" as optional In API docs, the action `package_create` lists the parameter `owner_org` as optional which is not correct. The parameter `owner_org` can be optional only if `ckan.auth.create_unowned_dataset` is set to `true` in the config. I suggest to remove the "(optional)" text and add to the description of the parameter that it can be optional only if `ckan.auth.create_unowned_dataset` is set to `true` in the config.
2017-06-29T14:47:35
ckan/ckan
3,657
ckan__ckan-3657
[ "3656" ]
114ed1f38588c1554b1c092d4a551c3cc0877e85
diff --git a/ckan/logic/action/update.py b/ckan/logic/action/update.py --- a/ckan/logic/action/update.py +++ b/ckan/logic/action/update.py @@ -7,6 +7,7 @@ import time import json import mimetypes +import os from ckan.common import config import paste.deploy.converters as converters @@ -1273,8 +1274,11 @@ def config_option_update(context, data_dict): for key, value in data.iteritems(): # Set full Logo url - if key =='ckan.site_logo' and value and not value.startswith('http'): - value = h.url_for_static('uploads/admin/{0}'.format(value)) + if key == 'ckan.site_logo' and value and not value.startswith('http')\ + and not value.startswith('/'): + image_path = 'uploads/admin/' + + value = h.url_for_static('{0}{1}'.format(image_path, value)) # Save value in database model.set_system_info(key, value)
Default logo image not properly saved ### CKAN Version if known (or site URL) 2.7 and 2.8.0a By default, CKAN uses a default logo image. This can be changed through the UI in the sysadmin config page or in configuration settings. If you go to the sysadmin config page, and if you don't change the logo image and just click Update, the logo image will break. The reason is because its been given wrong path to the image. ### What steps can be taken to reproduce the issue? Go to sysadmin config page. If you previously changed the default logo image, click the Reset button to bring the default settings. After that click on Update and the logo image will break. I isolated the issue and will provide a fix.
2017-06-30T18:00:03
ckan/ckan
3,674
ckan__ckan-3674
[ "3667" ]
853f40de67bce5800bda008904db2c175dec78ec
diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py --- a/ckan/lib/helpers.py +++ b/ckan/lib/helpers.py @@ -2342,6 +2342,15 @@ def mail_to(email_address, name): return html +@core_helper +def radio(selected, id, checked): + if checked: + return literal((u'<input checked="checked" id="%s_%s" name="%s" \ + value="%s" type="radio">') % (selected, id, selected, id)) + return literal(('<input id="%s_%s" name="%s" \ + value="%s" type="radio">') % (selected, id, selected, id)) + + core_helper(flash, name='flash') core_helper(localised_number) core_helper(localised_SI_number) @@ -2362,6 +2371,7 @@ def mail_to(email_address, name): core_helper(urlencode) core_helper(clean_html, name='clean_html') + def load_plugin_helpers(): """ (Re)loads the list of helpers provided by plugins.
radio helper missing ### CKAN Version if known (or site URL) CKAN 2.6.2 ### Please describe the expected behaviour The radio button helper is removed from helpers.py and it's still used in revisions_table.html ### Please describe the actual behaviour As I am informed history revision will be removed, but we should be taken into consideration that some extensions may still use it. The radio button helper should be displayed and not produce an error. ### What steps can be taken to reproduce the issue?
2017-07-06T13:53:20
ckan/ckan
3,685
ckan__ckan-3685
[ "3684" ]
a27cafef5ea665ac57a55e3a0bc4fdf192b4d3d9
diff --git a/ckan/controllers/group.py b/ckan/controllers/group.py --- a/ckan/controllers/group.py +++ b/ckan/controllers/group.py @@ -670,8 +670,11 @@ def member_new(self, id): context = {'model': model, 'session': model.Session, 'user': c.user} + try: + self._check_access('group_member_create', context, {'id': id}) + except NotAuthorized: + abort(403, _('Unauthorized to create group %s members') % '') - # self._check_access('group_delete', context, {'id': id}) try: data_dict = {'id': id} data_dict['include_datasets'] = False diff --git a/ckan/controllers/package.py b/ckan/controllers/package.py --- a/ckan/controllers/package.py +++ b/ckan/controllers/package.py @@ -546,6 +546,16 @@ def new(self, data=None, errors=None, error_summary=None): def resource_edit(self, id, resource_id, data=None, errors=None, error_summary=None): + context = {'model': model, 'session': model.Session, + 'api_version': 3, 'for_edit': True, + 'user': c.user, 'auth_user_obj': c.userobj} + data_dict = {'id': id} + + try: + check_access('package_update', context, data_dict) + except NotAuthorized: + abort(403, _('User %r not authorized to edit %s') % (c.user, id)) + if request.method == 'POST' and not data: data = data or \ clean_dict(dict_fns.unflatten(tuplize_dict(parse_params( @@ -553,10 +563,6 @@ def resource_edit(self, id, resource_id, data=None, errors=None, # we don't want to include save as it is part of the form del data['save'] - context = {'model': model, 'session': model.Session, - 'api_version': 3, 'for_edit': True, - 'user': c.user, 'auth_user_obj': c.userobj} - data['package_id'] = id try: if resource_id: @@ -574,9 +580,6 @@ def resource_edit(self, id, resource_id, data=None, errors=None, h.redirect_to(controller='package', action='resource_read', id=id, resource_id=resource_id) - context = {'model': model, 'session': model.Session, - 'api_version': 3, 'for_edit': True, - 'user': c.user, 'auth_user_obj': c.userobj} pkg_dict = get_action('package_show')(context, {'id': id}) if pkg_dict['state'].startswith('draft'): # dataset has not yet been fully created
diff --git a/ckan/tests/controllers/test_group.py b/ckan/tests/controllers/test_group.py --- a/ckan/tests/controllers/test_group.py +++ b/ckan/tests/controllers/test_group.py @@ -409,6 +409,62 @@ def test_remove_member(self): assert_equal(len(user_roles.keys()), 1) assert_equal(user_roles['User One'], 'Admin') + def test_member_users_cannot_add_members(self): + + user = factories.User() + group = factories.Group( + users=[{'name': user['name'], 'capacity': 'member'}] + ) + + app = helpers._get_test_app() + + env = {'REMOTE_USER': user['name'].encode('ascii')} + + app.get( + url_for( + controller='group', + action='member_new', + id=group['id'], + ), + extra_environ=env, + status=403, + ) + + app.post( + url_for( + controller='group', + action='member_new', + id=group['id'], + ), + {'id': 'test', 'username': 'test', 'save': 'save', 'role': 'test'}, + extra_environ=env, + status=403, + ) + + def test_anonymous_users_cannot_add_members(self): + group = factories.Group() + + app = helpers._get_test_app() + + app.get( + url_for( + controller='group', + action='member_new', + id=group['id'], + ), + status=403, + ) + + app.post( + url_for( + controller='group', + action='member_new', + id=group['id'], + ), + {'id': 'test', 'username': 'test', 'save': 'save', 'role': 'test'}, + status=403, + ) + class TestGroupFollow(helpers.FunctionalTestBase): diff --git a/ckan/tests/controllers/test_organization.py b/ckan/tests/controllers/test_organization.py --- a/ckan/tests/controllers/test_organization.py +++ b/ckan/tests/controllers/test_organization.py @@ -444,3 +444,94 @@ def test_organization_search_within_org_no_results(self): ds_titles = [t.string for t in ds_titles] assert_equal(len(ds_titles), 0) + + +class TestOrganizationMembership(helpers.FunctionalTestBase): + + def test_editor_users_cannot_add_members(self): + + user = factories.User() + organization = factories.Organization( + users=[{'name': user['name'], 'capacity': 'editor'}] + ) + + app = helpers._get_test_app() + + env = {'REMOTE_USER': user['name'].encode('ascii')} + + app.get( + url_for( + controller='organization', + action='member_new', + id=organization['id'], + ), + extra_environ=env, + status=403, + ) + + app.post( + url_for( + controller='organization', + action='member_new', + id=organization['id'], + ), + {'id': 'test', 'username': 'test', 'save': 'save', 'role': 'test'}, + extra_environ=env, + status=403, + ) + + def test_member_users_cannot_add_members(self): + + user = factories.User() + organization = factories.Organization( + users=[{'name': user['name'], 'capacity': 'member'}] + ) + + app = helpers._get_test_app() + + env = {'REMOTE_USER': user['name'].encode('ascii')} + + app.get( + url_for( + controller='organization', + action='member_new', + id=organization['id'], + ), + extra_environ=env, + status=403, + ) + + app.post( + url_for( + controller='organization', + action='member_new', + id=organization['id'], + ), + {'id': 'test', 'username': 'test', 'save': 'save', 'role': 'test'}, + extra_environ=env, + status=403, + ) + + def test_anonymous_users_cannot_add_members(self): + organization = factories.Organization() + + app = helpers._get_test_app() + + app.get( + url_for( + controller='organization', + action='member_new', + id=organization['id'], + ), + status=403, + ) + + app.post( + url_for( + controller='organization', + action='member_new', + id=organization['id'], + ), + {'id': 'test', 'username': 'test', 'save': 'save', 'role': 'test'}, + status=403, + ) diff --git a/ckan/tests/controllers/test_package.py b/ckan/tests/controllers/test_package.py --- a/ckan/tests/controllers/test_package.py +++ b/ckan/tests/controllers/test_package.py @@ -993,6 +993,35 @@ def test_anonymous_users_cannot_add_new_resource(self): status=403, ) + def test_anonymous_users_cannot_edit_resource(self): + organization = factories.Organization() + dataset = factories.Dataset( + owner_org=organization['id'], + ) + resource = factories.Resource(package_id=dataset['id']) + app = helpers._get_test_app() + + response = app.get( + url_for( + controller='package', + action='resource_edit', + id=dataset['id'], + resource_id=resource['id'], + ), + status=403, + ) + + response = app.post( + url_for( + controller='package', + action='resource_edit', + id=dataset['id'], + resource_id=resource['id'], + ), + {'name': 'test', 'url': 'test', 'save': 'save', 'id': ''}, + status=403, + ) + class TestResourceView(helpers.FunctionalTestBase): @classmethod @@ -1298,7 +1327,7 @@ def test_confirm_and_cancel_deleting_a_resource(self): # cancelling sends us back to the resource edit page form = response.forms['confirm-resource-delete-form'] response = form.submit('cancel') - response = response.follow() + response = response.follow(extra_environ=env) assert_equal(200, response.status_int)
Restrict access to forms Resource edit and add member page can be accessed knowing the URL. No action can be saved but it's best to allow access at all.
2017-07-12T10:43:43
ckan/ckan
3,689
ckan__ckan-3689
[ "3688" ]
7ef03e65365b0622ddc683984cf11f4cfc943f16
diff --git a/ckan/lib/cli.py b/ckan/lib/cli.py --- a/ckan/lib/cli.py +++ b/ckan/lib/cli.py @@ -2117,6 +2117,7 @@ def command(self): # Less css cmd = LessCommand('less') + cmd.options = self.options cmd.command() # js translation strings
Frontent build command does not work on master Running `paster front-end-build` on master returns: ``` Traceback (most recent call last): File "/home/adria/dev/pyenvs/ckan/bin/paster", line 11, in <module> sys.exit(run()) File "/home/adria/dev/pyenvs/ckan/local/lib/python2.7/site-packages/paste/script/command.py", line 102, in run invoke(command, command_name, options, args[1:]) File "/home/adria/dev/pyenvs/ckan/local/lib/python2.7/site-packages/paste/script/command.py", line 141, in invoke exit_code = runner.run(args) File "/home/adria/dev/pyenvs/ckan/local/lib/python2.7/site-packages/paste/script/command.py", line 236, in run result = self.command() File "/home/adria/dev/pyenvs/ckan/src/ckan/ckan/lib/cli.py", line 2120, in command cmd.command() File "/home/adria/dev/pyenvs/ckan/src/ckan/ckan/lib/cli.py", line 2025, in command self._load_config() File "/home/adria/dev/pyenvs/ckan/src/ckan/ckan/lib/cli.py", line 310, in _load_config self.site_user = load_config(self.options.config, load_site_user) AttributeError: 'LessCommand' object has no attribute 'options' ``` Looks like the culprit is this [line](https://github.com/ckan/ckan/pull/3547/files#diff-530e98d83857b6bd57795518ad4c2dbdR2027), part of the Bootstrap 3 PR. @klikstermkd can you have a look?
This works on 2.7 so there's no rush @amercader Yes I will look into it.
2017-07-13T15:33:05
ckan/ckan
3,695
ckan__ckan-3695
[ "3694" ]
7ef03e65365b0622ddc683984cf11f4cfc943f16
diff --git a/ckan/lib/fanstatic_resources.py b/ckan/lib/fanstatic_resources.py --- a/ckan/lib/fanstatic_resources.py +++ b/ckan/lib/fanstatic_resources.py @@ -235,7 +235,7 @@ def create_resource(path, lib_name, count, inline=False): base_path = os.path.abspath(os.path.join( os.path.dirname(__file__), '..', public, 'base')) -log.info('Base path {0}'.format(base_path)) +log.debug('Base path {0}'.format(base_path)) create_library('vendor', os.path.join(base_path, 'vendor'), depend_base=False) create_library('base', os.path.join(base_path, 'javascript'), diff --git a/ckanext/datapusher/logic/action.py b/ckanext/datapusher/logic/action.py --- a/ckanext/datapusher/logic/action.py +++ b/ckanext/datapusher/logic/action.py @@ -101,7 +101,7 @@ def datapusher_submit(context, data_dict): # likely something went wrong with it and the state wasn't # updated than its still in progress. Let it be restarted. log.info('A pending task was found %r, but it is only %s hours' - 'old', existing_task['id'], time_since_last_updated) + ' old', existing_task['id'], time_since_last_updated) else: log.info('A pending task was found %s for this resource, so ' 'skipping this duplicate task', existing_task['id'])
datastore set-up error - logging getting in the way ### CKAN Version if known (or site URL) master ### Please describe the actual behaviour Setting up the datastore permissions hits an error (which can be ignored, but still) ``` $ paster datastore set-permissions -c test-core.ini | sudo -u postgres psql You are now connected to database "datastore_test" as user "postgres". ERROR: syntax error at or near "2017" LINE 1: 2017-07-14 14:35:01,978 INFO [ckan.lib.fanstatic_resources]... ^ ``` This is because of some stray logging appearing: ``` $ paster datastore set-permissions -c test-core.ini 2017-07-14 14:37:10,623 INFO [ckan.lib.fanstatic_resources] Base path /home/dread/ckan-master/ckan/ckan/public/base /* This script configures the permissions for the datastore. ... ```
Looks like it was added in this commit: https://github.com/ckan/ckan/commit/d03a88211990fe324ee73ebe3cacaf39e9ccda0f#diff-075debb789cb12033188527d800a4db5R239 I guess we can just lose the log statement.
2017-07-14T13:53:41
ckan/ckan
3,734
ckan__ckan-3734
[ "3539" ]
81df5d591ba1ff2a3d487db8add1a815422c3eea
diff --git a/ckan/lib/i18n.py b/ckan/lib/i18n.py --- a/ckan/lib/i18n.py +++ b/ckan/lib/i18n.py @@ -225,7 +225,7 @@ def _set_lang(lang): if config.get('ckan.i18n_directory'): fake_config = {'pylons.paths': {'root': config['ckan.i18n_directory']}, 'pylons.package': config['pylons.package']} - i18n.set_lang(lang, config=fake_config, class_=Translations) + i18n.set_lang(lang, pylons_config=fake_config, class_=Translations) else: i18n.set_lang(lang, class_=Translations)
Exception when specifying a directory in the ckan.i18n_directory option ### CKAN Version if known (or site URL) 2.6.2 ### Please describe the expected behaviour After specifying a directory in the `ckan.i18n_directory` option, we should get locales from that directory. ### Please describe the actual behaviour Exception is thrown when accessing the CKAN site. The page shows "Internal Server Error". ```python File "/usr/lib/ckan/data_depositario/local/lib/python2.7/site-packages/pylons/controllers/core.py", line 60, in _perform_call return func(**args) File "/home/u10313335/ckan/lib/data_depositario/src/ckan/ckan/lib/base.py", line 200, in __before__ i18n.handle_request(request, c) File "/home/u10313335/ckan/lib/data_depositario/src/ckan/ckan/lib/i18n.py", line 188, in handle_request set_lang(lang) File "/home/u10313335/ckan/lib/data_depositario/src/ckan/ckan/lib/i18n.py", line 238, in set_lang _set_lang(language_code) File "/home/u10313335/ckan/lib/data_depositario/src/ckan/ckan/lib/i18n.py", line 178, in _set_lang i18n.set_lang(lang, config=fake_config, class_=Translations) File "/usr/lib/ckan/data_depositario/local/lib/python2.7/site-packages/pylons/i18n/translation.py", line 182, in set_lang translator = _get_translator(lang, **kwargs) File "/usr/lib/ckan/data_depositario/local/lib/python2.7/site-packages/pylons/i18n/translation.py", line 168, in _get_translator languages=lang, **kwargs) TypeError: translation() got an unexpected keyword argument 'config' ``` ### What steps can be taken to reproduce the issue? 1. Specify a directory with locales in the `ckan.i18n_directory` option. (Try the default `ckan/i18n` if you don't have one.) 2. Reload the CKAN site.
My workaround for this issue: Change this line: https://github.com/ckan/ckan/blob/a6fc30979dd75890c3322006554a350102f6b10b/ckan/lib/i18n.py#L178 from ```python i18n.set_lang(lang, config=fake_config, class_=Translations) ``` to ```python i18n.set_lang(lang, pylons_config=fake_config, class_=Translations) ``` Not sure if it is okay since we are migrating from pylons to flask. I would submit a PR later If this fix looks good. Hi @amercader ! I also saw this error when trying to upgrade to 2.6 I'm translating CKAN and have the translations in my plugin.
2017-07-27T14:38:41
ckan/ckan
3,735
ckan__ckan-3735
[ "3366" ]
b9153995661a5338ff018085efe719b115a42ac2
diff --git a/ckan/model/system_info.py b/ckan/model/system_info.py --- a/ckan/model/system_info.py +++ b/ckan/model/system_info.py @@ -53,11 +53,14 @@ def __init__(self, key, value): def get_system_info(key, default=None): ''' get data from system_info table ''' - obj = meta.Session.query(SystemInfo).filter_by(key=key).first() - if obj: - return obj.value - else: - return default + from sqlalchemy.exc import ProgrammingError + try: + obj = meta.Session.query(SystemInfo).filter_by(key=key).first() + if obj: + return obj.value + except ProgrammingError: + meta.Session.rollback() + return default def delete_system_info(key, default=None):
Tolerate missing system_info table If you have an old or incomplete database some commands (such as db clean) will fail because they can't find the system_info table. ```python-traceback $ cd ckan; paster db clean -c test-core.ini; paster db init -c test-core.ini Traceback (most recent call last): File "/home/ubuntu/virtualenvs/venv-system/bin/paster", line 11, in <module> sys.exit(run()) File "/home/ubuntu/virtualenvs/venv-system/local/lib/python2.7/site-packages/paste/script/command.py", line 102, in run invoke(command, command_name, options, args[1:]) File "/home/ubuntu/virtualenvs/venv-system/local/lib/python2.7/site-packages/paste/script/command.py", line 141, in invoke exit_code = runner.run(args) File "/home/ubuntu/virtualenvs/venv-system/local/lib/python2.7/site-packages/paste/script/command.py", line 236, in run result = self.command() File "/home/ubuntu/ckanext-scheming/ckan/ckan/lib/cli.py", line 217, in command self._load_config(cmd!='upgrade') File "/home/ubuntu/ckanext-scheming/ckan/ckan/lib/cli.py", line 161, in _load_config load_environment(conf.global_conf, conf.local_conf) File "/home/ubuntu/ckanext-scheming/ckan/ckan/config/environment.py", line 99, in load_environment app_globals.reset() File "/home/ubuntu/ckanext-scheming/ckan/ckan/lib/app_globals.py", line 172, in reset get_config_value(key) File "/home/ubuntu/ckanext-scheming/ckan/ckan/lib/app_globals.py", line 139, in get_config_value value = model.get_system_info(key) File "/home/ubuntu/ckanext-scheming/ckan/ckan/model/system_info.py", line 56, in get_system_info obj = meta.Session.query(SystemInfo).filter_by(key=key).first() File "/home/ubuntu/virtualenvs/venv-system/local/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2334, in first ret = list(self[0:1]) File "/home/ubuntu/virtualenvs/venv-system/local/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2201, in __getitem__ return list(res) File "/home/ubuntu/virtualenvs/venv-system/local/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2405, in __iter__ return self._execute_and_instances(context) File "/home/ubuntu/virtualenvs/venv-system/local/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2420, in _execute_and_instances result = conn.execute(querycontext.statement, self._params) File "/home/ubuntu/virtualenvs/venv-system/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 727, in execute return meth(self, multiparams, params) File "/home/ubuntu/virtualenvs/venv-system/local/lib/python2.7/site-packages/sqlalchemy/sql/elements.py", line 322, in _execute_on_connection return connection._execute_clauseelement(self, multiparams, params) File "/home/ubuntu/virtualenvs/venv-system/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 824, in _execute_clauseelement compiled_sql, distilled_params File "/home/ubuntu/virtualenvs/venv-system/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 954, in _execute_context context) File "/home/ubuntu/virtualenvs/venv-system/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1116, in _handle_dbapi_exception exc_info File "/home/ubuntu/virtualenvs/venv-system/local/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 189, in raise_from_cause reraise(type(exception), exception, tb=exc_tb) File "/home/ubuntu/virtualenvs/venv-system/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 947, in _execute_context context) File "/home/ubuntu/virtualenvs/venv-system/local/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 435, in do_execute cursor.execute(statement, parameters) sqlalchemy.exc.ProgrammingError: (ProgrammingError) column system_info.state does not exist LINE 1: ...info_key, system_info.value AS system_info_value, system_inf... ^ 'SELECT system_info.id AS system_info_id, system_info.key AS system_info_key, system_info.value AS system_info_value, system_info.state AS system_info_state, system_info.revision_id AS system_info_revision_id \nFROM system_info \nWHERE system_info.key = %(key_1)s \n LIMIT %(param_1)s' {'param_1': 1, 'key_1': 'ckan.site_description'} ``` This change treats a missing system_info table the same as no overridden configuration.
👍 @TkTech care to merge this?
2017-07-28T05:32:11
ckan/ckan
3,749
ckan__ckan-3749
[ "3499" ]
b0c2d834fb33fcb8a20dbfe1aa0224ab9e40952c
diff --git a/ckan/controllers/user.py b/ckan/controllers/user.py --- a/ckan/controllers/user.py +++ b/ckan/controllers/user.py @@ -397,8 +397,7 @@ def login(self, error=None): if not c.user: came_from = request.params.get('came_from') if not came_from: - came_from = h.url_for(controller='user', action='logged_in', - __ckan_no_root=True) + came_from = h.url_for(controller='user', action='logged_in') c.login_handler = h.url_for( self._get_repoze_handler('login_handler_path'), came_from=came_from) @@ -436,10 +435,9 @@ def logout(self): # Do any plugin logout stuff for item in p.PluginImplementations(p.IAuthenticator): item.logout() - url = h.url_for(controller='user', action='logged_out_page', - __ckan_no_root=True) + url = h.url_for(controller='user', action='logged_out_page') h.redirect_to(self._get_repoze_handler('logout_handler_path') + - '?came_from=' + url) + '?came_from=' + url, parse_url=True) def logged_out(self): # redirect if needed diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py --- a/ckan/lib/helpers.py +++ b/ckan/lib/helpers.py @@ -152,6 +152,12 @@ def redirect_to(*args, **kw): toolkit.redirect_to('dataset_read', id='changed') + If given a single string as argument, this redirects without url parsing + + toolkit.redirect_to('http://example.com') + toolkit.redirect_to('/dataset') + toolkit.redirect_to('/some/other/path') + ''' if are_there_flash_messages(): kw['__no_cache__'] = True @@ -159,7 +165,19 @@ def redirect_to(*args, **kw): # Routes router doesn't like unicode args uargs = map(lambda arg: str(arg) if isinstance(arg, unicode) else arg, args) - _url = url_for(*uargs, **kw) + + _url = '' + skip_url_parsing = False + parse_url = kw.pop('parse_url', False) + if uargs and len(uargs) is 1 and isinstance(uargs[0], basestring) \ + and (uargs[0].startswith('/') or is_url(uargs[0])) \ + and parse_url is False: + skip_url_parsing = True + _url = uargs[0] + + if skip_url_parsing is False: + _url = url_for(*uargs, **kw) + if _url.startswith('/'): _url = str(config['ckan.site_url'].rstrip('/') + _url)
Redirecting to same page in non-root hosted ckan adds extra root_path to url ### CKAN Version if known (or site URL) 2.6.0, 2.6.1, master ### Please describe the expected behaviour In ckanext-harvest reharvest and clear buttons and in ckanext-report button redirect to the same page, if ckan is hosted in for example /data, I expect the redirection to /data/harvest/admin/someharvestname. ### Please describe the actual behaviour Resulting url is /data/data/harvest/admin/someharvestname ### What steps can be taken to reproduce the issue? Clear or reharvest non-root hosted ckan. ### Some additional info https://github.com/ckan/ckan/pull/2998 is probably the culprit since redirection works in ckan 2.3.5. Will supply PR which should be validated for not breaking anything else.
@fanjinfei would you look at this when you have some time? for a none root such as `/data/{{LANG}}`, `h.url_for('/data/user/login')` is wrong (`/data/data/user/login`). `h.url_for(controller='user', action='login')` is correct. h.redirect_to() should have the same problem. Yes, this issue can circumvented by modifying the extensions to redirect to controller actions instead of urls. For ckanext-harvest https://github.com/ckan/ckanext-harvest/blob/master/ckanext/harvest/controllers/view.py#L77 and for ckanext-report https://github.com/datagovuk/ckanext-report/blob/master/ckanext/report/controllers.py#L46 But since the helper functions accept urls as parameters and the issue does not manifest itself when ckan is hosted in root path, I suspect there is a bug in ckan core with url amending which should be fixed or at least prohibit urls as parameters. When passing urls to redirect_to I agree with @Zharktas, we should never add the root path. That way existing code that does `redirect_to(url_for(...))` will work, `redirect_to('http://some.other.place/..')` will work and `redirect_to('/user/login')` won't work because it should be written with the controller and action parameters as @fanjinfei suggests. We should also document this on redirect_to. This issue might manifest itself with ckan 2.7 as there is now new handler [helpers.py](https://github.com/ckan/ckan/blob/ckan-2.7.0/ckan/lib/helpers.py#L162]) if the path starts with /-character. If the root path is set, both ckan 2.6 and 2.7 will generate urls incorrectly with url_for: h.url_for('http://example.com') '/datahttp://example.com' When calling redirect_to with 'http://example.com', 2.6 redirects just fine, but 2.7 adds site_url to the final url and redirection no longer works. I'll take a look if this is actually caused by the same issue and try fix it. If it's not, I'll create separate issue.
2017-08-10T13:33:25
ckan/ckan
3,786
ckan__ckan-3786
[ "3785" ]
177143fca601cad334d0e6be09a4224ac9c85645
diff --git a/ckanext/datastore/backend/postgres.py b/ckanext/datastore/backend/postgres.py --- a/ckanext/datastore/backend/postgres.py +++ b/ckanext/datastore/backend/postgres.py @@ -349,22 +349,6 @@ def _validate_record(record, num, field_names): }) -def _to_full_text(fields, record): - full_text = [] - ft_types = ['int8', 'int4', 'int2', 'float4', 'float8', 'date', 'time', - 'timetz', 'timestamp', 'numeric', 'text'] - for field in fields: - value = record.get(field['id']) - if not value: - continue - - if field['type'].lower() in ft_types and unicode(value): - full_text.append(unicode(value)) - else: - full_text.extend(json_get_values(value)) - return ' '.join(set(full_text)) - - def _where_clauses(data_dict, fields_types): filters = data_dict.get('filters', {}) clauses = [] @@ -755,19 +739,6 @@ def convert(data, type_name): return unicode(data) -def json_get_values(obj, current_list=None): - if current_list is None: - current_list = [] - if isinstance(obj, list) or isinstance(obj, tuple): - for item in obj: - json_get_values(item, current_list) - elif isinstance(obj, dict): - json_get_values(obj.items(), current_list) - elif obj: - current_list.append(unicode(obj)) - return current_list - - def check_fields(context, fields): '''Check if field types are valid.''' for field in fields: @@ -1052,8 +1023,8 @@ def upsert_data(context, data_dict): fields = _get_fields(context, data_dict) field_names = _pluck('id', fields) records = data_dict['records'] - sql_columns = ", ".join(['"%s"' % name.replace( - '%', '%%') for name in field_names] + ['"_full_text"']) + sql_columns = ", ".join( + identifier(name) for name in field_names) if method == _INSERT: rows = [] @@ -1067,13 +1038,12 @@ def upsert_data(context, data_dict): # a tuple with an empty second value value = (json.dumps(value), '') row.append(value) - row.append(_to_full_text(fields, record)) rows.append(row) - sql_string = u'''INSERT INTO "{res_id}" ({columns}) - VALUES ({values}, to_tsvector(%s));'''.format( - res_id=data_dict['resource_id'], - columns=sql_columns, + sql_string = u'''INSERT INTO {res_id} ({columns}) + VALUES ({values});'''.format( + res_id=identifier(data_dict['resource_id']), + columns=sql_columns.replace('%', '%%'), values=', '.join(['%s' for field in field_names]) ) @@ -1129,18 +1099,16 @@ def upsert_data(context, data_dict): used_values = [record[field] for field in used_field_names] - full_text = _to_full_text(fields, record) - if method == _UPDATE: sql_string = u''' UPDATE "{res_id}" - SET ({columns}, "_full_text") = ({values}, to_tsvector(%s)) + SET ({columns}, "_full_text") = ({values}, NULL) WHERE ({primary_key}) = ({primary_value}); '''.format( res_id=data_dict['resource_id'], columns=u', '.join( - [u'"{0}"'.format(field) - for field in used_field_names]), + [identifier(field) + for field in used_field_names]).replace('%', '%%'), values=u', '.join( ['%s' for _ in used_field_names]), primary_key=u','.join( @@ -1149,7 +1117,7 @@ def upsert_data(context, data_dict): ) try: results = context['connection'].execute( - sql_string, used_values + [full_text] + unique_values) + sql_string, used_values + unique_values) except sqlalchemy.exc.DatabaseError as err: raise ValidationError({ u'records': [_programming_error_summary(err)], @@ -1164,10 +1132,10 @@ def upsert_data(context, data_dict): elif method == _UPSERT: sql_string = u''' UPDATE "{res_id}" - SET ({columns}, "_full_text") = ({values}, to_tsvector(%s)) + SET ({columns}, "_full_text") = ({values}, NULL) WHERE ({primary_key}) = ({primary_value}); - INSERT INTO "{res_id}" ({columns}, "_full_text") - SELECT {values}, to_tsvector(%s) + INSERT INTO "{res_id}" ({columns}) + SELECT {values} WHERE NOT EXISTS (SELECT 1 FROM "{res_id}" WHERE ({primary_key}) = ({primary_value})); '''.format( @@ -1184,7 +1152,7 @@ def upsert_data(context, data_dict): try: context['connection'].execute( sql_string, - (used_values + [full_text] + unique_values) * 2) + (used_values + unique_values) * 2) except sqlalchemy.exc.DatabaseError as err: raise ValidationError({ u'records': [_programming_error_summary(err)], @@ -1416,7 +1384,8 @@ def _create_triggers(connection, resource_id, triggers): or "for_each" parameters from triggers list. ''' existing = connection.execute( - u'SELECT tgname FROM pg_trigger WHERE tgrelid = %s::regclass', + u"""SELECT tgname FROM pg_trigger + WHERE tgrelid = %s::regclass AND tgname LIKE 't___'""", resource_id) sql_list = ( [u'DROP TRIGGER {name} ON {table}'.format( @@ -1438,6 +1407,14 @@ def _create_triggers(connection, resource_id, triggers): raise ValidationError({u'triggers': [_programming_error_summary(pe)]}) +def _create_fulltext_trigger(connection, resource_id): + connection.execute( + u'''CREATE TRIGGER zfulltext + BEFORE INSERT OR UPDATE ON {table} + FOR EACH ROW EXECUTE PROCEDURE populate_full_text_trigger()'''.format( + table=identifier(resource_id))) + + def upsert(context, data_dict): ''' This method combines upsert insert and update on the datastore. The method @@ -1829,6 +1806,9 @@ def create(self, context, data_dict): ).fetchone() if not result: create_table(context, data_dict) + _create_fulltext_trigger( + context['connection'], + data_dict['resource_id']) else: alter_table(context, data_dict) if 'triggers' in data_dict: diff --git a/ckanext/datastore/logic/action.py b/ckanext/datastore/logic/action.py --- a/ckanext/datastore/logic/action.py +++ b/ckanext/datastore/logic/action.py @@ -450,16 +450,16 @@ def datastore_search(context, data_dict): res_id = data_dict['resource_id'] - res_exists, real_id = backend.resource_id_from_alias(res_id) - # Resource only has to exist in the datastore (because it could be an - # alias) + if data_dict['resource_id'] not in WHITELISTED_RESOURCES: + res_exists, real_id = backend.resource_id_from_alias(res_id) + # Resource only has to exist in the datastore (because it could be an + # alias) - if not res_exists: - raise p.toolkit.ObjectNotFound(p.toolkit._( - 'Resource "{0}" was not found.'.format(res_id) - )) + if not res_exists: + raise p.toolkit.ObjectNotFound(p.toolkit._( + 'Resource "{0}" was not found.'.format(res_id) + )) - if data_dict['resource_id'] not in WHITELISTED_RESOURCES: # Replace potential alias with real id to simplify access checks if real_id: data_dict['resource_id'] = real_id
diff --git a/ckanext/datastore/tests/helpers.py b/ckanext/datastore/tests/helpers.py --- a/ckanext/datastore/tests/helpers.py +++ b/ckanext/datastore/tests/helpers.py @@ -26,7 +26,7 @@ def clear_db(Session): SELECT 'drop function ' || quote_ident(proname) || '();' FROM pg_proc INNER JOIN pg_namespace ns ON (pg_proc.pronamespace = ns.oid) - WHERE ns.nspname = 'public' + WHERE ns.nspname = 'public' AND proname != 'populate_full_text_trigger' ''' drop_functions = u''.join(r[0] for r in c.execute(drop_functions_sql)) if drop_functions: diff --git a/ckanext/datastore/tests/test_db.py b/ckanext/datastore/tests/test_db.py --- a/ckanext/datastore/tests/test_db.py +++ b/ckanext/datastore/tests/test_db.py @@ -173,26 +173,6 @@ def test_upsert_with_insert_method_and_invalid_data( backend.InvalidDataError, db.upsert_data, context, data_dict) -class TestJsonGetValues(object): - def test_returns_empty_list_if_called_with_none(self): - assert_equal(db.json_get_values(None), []) - - def test_returns_list_with_value_if_called_with_string(self): - assert_equal(db.json_get_values('foo'), ['foo']) - - def test_returns_list_with_only_the_original_truthy_values_if_called(self): - data = [None, 'foo', 42, 'bar', {}, []] - assert_equal(db.json_get_values(data), ['foo', '42', 'bar']) - - def test_returns_flattened_list(self): - data = ['foo', ['bar', ('baz', 42)]] - assert_equal(db.json_get_values(data), ['foo', 'bar', 'baz', '42']) - - def test_returns_only_truthy_values_from_dict(self): - data = {'foo': 'bar', 'baz': [42, None, {}, [], 'hey']} - assert_equal(db.json_get_values(data), ['foo', 'bar', 'baz', '42', 'hey']) - - class TestGetAllResourcesIdsInDatastore(object): @classmethod def setup_class(cls): diff --git a/doc/contributing/test.rst b/doc/contributing/test.rst --- a/doc/contributing/test.rst +++ b/doc/contributing/test.rst @@ -40,6 +40,7 @@ environment: pip install -r |virtualenv|/src/ckan/dev-requirements.txt +.. _datastore-test-set-permissions: ~~~~~~~~~~~~~~~~~~~~~~~~~ Set up the test databases @@ -55,6 +56,9 @@ Create test databases: sudo -u postgres createdb -O |database_user| |test_database| -E utf-8 sudo -u postgres createdb -O |database_user| |test_datastore| -E utf-8 + +Set the permissions:: + paster datastore set-permissions -c test-core.ini | sudo -u postgres psql This database connection is specified in the ``test-core.ini`` file by the
Datastore full-text-search column is populated by postgres trigger rather than python Datastore tables have a column with the full-text-search indexing. This has hitherto been populated by python code _to_full_text() when loading/updating data. This PR changes it to being generated by a postgres function, triggered by postgres seeing rows being added or updated. Benefits: * it works when data gets into the table in ways other than datastore action functions. e.g. columns generated by other postgres triggers. Or ckanext-shift which COPYs data into datastore. * it's marginally faster (I understand)
2017-08-25T16:00:24
ckan/ckan
3,835
ckan__ckan-3835
[ "3834" ]
b8c1dba39a0943f3b1f94dc7ba64d15efded0dd7
diff --git a/ckan/controllers/user.py b/ckan/controllers/user.py --- a/ckan/controllers/user.py +++ b/ckan/controllers/user.py @@ -258,7 +258,7 @@ def _save_new(self, context): if not c.user: # log the user in programatically set_repoze_user(data_dict['name']) - h.redirect_to(controller='user', action='me', __ckan_no_root=True) + h.redirect_to(controller='user', action='me') else: # #1799 User has managed to register whilst logged in - warn user # they are not re-logged in as new user.
Registering a new account redirects to an unprefixed url ### CKAN Version if known (or site URL) 2.7.0 and master ### Please describe the expected behaviour Upon registering a new account, the user should be redirected to a url starting with the root path ### Please describe the actual behaviour The url to which a new user is redirected should include the root path ### What steps can be taken to reproduce the issue? On an installation that uses `ckan.root_path`, register a new account.
2017-09-22T18:38:10
ckan/ckan
3,854
ckan__ckan-3854
[ "3796", "3796" ]
71e839ab461ca072302381781f040a12708ce52b
diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py --- a/ckan/config/middleware/flask_app.py +++ b/ckan/config/middleware/flask_app.py @@ -355,7 +355,9 @@ def _register_core_blueprints(app): def is_blueprint(mm): return isinstance(mm, Blueprint) - for loader, name, _ in pkgutil.iter_modules(['ckan/views'], 'ckan.views.'): + path = os.path.join(os.path.dirname(__file__), '..', '..', 'views') + + for loader, name, _ in pkgutil.iter_modules([path], 'ckan.views.'): module = loader.find_module(name).load_module(name) for blueprint in inspect.getmembers(module, is_blueprint): app.register_blueprint(blueprint[1])
Incorrect API link on /dataset ### CKAN Version if known (or site URL) master ### Please describe the expected behaviour Text at bottom of dataset listing (search.html template) should include a working API link ### Please describe the actual behaviour A link of the form https://beta.ckan.org/packages?ver=%2F3 is generated (https://beta.ckan.org/dataset) This line is no longer working, I suspect because of the recent work to move the API over to Flask(?): https://github.com/ckan/ckan/blob/master/ckan/templates/package/search.html#L52 ### What steps can be taken to reproduce the issue? Incorrect API link on /dataset ### CKAN Version if known (or site URL) master ### Please describe the expected behaviour Text at bottom of dataset listing (search.html template) should include a working API link ### Please describe the actual behaviour A link of the form https://beta.ckan.org/packages?ver=%2F3 is generated (https://beta.ckan.org/dataset) This line is no longer working, I suspect because of the recent work to move the API over to Flask(?): https://github.com/ckan/ckan/blob/master/ckan/templates/package/search.html#L52 ### What steps can be taken to reproduce the issue?
Apparently the api link itself is also broken, which probably is caused by the same issue. For example https://beta.ckan.org/api/3 returns 404. Apparently the api link itself is also broken, which probably is caused by the same issue. For example https://beta.ckan.org/api/3 returns 404.
2017-10-06T09:59:50
ckan/ckan
3,867
ckan__ckan-3867
[ "3863" ]
67dc2df32766c65e8c6ae409ada4c941d538aeb8
diff --git a/ckan/lib/search/__init__.py b/ckan/lib/search/__init__.py --- a/ckan/lib/search/__init__.py +++ b/ckan/lib/search/__init__.py @@ -31,7 +31,7 @@ def text_traceback(): return res -SUPPORTED_SCHEMA_VERSIONS = ['2.7'] +SUPPORTED_SCHEMA_VERSIONS = ['2.8'] DEFAULT_OPTIONS = { 'limit': 20,
Permission labels are indexed by type text in SOLR ### CKAN Version if known (or site URL) 2.7, master ### Please describe the expected behaviour Organization Admin should see organizations private datasets even when SOLR indexing has been changed to accommodate different languages. The permission label should not be index by language rules. ### Please describe the actual behaviour If indexing rules are changed for example to use [EdgeNGram](https://wiki.apache.org/solr/AnalyzersTokenizersTokenFilters#solr.EdgeNGramFilterFactory), the permission label id's are indexed by these rules and organization admin, editor or member can not see organizations private datasets. ### What steps can be taken to reproduce the issue? Apply EdgeNGram to solr indexing. Create organization. Create user. Add user to organization. Create private Dataset to organization. ### Possible fix Use type textgen instead of text in the default schema.xml.
@Zharktas sounds right to me. Mind submitting a PR? Use `string` not `textgen`, which in CKAN's schema is not the same as the old Solr 1.* `textgen` FieldType (confusing I know). @wardi submitted minor PR for this.
2017-10-11T05:46:30
ckan/ckan
3,870
ckan__ckan-3870
[ "3586" ]
f1f36f8a67b1e247005bb7cb9911b42ff8227af8
diff --git a/ckan/config/routing.py b/ckan/config/routing.py --- a/ckan/config/routing.py +++ b/ckan/config/routing.py @@ -371,13 +371,6 @@ def make_map(): m.connect('/revision/list', action='list') m.connect('/revision/{id}', action='read') - # feeds - with SubMapper(map, controller='feed') as m: - m.connect('/feeds/group/{id}.atom', action='group') - m.connect('/feeds/organization/{id}.atom', action='organization') - m.connect('/feeds/tag/{id}.atom', action='tag') - m.connect('/feeds/dataset.atom', action='general') - m.connect('/feeds/custom.atom', action='custom') map.connect('ckanadmin_index', '/ckan-admin', controller='admin', action='index', ckan_icon='gavel') diff --git a/ckan/views/feed.py b/ckan/views/feed.py new file mode 100644 --- /dev/null +++ b/ckan/views/feed.py @@ -0,0 +1,583 @@ +# encoding: utf-8 + +import logging +import urlparse + +from flask import Blueprint, make_response +import webhelpers.feedgenerator +from ckan.common import _, config, g, request, response +import ckan.lib.helpers as h +import ckan.lib.base as base +import ckan.model as model +import ckan.logic as logic +import ckan.plugins as plugins +import json + +log = logging.getLogger(__name__) + +feeds = Blueprint(u'feeds', __name__, url_prefix=u'/feeds') + +ITEMS_LIMIT = config.get(u'ckan.feeds.limit', 20) +BASE_URL = config.get(u'ckan.site_url') +SITE_TITLE = config.get(u'ckan.site_title', u'CKAN') + + +def _package_search(data_dict): + """ + Helper method that wraps the package_search action. + + * unless overridden, sorts results by metadata_modified date + * unless overridden, sets a default item limit + """ + context = { + u'model': model, + u'session': model.Session, + u'user': g.user, + u'auth_user_obj': g.userobj + } + if u'sort' not in data_dict or not data_dict['sort']: + data_dict['sort'] = u'metadata_modified desc' + + if u'rows' not in data_dict or not data_dict['rows']: + data_dict['rows'] = ITEMS_LIMIT + + # package_search action modifies the data_dict, so keep our copy intact. + query = logic.get_action(u'package_search')(context, data_dict.copy()) + + return query['count'], query['results'] + + +def _enclosure(pkg): + links = [] + links.append({ + u'href': h.url(u'api.action', logic_function=u'package_show', + ver=3, id=pkg['id'], _external=True), + u'rel': u'', + u'length': unicode(len(json.dumps(pkg))), + u'type': u'application/json'}) + return links + + +def _set_extras(**kw): + extras = [] + for key, value in kw.iteritems(): + extras.append({key: value}) + return extras + + +def output_feed(results, feed_title, feed_description, feed_link, feed_url, + navigation_urls, feed_guid): + author_name = config.get(u'ckan.feeds.author_name', u'').strip() or \ + config.get(u'ckan.site_id', u'').strip() + + # TODO: language + feed_class = None + for plugin in plugins.PluginImplementations(plugins.IFeed): + if hasattr(plugin, u'get_feed_class'): + feed_class = plugin.get_feed_class() + + if not feed_class: + feed_class = _FixedAtom1Feed + + feed = feed_class( + feed_title, + feed_link, + feed_description, + language=u'en', + author_name=author_name, + feed_guid=feed_guid, + feed_url=feed_url, + previous_page=navigation_urls[u'previous'], + next_page=navigation_urls[u'next'], + first_page=navigation_urls[u'first'], + last_page=navigation_urls[u'last'], ) + + for pkg in results: + additional_fields = {} + + for plugin in plugins.PluginImplementations(plugins.IFeed): + if hasattr(plugin, u'get_item_additional_fields'): + additional_fields = plugin.get_item_additional_fields(pkg) + + feed.add_item( + title=pkg.get(u'title', u''), + link=h.url_for( + u'api.action', + logic_function=u'package_read', + id=pkg['id'], + ver=3, + _external=True), + description=pkg.get(u'notes', u''), + updated=h.date_str_to_datetime(pkg.get(u'metadata_modified')), + published=h.date_str_to_datetime(pkg.get(u'metadata_created')), + unique_id=_create_atom_id(u'/dataset/%s' % pkg['id']), + author_name=pkg.get(u'author', u''), + author_email=pkg.get(u'author_email', u''), + categories=[t['name'] for t in pkg.get(u'tags', [])], + enclosure=webhelpers.feedgenerator.Enclosure( + h.url_for( + u'api.action', + logic_function=u'package_show', + id=pkg['name'], + ver=3, + _external=True), + unicode(len(json.dumps(pkg))), u'application/json'), + **additional_fields) + + resp = make_response(feed.writeString(u'utf-8'), 200) + resp.headers['Content-Type'] = u'application/atom+xml' + return resp + + +def group(id): + try: + context = { + u'model': model, + u'session': model.Session, + u'user': g.user, + u'auth_user_obj': g.userobj + } + group_dict = logic.get_action(u'group_show')(context, {u'id': id}) + except logic.NotFound: + base.abort(404, _(u'Group not found')) + + return group_or_organization(group_dict, is_org=False) + + +def organization(id): + try: + context = { + u'model': model, + u'session': model.Session, + u'user': g.user, + u'auth_user_obj': g.userobj + } + group_dict = logic.get_action(u'organization_show')(context, { + u'id': id + }) + except logic.NotFound: + base.abort(404, _(u'Organization not found')) + + return group_or_organization(group_dict, is_org=True) + + +def tag(id): + data_dict, params = _parse_url_params() + data_dict['fq'] = u'tags: "%s"' % id + + item_count, results = _package_search(data_dict) + + navigation_urls = _navigation_urls( + params, + item_count=item_count, + limit=data_dict['rows'], + controller=u'feeds', + action=u'tag', + id=id) + + feed_url = _feed_url(params, controller=u'feeds', action=u'tag', id=id) + + alternate_url = _alternate_url(params, tags=id) + + title = u'%s - Tag: "%s"' % (SITE_TITLE, id) + desc = u'Recently created or updated datasets on %s by tag: "%s"' % \ + (SITE_TITLE, id) + guid = _create_atom_id(u'/feeds/tag/%s.atom' % id) + + return output_feed( + results, + feed_title=title, + feed_description=desc, + feed_link=alternate_url, + feed_guid=guid, + feed_url=feed_url, + navigation_urls=navigation_urls) + + +def group_or_organization(obj_dict, is_org): + data_dict, params = _parse_url_params() + if is_org: + key = u'owner_org' + value = obj_dict['id'] + group_type = u'organization' + else: + key = u'groups' + value = obj_dict['name'] + group_type = u'group' + + data_dict['fq'] = u'{0}: "{1}"'.format(key, value) + item_count, results = _package_search(data_dict) + + navigation_urls = _navigation_urls( + params, + item_count=item_count, + limit=data_dict['rows'], + controller=u'feed', + action=group_type, + id=obj_dict['name']) + feed_url = _feed_url( + params, controller=u'feed', action=group_type, id=obj_dict['name']) + # site_title = SITE_TITLE + if is_org: + guid = _create_atom_id( + u'feeds/organization/%s.atom' % obj_dict['name']) + alternate_url = _alternate_url(params, organization=obj_dict['name']) + desc = u'Recently created or updated datasets on %s '\ + 'by organization: "%s"' % (SITE_TITLE, obj_dict['title']) + title = u'%s - Organization: "%s"' % (SITE_TITLE, obj_dict['title']) + + else: + guid = _create_atom_id(u'feeds/group/%s.atom' % obj_dict['name']) + alternate_url = _alternate_url(params, groups=obj_dict['name']) + desc = u'Recently created or updated datasets on %s '\ + 'by group: "%s"' % (SITE_TITLE, obj_dict['title']) + title = u'%s - Group: "%s"' % (SITE_TITLE, obj_dict['title']) + + return output_feed( + results, + feed_title=title, + feed_description=desc, + feed_link=alternate_url, + feed_guid=guid, + feed_url=feed_url, + navigation_urls=navigation_urls) + + +def _parse_url_params(): + """ + Constructs a search-query dict from the URL query parameters. + + Returns the constructed search-query dict, and the valid URL + query parameters. + """ + page = h.get_page_number(request.params) + + limit = ITEMS_LIMIT + data_dict = {u'start': (page - 1) * limit, u'rows': limit} + + # Filter ignored query parameters + valid_params = ['page'] + params = dict((p, request.params.get(p)) for p in valid_params + if p in request.params) + return data_dict, params + + +def general(): + data_dict, params = _parse_url_params() + data_dict['q'] = u'*:*' + + item_count, results = _package_search(data_dict) + + navigation_urls = _navigation_urls( + params, + item_count=item_count, + limit=data_dict['rows'], + controller=u'feeds', + action=u'general') + + feed_url = _feed_url(params, controller=u'feeds', action=u'general') + + alternate_url = _alternate_url(params) + + guid = _create_atom_id(u'/feeds/dataset.atom') + + desc = u'Recently created or updated datasets on %s' % SITE_TITLE + + return output_feed( + results, + feed_title=SITE_TITLE, + feed_description=desc, + feed_link=alternate_url, + feed_guid=guid, + feed_url=feed_url, + navigation_urls=navigation_urls) + + +def custom(): + """ + Custom atom feed + + """ + q = request.params.get(u'q', u'') + fq = u'' + search_params = {} + for (param, value) in request.params.items(): + if param not in [u'q', u'page', u'sort'] \ + and len(value) and not param.startswith(u'_'): + search_params[param] = value + fq += u'%s:"%s"' % (param, value) + + page = h.get_page_number(request.params) + + limit = ITEMS_LIMIT + data_dict = { + u'q': q, + u'fq': fq, + u'start': (page - 1) * limit, + u'rows': limit, + u'sort': request.params.get(u'sort', None) + } + + item_count, results = _package_search(data_dict) + + navigation_urls = _navigation_urls( + request.params, + item_count=item_count, + limit=data_dict['rows'], + controller=u'feeds', + action=u'custom') + + feed_url = _feed_url(request.params, controller=u'feeds', action=u'custom') + + atom_url = h._url_with_params(u'/feeds/custom.atom', search_params.items()) + + alternate_url = _alternate_url(request.params) + + return output_feed( + results, + feed_title=u'%s - Custom query' % SITE_TITLE, + feed_description=u'Recently created or updated' + ' datasets on %s. Custom query: \'%s\'' % (SITE_TITLE, q), + feed_link=alternate_url, + feed_guid=_create_atom_id(atom_url), + feed_url=feed_url, + navigation_urls=navigation_urls) + + +def _alternate_url(params, **kwargs): + search_params = params.copy() + search_params.update(kwargs) + + # Can't count on the page sizes being the same on the search results + # view. So provide an alternate link to the first page, regardless + # of the page we're looking at in the feed. + search_params.pop(u'page', None) + return _feed_url(search_params, controller=u'package', action=u'search') + + +def _feed_url(query, controller, action, **kwargs): + """ + Constructs the url for the given action. Encoding the query + parameters. + """ + for item in query.iteritems(): + kwargs['query'] = item + return h.url_for(controller=controller, action=action, **kwargs) + + +def _navigation_urls(query, controller, action, item_count, limit, **kwargs): + """ + Constructs and returns first, last, prev and next links for paging + """ + + urls = dict((rel, None) for rel in u'previous next first last'.split()) + + page = int(query.get(u'page', 1)) + + # first: remove any page parameter + first_query = query.copy() + first_query.pop(u'page', None) + urls['first'] = _feed_url(first_query, controller, + action, **kwargs) + + # last: add last page parameter + last_page = (item_count / limit) + min(1, item_count % limit) + last_query = query.copy() + last_query['page'] = last_page + urls['last'] = _feed_url(last_query, controller, + action, **kwargs) + + # previous + if page > 1: + previous_query = query.copy() + previous_query['page'] = page - 1 + urls['previous'] = _feed_url(previous_query, controller, + action, **kwargs) + else: + urls['previous'] = None + + # next + if page < last_page: + next_query = query.copy() + next_query['page'] = page + 1 + urls['next'] = _feed_url(next_query, controller, + action, **kwargs) + else: + urls['next'] = None + + return urls + + +def _create_atom_id(resource_path, authority_name=None, date_string=None): + """ + Helper method that creates an atom id for a feed or entry. + + An id must be unique, and must not change over time. ie - once published, + it represents an atom feed or entry uniquely, and forever. See [4]: + + When an Atom Document is relocated, migrated, syndicated, + republished, exported, or imported, the content of its atom:id + element MUST NOT change. Put another way, an atom:id element + pertains to all instantiations of a particular Atom entry or feed; + revisions retain the same content in their atom:id elements. It is + suggested that the atom:id element be stored along with the + associated resource. + + resource_path + The resource path that uniquely identifies the feed or element. This + mustn't be something that changes over time for a given entry or feed. + And does not necessarily need to be resolvable. + + e.g. ``"/group/933f3857-79fd-4beb-a835-c0349e31ce76"`` could represent + the feed of datasets belonging to the identified group. + + authority_name + The domain name or email address of the publisher of the feed. See [3] + for more details. If ``None`` then the domain name is taken from the + config file. First trying ``ckan.feeds.authority_name``, and failing + that, it uses ``ckan.site_url``. Again, this should not change over + time. + + date_string + A string representing a date on which the authority_name is owned by + the publisher of the feed. + + e.g. ``"2012-03-22"`` + + Again, this should not change over time. + + If date_string is None, then an attempt is made to read the config + option ``ckan.feeds.date``. If that's not available, + then the date_string is not used in the generation of the atom id. + + Following the methods outlined in [1], [2] and [3], this function produces + tagURIs like: + ``"tag:thedatahub.org,2012:/group/933f3857-79fd-4beb-a835-c0349e31ce76"``. + + If not enough information is provide to produce a valid tagURI, then only + the resource_path is used, e.g.: :: + + "http://thedatahub.org/group/933f3857-79fd-4beb-a835-c0349e31ce76" + + or + + "/group/933f3857-79fd-4beb-a835-c0349e31ce76" + + The latter of which is only used if no site_url is available. And it + should be noted will result in an invalid feed. + + [1] http://web.archive.org/web/20110514113830/http://diveintomark.org/\ + archives/2004/05/28/howto-atom-id + [2] http://www.taguri.org/ + [3] http://tools.ietf.org/html/rfc4151#section-2.1 + [4] http://www.ietf.org/rfc/rfc4287 + """ + if authority_name is None: + authority_name = config.get(u'ckan.feeds.authority_name', u'').strip() + if not authority_name: + site_url = config.get(u'ckan.site_url', u'').strip() + authority_name = urlparse.urlparse(site_url).netloc + + if not authority_name: + log.warning(u'No authority_name available for feed generation. ' + 'Generated feed will be invalid.') + + if date_string is None: + date_string = config.get(u'ckan.feeds.date', u'') + + if not date_string: + log.warning(u'No date_string available for feed generation. ' + 'Please set the "ckan.feeds.date" config value.') + + # Don't generate a tagURI without a date as it wouldn't be valid. + # This is best we can do, and if the site_url is not set, then + # this still results in an invalid feed. + site_url = config.get(u'ckan.site_url', u'') + return u''.join([site_url, resource_path]) + + tagging_entity = u','.join([authority_name, date_string]) + return u':'.join(['tag', tagging_entity, resource_path]) + + +class _FixedAtom1Feed(webhelpers.feedgenerator.Atom1Feed): + """ + The Atom1Feed defined in webhelpers doesn't provide all the fields we + might want to publish. + * In Atom1Feed, each <entry> is created with identical <updated> and + <published> fields. See [1] (webhelpers 1.2) for details. + So, this class fixes that by allow an item to set both an <updated> and + <published> field. + * In Atom1Feed, the feed description is not used. So this class uses the + <subtitle> field to publish that. + [1] https://bitbucket.org/bbangert/webhelpers/src/f5867a319abf/\ + webhelpers/feedgenerator.py#cl-373 + """ + + def add_item(self, *args, **kwargs): + """ + Drop the pubdate field from the new item. + """ + if u'pubdate' in kwargs: + kwargs.pop(u'pubdate') + defaults = {u'updated': None, u'published': None} + defaults.update(kwargs) + super(_FixedAtom1Feed, self).add_item(*args, **defaults) + + def latest_post_date(self): + """ + Calculates the latest post date from the 'updated' fields, + rather than the 'pubdate' fields. + """ + updates = [ + item['updated'] for item in self.items + if item['updated'] is not None + ] + if not len(updates): # delegate to parent for default behaviour + return super(_FixedAtom1Feed, self).latest_post_date() + return max(updates) + + def add_item_elements(self, handler, item): + """ + Add the <updated> and <published> fields to each entry that's written + to the handler. + """ + super(_FixedAtom1Feed, self).add_item_elements(handler, item) + + dfunc = webhelpers.feedgenerator.rfc3339_date + + if (item['updated']): + handler.addQuickElement(u'updated', + dfunc(item['updated']).decode(u'utf-8')) + + if (item['published']): + handler.addQuickElement(u'published', + dfunc(item['published']).decode(u'utf-8')) + + def add_root_elements(self, handler): + """ + Add additional feed fields. + * Add the <subtitle> field from the feed description + * Add links other pages of the logical feed. + """ + super(_FixedAtom1Feed, self).add_root_elements(handler) + + handler.addQuickElement(u'subtitle', self.feed['description']) + + for page in [u'previous', u'next', u'first', u'last']: + if self.feed.get(page + u'_page', None): + handler.addQuickElement(u'link', u'', { + u'rel': page, + u'href': self.feed.get(page + u'_page') + }) + + +# Routing +feeds.add_url_rule(u'/dataset.atom', methods=[u'GET'], view_func=general) +feeds.add_url_rule(u'/custom.atom', methods=[u'GET'], view_func=custom) +feeds.add_url_rule(u'/tag/<string:id>.atom', methods=[u'GET'], view_func=tag) +feeds.add_url_rule( + u'/group/<string:id>.atom', methods=[u'GET'], view_func=group) +feeds.add_url_rule( + u'/organization/<string:id>.atom', + methods=[u'GET'], + view_func=organization)
diff --git a/ckan/tests/controllers/test_feed.py b/ckan/tests/controllers/test_feed.py --- a/ckan/tests/controllers/test_feed.py +++ b/ckan/tests/controllers/test_feed.py @@ -1,89 +1,99 @@ # encoding: utf-8 from ckan.lib.helpers import url_for -from webhelpers.feedgenerator import GeoAtom1Feed - -import ckan.plugins as plugins import ckan.tests.helpers as helpers import ckan.tests.factories as factories +import ckan.plugins as plugins +from webhelpers.feedgenerator import GeoAtom1Feed class TestFeedNew(helpers.FunctionalTestBase): - @classmethod def teardown_class(cls): helpers.reset_db() def test_atom_feed_page_zero_gives_error(self): group = factories.Group() - offset = url_for(controller='feed', action='group', - id=group['name']) + '?page=0' + offset = url_for(u'feeds.group', id=group['name']) + '?page=0' app = self._get_test_app() + offset = url_for(u'feeds.group', id=group['name']) + u'?page=0' + res = app.get(offset, status=400) assert '"page" parameter must be a positive integer' in res, res def test_atom_feed_page_negative_gives_error(self): group = factories.Group() - offset = url_for(controller='feed', action='group', - id=group['name']) + '?page=-2' + offset = url_for(u'feeds.group', id=group['name']) + '?page=-2' app = self._get_test_app() + offset = url_for(u'feeds.group', id=group['name']) + '?page=-2' res = app.get(offset, status=400) assert '"page" parameter must be a positive integer' in res, res def test_atom_feed_page_not_int_gives_error(self): group = factories.Group() - offset = url_for(controller='feed', action='group', - id=group['name']) + '?page=abc' + offset = url_for(u'feeds.group', id=group['name']) + '?page=abc' app = self._get_test_app() + offset = url_for(u'feeds.group', id=group['name']) + '?page=abc' res = app.get(offset, status=400) assert '"page" parameter must be a positive integer' in res, res def test_general_atom_feed_works(self): dataset = factories.Dataset() - offset = url_for(controller='feed', action='general') + offset = url_for(u'feeds.general') app = self._get_test_app() + offset = url_for(u'feeds.general') res = app.get(offset) - assert '<title>{0}</title>'.format(dataset['title']) in res.body + assert u'<title>{0}</title>'.format( + dataset['title']) in res.body def test_group_atom_feed_works(self): group = factories.Group() dataset = factories.Dataset(groups=[{'id': group['id']}]) - offset = url_for(controller='feed', action='group', - id=group['name']) + offset = url_for(u'feeds.group', id=group['name']) app = self._get_test_app() + offset = url_for(u'feeds.group', id=group['name']) res = app.get(offset) - assert '<title>{0}</title>'.format(dataset['title']) in res.body + assert u'<title>{0}</title>'.format( + dataset['title']) in res.body def test_organization_atom_feed_works(self): group = factories.Organization() dataset = factories.Dataset(owner_org=group['id']) - offset = url_for(controller='feed', action='organization', - id=group['name']) + offset = url_for(u'feeds.organization', id=group['name']) app = self._get_test_app() + offset = url_for(u'feeds.organization', id=group['name']) res = app.get(offset) - assert '<title>{0}</title>'.format(dataset['title']) in res.body + assert u'<title>{0}</title>'.format( + dataset['title']) in res.body def test_custom_atom_feed_works(self): dataset1 = factories.Dataset( - title='Test weekly', - extras=[{'key': 'frequency', 'value': 'weekly'}]) + title=u'Test weekly', + extras=[{ + 'key': 'frequency', + 'value': 'weekly' + }]) dataset2 = factories.Dataset( - title='Test daily', - extras=[{'key': 'frequency', 'value': 'daily'}]) - offset = url_for(controller='feed', action='custom') - params = { - 'q': 'frequency:weekly' - } + title=u'Test daily', + extras=[{ + 'key': 'frequency', + 'value': 'daily' + }]) + + offset = url_for(u'feeds.custom') + params = {'q': 'frequency:weekly'} app = self._get_test_app() res = app.get(offset, params=params) - assert '<title>{0}</title>'.format(dataset1['title']) in res.body + assert u'<title>{0}</title>'.format( + dataset1['title']) in res.body - assert '<title>{0}</title>'.format(dataset2['title']) not in res.body + assert u'<title">{0}</title>'.format( + dataset2['title']) not in res.body class TestFeedInterface(helpers.FunctionalTestBase): @@ -102,8 +112,7 @@ def teardown_class(cls): def test_custom_class_used(self): app = self._get_test_app() - with app.flask_app.test_request_context(): - offset = url_for(controller='feed', action='general') + offset = url_for(u'feeds.general') app = self._get_test_app() res = app.get(offset) @@ -117,16 +126,12 @@ def test_additional_fields_added(self): 'xmax': '3567770', } - extras = [ - {'key': k, 'value': v} for (k, v) in - metadata.items() - ] + extras = [{'key': k, 'value': v} for (k, v) in metadata.items()] factories.Dataset(extras=extras) app = self._get_test_app() - with app.flask_app.test_request_context(): - offset = url_for(controller='feed', action='general') + offset = url_for(u'feeds.general') app = self._get_test_app() res = app.get(offset) @@ -142,6 +147,6 @@ def get_feed_class(self): def get_item_additional_fields(self, dataset_dict): extras = {e['key']: e['value'] for e in dataset_dict['extras']} - box = tuple(float(extras.get(n)) - for n in ('ymin', 'xmin', 'ymax', 'xmax')) + box = tuple( + float(extras.get(n)) for n in ('ymin', 'xmin', 'ymax', 'xmax')) return {'geometry': box}
[#3567] blueprint feeds controller #Fixes # #3567 With this PR we are moving feeds controller to feeds Blueprint with all endpoints. Within this change, `webhelpers.FeedGenerator` is replaced by `werkzeug.contrib.atom.AtomFeed` and feed output format is generated by [Atom Syndication](https://tools.ietf.org/html/rfc4287#section-1.1)
This is looking great @tino097! Can't wait to merge all the other Flask stuff to get this properly reviewed and merged @tino097 can you merge latest master please? Cheers @tino097 there are unrelated changes in i18n and js files that revert things on master? Do you know what is going on with the PR? @amercader im checking now, cant recall that i had a issue with merging data from master, but i will start new PR
2017-10-12T12:40:36
ckan/ckan
3,884
ckan__ckan-3884
[ "3869" ]
8e153787ba7baf545f8d17912102b90d17f560aa
diff --git a/ckan/lib/uploader.py b/ckan/lib/uploader.py --- a/ckan/lib/uploader.py +++ b/ckan/lib/uploader.py @@ -7,11 +7,14 @@ import magic import mimetypes +from werkzeug.datastructures import FileStorage as FlaskFileStorage + import ckan.lib.munge as munge import ckan.logic as logic import ckan.plugins as plugins from ckan.common import config +ALLOWED_UPLOAD_TYPES = (cgi.FieldStorage, FlaskFileStorage) log = logging.getLogger(__name__) _storage_path = None @@ -19,6 +22,12 @@ _max_image_size = None +def _get_underlying_file(wrapper): + if isinstance(wrapper, FlaskFileStorage): + return wrapper.stream + return wrapper.file + + def get_uploader(upload_to, old_filename=None): '''Query IUploader plugins and return an uploader instance for general files.''' @@ -130,13 +139,13 @@ def update_data_dict(self, data_dict, url_field, file_field, clear_field): if not self.storage_path: return - if isinstance(self.upload_field_storage, cgi.FieldStorage): + if isinstance(self.upload_field_storage, (ALLOWED_UPLOAD_TYPES)): self.filename = self.upload_field_storage.filename self.filename = str(datetime.datetime.utcnow()) + self.filename self.filename = munge.munge_filename_legacy(self.filename) self.filepath = os.path.join(self.storage_path, self.filename) data_dict[url_field] = self.filename - self.upload_file = self.upload_field_storage.file + self.upload_file = _get_underlying_file(self.upload_field_storage) self.tmp_filepath = self.filepath + '~' # keep the file if there has been no change elif self.old_filename and not self.old_filename.startswith('http'): @@ -206,7 +215,7 @@ def __init__(self, resource): if config_mimetype_guess == 'file_ext': self.mimetype = mimetypes.guess_type(url)[0] - if isinstance(upload_field_storage, cgi.FieldStorage): + if isinstance(upload_field_storage, ALLOWED_UPLOAD_TYPES): self.filesize = 0 # bytes self.filename = upload_field_storage.filename @@ -214,8 +223,7 @@ def __init__(self, resource): resource['url'] = self.filename resource['url_type'] = 'upload' resource['last_modified'] = datetime.datetime.utcnow() - self.upload_file = upload_field_storage.file - + self.upload_file = _get_underlying_file(upload_field_storage) self.upload_file.seek(0, os.SEEK_END) self.filesize = self.upload_file.tell() # go back to the beginning of the file buffer diff --git a/ckan/views/api.py b/ckan/views/api.py --- a/ckan/views/api.py +++ b/ckan/views/api.py @@ -197,7 +197,8 @@ def mixed(multi_dict): if request.method == u'PUT' and not request_data: raise ValueError(u'Invalid request. Please use the POST method for ' 'your request') - + for field_name, file_ in request.files.iteritems(): + request_data[field_name] = file_ log.debug(u'Request data extracted: %r', request_data) return request_data
diff --git a/ckan/tests/controllers/test_api.py b/ckan/tests/controllers/test_api.py --- a/ckan/tests/controllers/test_api.py +++ b/ckan/tests/controllers/test_api.py @@ -6,19 +6,67 @@ ''' import json import re +import mock +import __builtin__ as builtins +from StringIO import StringIO -from ckan.lib.helpers import url_for from nose.tools import assert_equal, assert_in, eq_ +from pyfakefs import fake_filesystem +from ckan.lib.helpers import url_for import ckan.tests.helpers as helpers from ckan.tests import factories -from ckan.lib import helpers as template_helpers +from ckan.lib import helpers as template_helpers, uploader as ckan_uploader import ckan.plugins as p from ckan import model +fs = fake_filesystem.FakeFilesystem() +fake_os = fake_filesystem.FakeOsModule(fs) +fake_open = fake_filesystem.FakeFileOpen(fs) +real_open = open + + +def mock_open_if_open_fails(*args, **kwargs): + try: + return real_open(*args, **kwargs) + except (OSError, IOError): + return fake_open(*args, **kwargs) + class TestApiController(helpers.FunctionalTestBase): + @helpers.change_config('ckan.storage_path', '/doesnt_exist') + @mock.patch.object(builtins, 'open', side_effect=mock_open_if_open_fails) + @mock.patch.object(ckan_uploader, 'os', fake_os) + @mock.patch.object(ckan_uploader, '_storage_path', new='/doesnt_exist') + def test_resource_create_upload_file(self, _): + user = factories.User() + pkg = factories.Dataset(creator_user_id=user['id']) + # upload_content = StringIO() + # upload_content.write('test-content') + + url = url_for( + controller='api', + action='action', + logic_function='resource_create', ver='/3') + env = {'REMOTE_USER': user['name'].encode('ascii')} + postparams = { + 'name': 'test-flask-upload', + 'package_id': pkg['id'] + } + upload_content = 'test-content' + upload_info = ('upload', 'test-upload.txt', upload_content) + app = self._get_test_app() + resp = app.post( + url, params=postparams, + upload_files=[upload_info], + extra_environ=env + # content_type= 'application/json' + ) + result = resp.json['result'] + eq_('upload', result['url_type']) + eq_(len(upload_content), result['size']) + def test_unicode_in_error_message_works_ok(self): # Use tag_delete to echo back some unicode app = self._get_test_app()
File uploads don't work on new Flask based API For instance: ``` curl -X POST http://localhost:5000/api/action/resource_create \ -F "package_id=9222f234-2839-4864-8463-03dca09d6237" \ -F "name=Test upload API" \ -F "upload=@/home/adria/Downloads/valid.csv" \ -H "Authorization: API_KEY" ``` Works on 2.7 but not on master (the resource is created but no file is uploaded). The `data_dict` received by `resource_create` does not contain any `upload` key at all, so that is being lost in when [getting the request data](https://github.com/ckan/ckan/blob/master/ckan/views/api.py#L133).
Do you intend to work on this? Anything I can do to help? I had a quick look at this. We need to fix this at three levels: 1. We need to include incoming files in the `data_dict` passed to actions: ```diff diff --git a/ckan/views/api.py b/ckan/views/api.py index b9ed2e6..d7d73f2 100644 --- a/ckan/views/api.py +++ b/ckan/views/api.py @@ -198,6 +198,9 @@ def _get_request_data(try_url_params=False): raise ValueError(u'Invalid request. Please use the POST method for ' 'your request') + for field_name, file_ in request.files.iteritems(): + request_data[field_name] = file_ + log.debug(u'Request data extracted: %r', request_data) return request_data ``` 2. `Upload` and `ResourceUpload` classes need to also check against the [class](http://werkzeug.pocoo.org/docs/0.12/datastructures/#werkzeug.datastructures.FileStorage) used by Flask/Werkzeug ```diff diff --git a/ckan/lib/uploader.py b/ckan/lib/uploader.py index f83817c..6de65c9 100644 --- a/ckan/lib/uploader.py +++ b/ckan/lib/uploader.py @@ -7,6 +7,8 @@ import logging import magic import mimetypes +from werkzeug.datastructures import FileStorage as flask_FileStorage + import ckan.lib.munge as munge import ckan.logic as logic import ckan.plugins as plugins @@ -206,7 +208,8 @@ class ResourceUpload(object): if config_mimetype_guess == 'file_ext': self.mimetype = mimetypes.guess_type(url)[0] - if isinstance(upload_field_storage, cgi.FieldStorage): + if isinstance( + upload_field_storage, (cgi.FieldStorage, flask_FileStorage)): self.filesize = 0 # bytes self.filename = upload_field_storage.filename ``` 3. We need to refactor the same classes so any operation we did against the current `FieldStorage` object is supported against the new one, eg this is the first error I'm getting without changing anything: ``` File "/home/adria/dev/pyenvs/ckan/src/ckan/ckan/lib/uploader.py", line 46, in get_resource_uploader upload = ResourceUpload(data_dict) File "/home/adria/dev/pyenvs/ckan/src/ckan/ckan/lib/uploader.py", line 220, in __init__ self.upload_file = upload_field_storage.file File "/home/adria/dev/pyenvs/ckan/local/lib/python2.7/site-packages/werkzeug/datastructures.py", line 2723, in __getattr__ return getattr(self.stream, name) AttributeError: '_io.BytesIO' object has no attribute 'file' ``` Not sure if we can handle each failing call individually or we need some kind of wrapper like the one @wardi mentioned. 4. And of course we need a test that uploads a file via the API to make sure this works going forward @mattfullerton does this sound like something you could look into relatively soon? Otherwise @smotornyuk will work on it here's what ckanapi.LocalCKAN does for file-like objects passed to the API: https://github.com/ckan/ckanapi/blob/master/ckanapi/localckan.py#L54-L69 There's a special case for streams. Some actions assume we can seek on uploaded files so in that case we need to create a temporary file. @amercader I would have volunteered if it wasn't going to get looked at soon, as I have one CKAN where I'd like to stay on master and we do a lot of file uploads via API. Happy to let @smotornyuk work on it.
2017-10-26T10:19:23
ckan/ckan
3,888
ckan__ckan-3888
[ "3876" ]
6012f416c58152f20519043393adb63597fd24ba
diff --git a/ckan/controllers/group.py b/ckan/controllers/group.py --- a/ckan/controllers/group.py +++ b/ckan/controllers/group.py @@ -639,6 +639,9 @@ def delete(self, id): abort(403, _('Unauthorized to delete group %s') % '') except NotFound: abort(404, _('Group not found')) + except ValidationError as e: + h.flash_error(e.error_dict['message']) + h.redirect_to(controller='organization', action='read', id=id) return self._render_template('group/confirm_delete.html', group_type) def members(self, id): diff --git a/ckan/logic/action/delete.py b/ckan/logic/action/delete.py --- a/ckan/logic/action/delete.py +++ b/ckan/logic/action/delete.py @@ -346,12 +346,26 @@ def _group_or_org_delete(context, data_dict, is_org=False): else: _check_access('group_delete', context, data_dict) - # organization delete will delete all datasets for that org - # FIXME this gets all the packages the user can see which generally will - # be all but this is only a fluke so we should fix this properly + # organization delete will not occure whilke all datasets for that org are + # not deleted if is_org: - for pkg in group.packages(with_private=True): - _get_action('package_delete')(context, {'id': pkg.id}) + datasets = model.Session.query(model.Package) \ + .filter_by(owner_org=group.id) \ + .filter(model.Package.state != 'deleted') \ + .count() + if datasets: + if not authz.check_config_permission('ckan.auth.create_unowned_dataset'): + raise ValidationError(_('Organization cannot be deleted while it ' + 'still has datasets')) + + pkg_table = model.package_table + # using Core SQLA instead of the ORM should be faster + model.Session.execute( + pkg_table.update().where( + sqla.and_(pkg_table.c.owner_org == group.id, + pkg_table.c.state != 'deleted') + ).values(owner_org=None) + ) rev = model.repo.new_revision() rev.author = user @@ -391,7 +405,9 @@ def group_delete(context, data_dict): def organization_delete(context, data_dict): '''Delete an organization. - You must be authorized to delete the organization. + You must be authorized to delete the organization + and no datasets should belong to the organization + unless 'ckan.auth.create_unowned_dataset=True' :param id: the name or id of the organization :type id: string
diff --git a/ckan/tests/controllers/test_organization.py b/ckan/tests/controllers/test_organization.py --- a/ckan/tests/controllers/test_organization.py +++ b/ckan/tests/controllers/test_organization.py @@ -1,5 +1,6 @@ # encoding: utf-8 +from ckan.common import config from bs4 import BeautifulSoup from nose.tools import assert_equal, assert_true, assert_in from ckan.lib.helpers import url_for @@ -209,6 +210,35 @@ def test_anon_user_trying_to_delete_fails(self): id=self.organization['id']) assert_equal(organization['state'], 'active') + @helpers.change_config('ckan.auth.create_unowned_dataset', False) + def test_delete_organization_with_datasets(self): + ''' Test deletion of organization that has datasets''' + text = 'Organization cannot be deleted while it still has datasets' + datasets = [factories.Dataset(owner_org=self.organization['id']) + for i in range(0, 5)] + response = self.app.get( + url=url_for( + controller='organization', + action='delete', + id=self.organization['id']), + status=200, + extra_environ=self.user_env) + + form = response.forms['organization-confirm-delete-form'] + response = submit_and_follow( + self.app, form, name='delete', extra_environ=self.user_env) + assert text in response.body + + def test_delete_organization_with_unknown_dataset_true(self): + ''' Test deletion of organization that has datasets and unknown + datasets are set to true''' + dataset = factories.Dataset(owner_org=self.organization['id']) + assert_equal(dataset['owner_org'], self.organization['id']) + helpers.call_action('organization_delete', id=self.organization['id']) + + dataset = helpers.call_action('package_show', id=dataset['id']) + assert_equal(dataset['owner_org'], None) + class TestOrganizationBulkProcess(helpers.FunctionalTestBase): def setup(self): @@ -217,9 +247,10 @@ def setup(self): self.user = factories.User() self.user_env = {'REMOTE_USER': self.user['name'].encode('ascii')} self.organization = factories.Organization(user=self.user) - self.organization_bulk_url = url_for(controller='organization', - action='bulk_process', - id=self.organization['id']) + self.organization_bulk_url = url_for( + controller='organization', + action='bulk_process', + id=self.organization['id']) def test_make_private(self): datasets = [factories.Dataset(owner_org=self.organization['id'])
Delete organization ### CKAN Version if known (or site URL) Tested on 2.7 and 2.6.4 ckan versions ### Please describe the expected behavior If you delete the organization(not purge) what should happen with the datasets for that organization ? create_unowned_dataset flag is set as False, and there is no owner organization for those datasets. ### Please describe the actual behavior If you delete the organization the datasets that belongs to that organizations are not deleted and owner organization is null. Is this expected behavior ? ### What steps can be taken to reproduce the issue? Delete organization with datasets
2017-10-27T14:15:46
ckan/ckan
3,898
ckan__ckan-3898
[ "3855" ]
c5a1be8a82d8907824f2d67fcadae18fb249cdbd
diff --git a/ckan/views/__init__.py b/ckan/views/__init__.py --- a/ckan/views/__init__.py +++ b/ckan/views/__init__.py @@ -54,7 +54,7 @@ def set_cors_headers_for_response(response): cors_origin_allowed = None if asbool(config.get(u'ckan.cors.origin_allow_all')): - cors_origin_allowed = u'*' + cors_origin_allowed = b'*' elif config.get(u'ckan.cors.origin_whitelist') and \ request.headers.get(u'Origin') \ in config[u'ckan.cors.origin_whitelist'].split(u' '):
Change CORS header keys and values to string instead of unicode The CORS header keys and values being unicode raised problems when using uWSGI with CKAN. uWSGI expects the header keys to be string instead of unicode which results in a TypeError. ### Features: - [ ] includes tests covering changes - [ ] includes updated documentation - [ ] includes user-visible changes - [ ] includes API changes - [x] includes bugfix for possible backport Please [X] all the boxes above that apply
This makes our test that checks for string literals fail. Rather than remove the `u''` bit, can you replace it by a `b''`? Check the docs on this: http://docs.ckan.org/en/ckan-2.7.2/contributing/unicode.html#string-literals cc @torfsen Thanks @ljupchokotev!
2017-11-01T10:19:58
ckan/ckan
3,925
ckan__ckan-3925
[ "3806" ]
038f6c73a21b13311509ac50737705c137b50916
diff --git a/ckan/lib/cli.py b/ckan/lib/cli.py --- a/ckan/lib/cli.py +++ b/ckan/lib/cli.py @@ -22,13 +22,13 @@ from paste.script.util.logging_config import fileConfig import click +from ckan.config.middleware import make_app import ckan.logic as logic import ckan.model as model import ckan.include.rjsmin as rjsmin import ckan.include.rcssmin as rcssmin import ckan.plugins as p from ckan.common import config -from ckan.tests.helpers import _get_test_app # This is a test Flask request context to be used internally. # Do not use it! @@ -232,7 +232,9 @@ def load_config(config, load_site_user=True): # Set this internal test request context with the configured environment so # it can be used when calling url_for from the CLI. global _cli_test_request_context - flask_app = _get_test_app().flask_app + + app = make_app(conf.global_conf, **conf.local_conf) + flask_app = app.apps['flask_app']._wsgi_app _cli_test_request_context = flask_app.test_request_context() registry = Registry()
Paster/CLI config-tool requires _get_test_app which in turn requires a dev-only dependency ### CKAN Version if known (or site URL) 2.7/close-to-master ### Please describe the expected behaviour Paster can be used ### Please describe the actual behaviour File "/usr/lib/ckan/default/src/ckan/ckan/lib/cli.py", line 31, in <module> from ckan.tests.helpers import _get_test_app File "/usr/lib/ckan/default/src/ckan/ckan/tests/helpers.py", line 34, in <module> import mock ImportError: No module named mock ### What steps can be taken to reproduce the issue? Do not pip install dev-requirements and then use paster config-tool (`paster --plugin=ckan config-tool`)
Tried adding ```dev-requirements.txt``` to the ```Dockerfile``` to get mock, but still getting the same error. Messages from ```docker-compose logs -f ckan``` do report successful install of mock. ``` ... RUN ckan-pip install --upgrade -r $CKAN_VENV/src/ckan/requirements.txt && \ ckan-pip install --upgrade -r $CKAN_VENV/src/ckan/dev-requirements.txt && \ ckan-pip install -e $CKAN_VENV/src/ckan/ && \ ... ``` @AnveshC Not yet. I haven't had enough time to really dig into the issue. it seems to be introduced by https://github.com/ckan/ckan/pull/3782 as a conscious tradeoff, so in line with that it might be most appropriate to move the mock dependency from `dev-requirements.txt` to the `requirements.txt` file. @goatsweater it still not picking up on mock even though it's installs when building I think is caused by the `ckan_home` volume. For me `docker-compose down`, `docker volume prune` and `docker-compose up` resolved that problem.
2017-11-16T16:18:08
ckan/ckan
3,946
ckan__ckan-3946
[ "3926" ]
99795f248d015c57e8505e9fb44fc15fb8dbf4ca
diff --git a/ckan/config/middleware/pylons_app.py b/ckan/config/middleware/pylons_app.py --- a/ckan/config/middleware/pylons_app.py +++ b/ckan/config/middleware/pylons_app.py @@ -10,6 +10,7 @@ from paste.registry import RegistryManager from paste.urlparser import StaticURLParser from paste.deploy.converters import asbool +from paste.fileapp import _FileIter from pylons.middleware import ErrorHandler, StatusCodeRedirect from routes.middleware import RoutesMiddleware from repoze.who.config import WhoConfig @@ -223,33 +224,58 @@ def can_handle_request(self, environ): return (False, self.app_name) -def generate_close_and_callback(iterable, callback, environ): - """ - return a generator that passes through items from iterable - then calls callback(environ). +class CloseCallbackWrapper(object): + def __init__(self, iterable, callback, environ): + # pylons.fileapp expects app_iter to have `file` attribute. + self.file = iterable + self.callback = callback + self.environ = environ + + def __iter__(self): + """ + return a generator that passes through items from iterable + then calls callback(environ). + """ + try: + for item in self.file: + yield item + except GeneratorExit: + if hasattr(self.file, 'close'): + self.file.close() + raise + finally: + self.callback(self.environ) + + +class FileIterWrapper(CloseCallbackWrapper, _FileIter): + """Same CloseCallbackWrapper, just with _FileIter mixin. + + That will prevent pylons from converting file responses into + in-memori lists. """ - try: - for item in iterable: - yield item - except GeneratorExit: - if hasattr(iterable, 'close'): - iterable.close() - raise - finally: - callback(environ) + pass def execute_on_completion(application, config, callback): """ Call callback(environ) once complete response is sent """ + def inner(environ, start_response): try: result = application(environ, start_response) except: callback(environ) raise - return generate_close_and_callback(result, callback, environ) + # paste.fileapp converts non-file responses into list + # In order to avoid interception of OOM Killer + # file responses wrapped into generator with + # _FileIter in parent tree. + klass = CloseCallbackWrapper + if isinstance(result, _FileIter): + klass = FileIterWrapper + return klass(result, callback, environ) + return inner
ckan dies downloading 1GB file in debug mode (oom_killer) ### CKAN Version if known (or site URL) 2.6.0 ### Please describe the expected behaviour ckan "paster serve" web server process does not mysteriously exit when I download the 1GB file. ### Please describe the actual behaviour ckan "paster serve" web server process mysteriously exits when I download the 1GB file. No error message is produced to stdout/stderr or apache logs. The error shows up in /var/log/messages and dmesg: "python2 invoked oom-killer" and "Out of memory: Kill process 1699 (python2) score 418 or sacrifice child". ### What steps can be taken to reproduce the issue? Set debug to true in ckan.ini. (debug mode must be on to hit the problem) Increase file-size limits to handle 1GB files: Increase max_resource_size (and nginx client_max_body_size if nginx is used). Create 1GB file eg dd if=/dev/zero of=test1G bs=1GB count=1 Run "paster serve". (Running apache requires debug to be false so the problem does not occur) Create a dataset and upload a 1GB file to the new initial resource Click the download link on this 1GB file. (/dataset/.../resource/.../download/test1g) The ckan "paster serve" silently exits with no error or stack trace. The download fails. ### Details I found the problem line like this: //pdb breakpoint right in the download code before it dies: vi controllers/package.py +/"def resource_download" before "return app_iter", insert the line: import pdb; pdb.set_trace() I just kept pressing "r" to return up the stack until the last func before ckan mysteriously exited with no error or information. Then I stepped forward a few lines to the exact line which died. Problem line is in site-packages/weberror/evalexception.py: return_iter = list(app_iter) The surrounding code shows more about the problem: ``` B-> if isinstance(app_iter, fileapp._FileIter): return app_iter try: return_iter = list(app_iter) return return_iter ``` So if type is _FileIter, it works fine and does not die. But there is a feature in ckan called "ckan.use_pylons_response_cleanup_middleware" which is on by default. When it is off, the problem goes away. It wraps _FileIter inside generate_close_and_callback. It does that here: /usr/lib/ckan/default/src/ckan/ckan/config/middleware/pylons_app.py return generate_close_and_callback(result, callback, environ) So type is no longer _FileIter so evalexception.py runs "list(app_iter)" and that triggers oom_killer. When debug is false, pylons ErrorHandler middleware does not use EvalException so the problem is avoided. (see pylons/middleware.py function ErrorHandler) ### Possible ideas for a solution/improvement? Perhaps option "ckan.use_pylons_response_cleanup_middleware" should default to false? Perhaps if the ckan wrapper was a subclass of _FileIter, that would fix the problem? Perhaps the oom_killer should only kill the 1 child process, not all the web server processes? Perhaps oom_killer should have larger memory limits in debug mode? Can EvalException (or the ErrorHandler middleware in general) somehow be skipped for downloads? I notice that when debug is false, weberror does not call "list(app_iter)" but does wrap app_iter in wraps app_iter in CatchingIter (see weberror/errormiddleware.py:188). Perhaps this is a better way to wrap it? I am not sure if these 2 actions are comparable.
@amercader this is related to the flask changes, what do you think?
2017-12-04T18:13:33
ckan/ckan
3,962
ckan__ckan-3962
[ "3961" ]
4892cf39bc889fd100b4a4e44f5c452513c76339
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -216,6 +216,7 @@ def parse_version(s): keywords='data packaging component tool server', long_description=__long_description__, zip_safe=False, + include_package_data=True, packages=find_packages(exclude=['ez_setup']), namespace_packages=['ckanext', 'ckanext.stats'], message_extractors={
Package resources not included when installing from source in non-editable mode. Known affects: - CKAN 2.7.2; Python 2.7.14; Ubuntu 16.04 & 17.10; ``` $ virtualenv --version 15.1.0 $ virtualenv --no-site-packages test-venv <snip> $ ./test-venv/bin/pip freeze --all pip==9.0.1 setuptools==38.2.4 wheel==0.30.0 ``` ### Expected behaviour Checking out the repository and installing it(without the editable flag) should install the required package resources like `ckan/migration/migrate.cfg`. ## Actual behaviour Installing the package without the editable flag does not include the package resources meaning all JavaScript, CSS, templates and the migration config noted above are not included. This makes the package non-functional. For me the problem arose because `ckan/migration/migrate.cfg` did not exist in my install directory, and hence the database could not be created. There are numerous other files listed in `MANIFEST.in` which are also required for CKAN to run which are not included. ### What steps can be taken to reproduce the issue? Following the [installing from source](http://docs.ckan.org/en/latest/maintaining/installing/install-from-source.html) instructions, omitting the `-e` flag from step **c** ## Resolution. The solution to this is to add `include_package_data=True` to the `setup` call in `setup.py`
2017-12-18T22:26:11
ckan/ckan
3,976
ckan__ckan-3976
[ "3968" ]
0ccb2ce3fc869f2ac3d29dd7e8b7f6b466eb276d
diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py --- a/ckan/lib/helpers.py +++ b/ckan/lib/helpers.py @@ -25,7 +25,7 @@ import webhelpers.text as whtext import webhelpers.date as date from markdown import markdown -from bleach import clean as clean_html, ALLOWED_TAGS, ALLOWED_ATTRIBUTES +from bleach import clean as bleach_clean, ALLOWED_TAGS, ALLOWED_ATTRIBUTES from pylons import url as _pylons_default_url from ckan.common import config, is_flask_request from flask import redirect as _flask_redirect @@ -2102,7 +2102,7 @@ def render_markdown(data, auto_link=True, allow_html=False): data = markdown(data.strip()) else: data = RE_MD_HTML_TAGS.sub('', data.strip()) - data = clean_html( + data = bleach_clean( markdown(data), strip=True, tags=MARKDOWN_TAGS, attributes=MARKDOWN_ATTRIBUTES) # tags can be added by tag:... or tag:"...." and a link will be made @@ -2555,6 +2555,11 @@ def radio(selected, id, checked): value="%s" type="radio">') % (selected, id, selected, id)) +@core_helper +def clean_html(html): + return bleach_clean(unicode(html)) + + core_helper(flash, name='flash') core_helper(localised_number) core_helper(localised_SI_number) @@ -2573,7 +2578,6 @@ def radio(selected, id, checked): core_helper(converters.asbool) # Useful additions from the stdlib. core_helper(urlencode) -core_helper(clean_html, name='clean_html') def load_plugin_helpers():
diff --git a/ckan/tests/lib/test_helpers.py b/ckan/tests/lib/test_helpers.py --- a/ckan/tests/lib/test_helpers.py +++ b/ckan/tests/lib/test_helpers.py @@ -1,5 +1,7 @@ # encoding: utf-8 +import datetime + import nose import pytz import tzlocal @@ -525,6 +527,17 @@ def test_named_timezone(self): eq_(h.get_display_timezone(), pytz.timezone('America/New_York')) +class TestCleanHtml(object): + def test_disallowed_tag(self): + eq_(h.clean_html('<b><bad-tag>Hello'), + u'<b>&lt;bad-tag&gt;Hello&lt;/bad-tag&gt;</b>') + + def test_non_string(self): + # allow a datetime for compatibility with older ckanext-datapusher + eq_(h.clean_html(datetime.datetime(2018, 1, 5, 10, 48, 23, 463511)), + u'2018-01-05 10:48:23.463511') + + class TestHelperException(helpers.FunctionalTestBase): @raises(ckan.exceptions.HelperError)
DataStore status page throws TypeError - Bleach upgrade regression ### CKAN Version if known (or site URL) Git master (2ba282973690f481b1ed075ed9ce54db3f30ba5d) ### Please describe the expected behaviour DataStore status page displays details of DataPusher processing. ### Please describe the actual behaviour DataStore status page fails with Error 500 and following traceback in CKAN log ``` File '/usr/lib/python2.7/site-packages/weberror/errormiddleware.py', line 171 in __call__ app_iter = self.application(environ, sr_checker) File '/usr/lib/python2.7/site-packages/webob/dec.py', line 147 in __call__ resp = self.call_func(req, *args, **self.kwargs) File '/usr/lib/python2.7/site-packages/webob/dec.py', line 208 in call_func return self.func(req, *args, **kwargs) File '/usr/lib/python2.7/site-packages/fanstatic/publisher.py', line 234 in __call__ return request.get_response(self.app) File '/usr/lib/python2.7/site-packages/webob/request.py', line 1053 in get_response application, catch_exc_info=False) File '/usr/lib/python2.7/site-packages/webob/request.py', line 1022 in call_application app_iter = application(self.environ, start_response) File '/usr/lib/python2.7/site-packages/webob/dec.py', line 147 in __call__ resp = self.call_func(req, *args, **self.kwargs) File '/usr/lib/python2.7/site-packages/webob/dec.py', line 208 in call_func return self.func(req, *args, **kwargs) File '/usr/lib/python2.7/site-packages/fanstatic/injector.py', line 54 in __call__ response = request.get_response(self.app) File '/usr/lib/python2.7/site-packages/webob/request.py', line 1053 in get_response application, catch_exc_info=False) File '/usr/lib/python2.7/site-packages/webob/request.py', line 1022 in call_application app_iter = application(self.environ, start_response) File '/srv/ckan/src/ckan/ckan/config/middleware/pylons_app.py', line 266 in inner result = application(environ, start_response) File '/usr/lib/python2.7/site-packages/beaker/middleware.py', line 73 in __call__ return self.app(environ, start_response) File '/usr/lib/python2.7/site-packages/beaker/middleware.py', line 156 in __call__ return self.wrap_app(environ, session_start_response) File '/usr/lib/python2.7/site-packages/routes/middleware.py', line 131 in __call__ response = self.app(environ, start_response) File '/srv/ckan/src/ckan/ckan/config/middleware/common_middleware.py', line 28 in __call__ return self.app(environ, start_response) File '/usr/lib/python2.7/site-packages/pylons/wsgiapp.py', line 125 in __call__ response = self.dispatch(controller, environ, start_response) File '/usr/lib/python2.7/site-packages/pylons/wsgiapp.py', line 324 in dispatch return controller(environ, start_response) File '/srv/ckan/src/ckan/ckan/lib/base.py', line 231 in __call__ res = WSGIController.__call__(self, environ, start_response) File '/usr/lib/python2.7/site-packages/pylons/controllers/core.py', line 221 in __call__ response = self._dispatch_call() File '/usr/lib/python2.7/site-packages/pylons/controllers/core.py', line 172 in _dispatch_call response = self._inspect_call(func) File '/usr/lib/python2.7/site-packages/pylons/controllers/core.py', line 107 in _inspect_call result = self._perform_call(func, args) File '/usr/lib/python2.7/site-packages/pylons/controllers/core.py', line 60 in _perform_call return func(**args) File '/srv/ckan/src/ckan/ckanext/datapusher/plugin.py', line 71 in resource_data extra_vars={'status': datapusher_status}) File '/srv/ckan/src/ckan/ckan/lib/base.py', line 195 in render return cached_template(template_name, render_template) File '/usr/lib/python2.7/site-packages/pylons/templating.py', line 249 in cached_template return render_func() File '/srv/ckan/src/ckan/ckan/lib/base.py', line 137 in render_template return render_jinja2(template_name, globs) File '/srv/ckan/src/ckan/ckan/lib/base.py', line 94 in render_jinja2 return template.render(**extra_vars) File '/usr/lib/python2.7/site-packages/jinja2/environment.py', line 989 in render return self.environment.handle_exception(exc_info, True) File '/usr/lib/python2.7/site-packages/jinja2/environment.py', line 754 in handle_exception reraise(exc_type, exc_value, tb) File '/srv/ckan/src/ckan/ckanext/datapusher/templates/datapusher/resource_data.html', line 1 in top-level template code {% extends "package/resource_edit_base.html" %} File '/srv/ckan/src/ckan/ckanext/datastore/templates/package/resource_edit_base.html', line 1 in top-level template code {% ckan_extends %} File '/srv/ckan/src/ckan/ckanext/datapusher/templates/package/resource_edit_base.html', line 1 in top-level template code {% ckan_extends %} File '/srv/ckan/src/ckan/ckan/templates/package/resource_edit_base.html', line 4 in top-level template code {% set res = c.resource %} File '/srv/ckan/src/ckan/ckan/templates/package/base.html', line 3 in top-level template code {% set pkg = c.pkg_dict or pkg_dict %} File '/srv/ckan/src/ckan/ckan/templates/page.html', line 1 in top-level template code {% extends "base.html" %} File '/srv/ckan/src/ckanext-geoview/ckanext/geoview/templates/base.html', line 1 in top-level template code {% ckan_extends %} File '/srv/ckan/src/ckanext-pages/ckanext/pages/theme/templates_main/base.html', line 1 in top-level template code {% ckan_extends %} File '/srv/ckan/src/ckan/ckan/templates/base.html', line 101 in top-level template code {%- block page %}{% endblock -%} File '/srv/ckan/src/ckan/ckan/templates/page.html', line 19 in block "page" {%- block content %} File '/srv/ckan/src/ckan/ckan/templates/page.html', line 22 in block "content" {% block main_content %} File '/srv/ckan/src/ckan/ckan/templates/page.html', line 74 in block "main_content" {% block primary %} File '/srv/ckan/src/ckan/ckan/templates/page.html', line 87 in block "primary" {% block primary_content %} File '/srv/ckan/src/ckan/ckan/templates/page.html', line 107 in block "primary_content" {% block primary_content_inner %} File '/srv/ckan/src/ckan/ckanext/datapusher/templates/datapusher/resource_data.html', line 76 in block "primary_content_inner" <a href="#" data-target="popover" data-content="<dl>{% for key, value in item.iteritems() %}<dt>{{ key }}</dt><dd>{{ h.clean_html(value) }}</dd>{% endfor %}</dl>" data-html="true">{{ _('Details') }}</a> File '/usr/lib/python2.7/site-packages/bleach/__init__.py', line 99 in clean return cleaner.clean(text) File '/usr/lib/python2.7/site-packages/bleach/sanitizer.py', line 203 in clean raise TypeError(message) TypeError: argument cannot be of 'datetime' type, must be of text type ``` ### What steps can be taken to reproduce the issue? 1. Install CKAN with PR #3952 merged (any commit after 4892cf39bc889fd100b4a4e44f5c452513c76339). 2. Install DataPusher and configure CKAN to work with it. 3. Upload a resource.
@davidread #3952 was your PR would you mind having a look?
2018-01-05T11:19:16
ckan/ckan
3,978
ckan__ckan-3978
[ "3881" ]
794b4d64dafdb4074d1a79e1ed120338ca0c5458
diff --git a/ckanext/datastore/backend/postgres.py b/ckanext/datastore/backend/postgres.py --- a/ckanext/datastore/backend/postgres.py +++ b/ckanext/datastore/backend/postgres.py @@ -23,7 +23,7 @@ import ckanext.datastore.helpers as datastore_helpers import ckanext.datastore.interfaces as interfaces -import psycopg2.extras +from psycopg2.extras import register_default_json, register_composite import distutils.version from sqlalchemy.exc import (ProgrammingError, IntegrityError, DBAPIError, DataError) @@ -117,6 +117,14 @@ def _get_engine_from_url(connection_url): 'ckan.datastore.sqlalchemy.', **extras) _engines[connection_url] = engine + + # don't automatically convert to python objects + # when using native json types in 9.2+ + # http://initd.org/psycopg/docs/extras.html#adapt-json + register_default_json(conn_or_curs=engine.raw_connection().connection, + globally=False, + loads=lambda x: x) + return engine @@ -274,9 +282,7 @@ def _cache_types(context): # redo cache types with json now available. return _cache_types(context) - psycopg2.extras.register_composite('nested', - connection.connection, - True) + register_composite('nested', connection.connection, True) def _pg_version_is_at_least(connection, version):
diff --git a/ckanext/datastore/tests/test_unit.py b/ckanext/datastore/tests/test_unit.py --- a/ckanext/datastore/tests/test_unit.py +++ b/ckanext/datastore/tests/test_unit.py @@ -43,7 +43,7 @@ def test_pg_version_check(self): engine = db._get_engine_from_url(config['sqlalchemy.url']) connection = engine.connect() assert db._pg_version_is_at_least(connection, '8.0') - assert not db._pg_version_is_at_least(connection, '10.0') + assert not db._pg_version_is_at_least(connection, '20.0') class TestLegacyModeSetting():
Add support for postgresql 10 Updated the psycopg2 drivers to support latest Postgresql version Fixes # ### Proposed fixes: ### Features: - [x] includes tests covering changes - [ ] includes updated documentation - [ ] includes user-visible changes - [ ] includes API changes - [ ] includes bugfix for possible backport Please [X] all the boxes above that apply
@groundrace thanks for this. We need to ensure that the actual code also works against postgres 10. Looking at the failures it looks like there are some JSON related ones on the DataStore, so perhaps this needs to be investigated a bit more. Can you check what needs updating?
2018-01-07T11:08:37
ckan/ckan
4,026
ckan__ckan-4026
[ "3929" ]
eda0b4929b5bbd246ea19d10a81fa873b13560d4
diff --git a/ckan/migration/versions/001_add_existing_tables.py b/ckan/migration/versions/001_add_existing_tables.py --- a/ckan/migration/versions/001_add_existing_tables.py +++ b/ckan/migration/versions/001_add_existing_tables.py @@ -2,10 +2,17 @@ from sqlalchemy import * from migrate import * +from ckan.common import config as ckan_config def upgrade(migrate_engine): - meta = MetaData() + schema = ckan_config.get(u'ckan.migrations.target_schema') or 'public' + # we specify the schema here because of a clash with another 'state' table + # in the mdillon/postgis container. You only need to change the value in the + # config if you've altered the default schema from 'public' in your + # postgresql.conf. Because this is such a rarely needed option, it is + # otherwise undocumented. + meta = MetaData(schema=schema) state = Table('state', meta, Column('id', Integer() , primary_key=True, nullable=False),
CKAN's state table clashes with PostGIS generated TIGER state table ### CKAN Version if known (or site URL) 2.8.0a HEAD [e219c2] (although observed earlier tags) ### Please describe the expected behaviour On running `docker-compose up` in a freshly cloned repo, all services start and database migrations run successfully. ### Please describe the actual behaviour `ckan` container exits during start-up with errors (from `db` and `ckan` containers): ``` ckan | Traceback (most recent call last): ckan | File "/usr/local/bin/ckan-paster", line 11, in <module> ckan | sys.exit(run()) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/paste/script/command.py", line 102, in run ckan | invoke(command, command_name, options, args[1:]) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/paste/script/command.py", line 141, in invoke ckan | exit_code = runner.run(args) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/paste/script/command.py", line 236, in run ckan | result = self.command() ckan | File "/usr/lib/ckan/venv/src/ckan/ckan/lib/cli.py", line 356, in command ckan | model.repo.init_db() ckan | File "/usr/lib/ckan/venv/src/ckan/ckan/model/__init__.py", line 187, in init_db db | ERROR: column "id" referenced in foreign key constraint does not exist db | STATEMENT: db | CREATE TABLE package ( db | id SERIAL NOT NULL, db | name VARCHAR(100) NOT NULL, db | title TEXT, db | version VARCHAR(100), db | url TEXT, db | download_url TEXT, db | notes TEXT, db | license_id INTEGER, ckan | self.upgrade_db() ckan | File "/usr/lib/ckan/venv/src/ckan/ckan/model/__init__.py", line 284, in upgrade_db ckan | mig.upgrade(self.metadata.bind, self.migrate_repository, version=version) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/migrate/versioning/api.py", line 186, in upgrade db | state_id INTEGER, db | revision_id INTEGER, db | PRIMARY KEY (id), db | UNIQUE (name), db | FOREIGN KEY(license_id) REFERENCES license (id), db | FOREIGN KEY(state_id) REFERENCES state (id), db | FOREIGN KEY(revision_id) REFERENCES revision (id) db | ) db | db | ckan | return _migrate(url, repository, version, upgrade=True, err=err, **opts) ckan | File "<decorator-gen-16>", line 2, in _migrate ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/migrate/versioning/util/__init__.py", line 160, in with_engine ckan | return f(*a, **kw) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/migrate/versioning/api.py", line 366, in _migrate ckan | schema.runchange(ver, change, changeset.step) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/migrate/versioning/schema.py", line 93, in runchange ckan | change.run(self.engine, step) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/migrate/versioning/script/py.py", line 148, in run ckan | script_func(engine) ckan | File "/usr/lib/ckan/venv/src/ckan/ckan/migration/versions/001_add_existing_tables.py", line 105, in upgrade ckan | meta.create_all() ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/sql/schema.py", line 3934, in create_all ckan | tables=tables) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1929, in _run_visitor ckan | conn._run_visitor(visitorcallable, element, **kwargs) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1538, in _run_visitor ckan | **kwargs).traverse_single(element) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/sql/visitors.py", line 121, in traverse_single ckan | return meth(obj, **kw) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/sql/ddl.py", line 733, in visit_metadata ckan | _is_metadata_operation=True) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/sql/visitors.py", line 121, in traverse_single ckan | return meth(obj, **kw) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/sql/ddl.py", line 767, in visit_table ckan | include_foreign_key_constraints=include_foreign_key_constraints ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 945, in execute ckan | return meth(self, multiparams, params) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/sql/ddl.py", line 68, in _execute_on_connection ckan | return connection._execute_ddl(self, multiparams, params) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1002, in _execute_ddl ckan | compiled ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1189, in _execute_context ckan | context) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1402, in _handle_dbapi_exception ckan | exc_info ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 203, in raise_from_cause ckan | reraise(type(exception), exception, tb=exc_tb, cause=cause) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context ckan | context) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 470, in do_execute ckan | cursor.execute(statement, parameters) ckan | sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) column "id" referenced in foreign key constraint does not exist ckan | [SQL: '\nCREATE TABLE package (\n\tid SERIAL NOT NULL, \n\tname VARCHAR(100) NOT NULL, \n\ttitle TEXT, \n\tversion VARCHAR(100), \n\turl TEXT, \n\tdownload_url TEXT, \n\tnotes TEXT, \n\tlicense_id INTEGER, \n\tstate_id INTEGER, \n\trevision_id INTEGER, \n\tPRIMARY KEY (id), \n\tUNIQUE (name), \n\tFOREIGN KEY(license_id) REFERENCES license (id), \n\tFOREIGN KEY(state_id) REFERENCES state (id), \n\tFOREIGN KEY(revision_id) REFERENCES revision (id)\n)\n\n'] ckan exited with code 1 ``` ### What steps can be taken to reproduce the issue? Clone a fresh repository, with no existing docker images or volumes, then go to `./contrib/docker` and run: ```$ COMPOSE_HTTP_TIMEOUT=120 CKAN_SITE_URL=http://localhost CKAN_PORT=5000 docker-compose up``` ### Notes This seems to be caused by a clash of relation names in PostGIS, where the `mdillon/postgis` image creates a `state` table in the `tiger` namespace, and SQLAlchemy consequently does not create a table for the CKAN model ([./ckan/migration/versions/001_add_existing_tables.py:10](https://github.com/ckan/ckan/blob/e219c2352050d413392e33c560406a5b4e8557ac/ckan/migration/versions/001_add_existing_tables.py#L10)). Adding `public` as a schema argument to the MetaData constructor ([./ckan/migration/versions/001_add_existing_tables.py:8](https://github.com/ckan/ckan/blob/e219c2352050d413392e33c560406a5b4e8557ac/ckan/migration/versions/001_add_existing_tables.py#L8)) seems to solve this. As a workaround, I have added a `DATABASE_SCHEMA=public` variable to pass to the constructor, but happy to produce a PR if I could have some guidance on the preferred means of configuring/passing this schema choice to the migration scripts.
@philtweir a PR would be great! The other workaround is to remove tiger I'd imagine that removing tiger would take an extra step ootb, or a separate image, as it's bundled with mdillon's PostGIS? (or customizing in docker-compose build, I suppose) Schema as an environment variable, default "public", brought in via pylons_config sound OK then? Yes, where I'm working we automatically remove it at startup; your solution sounds better :-) I am getting the same error but adding the `DATABASE_SCHEMA=public` in 001_add_existing_tables.py:9 did not resolve it for me. Now I'm getting: `NameError: global name 'public' is not defined` Anything I might have missed? Sorry, that wasn't well described - that was thinking through passing the schema name in consistently (and a configurable patch is currently WIP), but the specific parameter you want is `schema` so you would have ``MetaData(schema='public')``, for example - this [minimal work-around](https://github.com/flaxandteal/ckan/blob/0ed116f3258cacac723978769d7607326aa082da/ckan/migration/versions/001_add_existing_tables.py#L9) may make it clearer. Also, I did setup from the database from scratch before it all worked, to make sure the tables got created again in the right order, but if you really needed to, you could probably pick around that. This worked fine. Thanks! @philtweir This is such a particular case that I'm inclined to just use your minimal patch for now. (but perhaps read it from an env var to make it customizable in case someone wants to use another schema name) To be consistent and do it "properly", if we wanted to made the schema customizable via a documented config option we would have to make sure that [every time](https://gist.github.com/amercader/47f45481eef5f2e617281883885038fc) a `MetaData` instance is created the schema config option is used. For that we would probably need to use our own wrapper around `MetaData` that just accesses this config option once. But as I said, the first approach should be enough if you don't want to follow that route. Yep, that was the issue I was finding going down that path - particularly directly executed SQL statements, which would need the schema injected into the SQL, or a default schema set, with syntax that would need to switch for a sqlite test database. If you're happy, will go with that more targeted approach. Having the same trouble on master (5ee0e074c6bfe7a288a8f35f2e1ca5f1af7ce59d) even after adding the schema fix to `ckan/migration/versions/001_add_existing_tables.py` that others mentioned above. Docker on Windows 10. ``` $ docker-compose logs -f ckan Attaching to ckan ckan | Traceback (most recent call last): ckan | File "/usr/local/bin/ckan-paster", line 11, in <module> ckan | sys.exit(run()) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/paste/script/command.py", line 102, in run ckan | invoke(command, command_name, options, args[1:]) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/paste/script/command.py", line 141, in invoke ckan | exit_code = runner.run(args) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/paste/script/command.py", line 236, in run ckan | result = self.command() ckan | File "/usr/lib/ckan/venv/src/ckan/ckan/lib/cli.py", line 356, in command ckan | model.repo.init_db() ckan | File "/usr/lib/ckan/venv/src/ckan/ckan/model/__init__.py", line 187, in init_db ckan | self.upgrade_db() ckan | File "/usr/lib/ckan/venv/src/ckan/ckan/model/__init__.py", line 284, in upgrade_db ckan | mig.upgrade(self.metadata.bind, self.migrate_repository, version=version) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/migrate/versioning/api.py", line 186, in upgrade ckan | return _migrate(url, repository, version, upgrade=True, err=err, **opts) ckan | File "<decorator-gen-16>", line 2, in _migrate ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/migrate/versioning/util/__init__.py", line 160, in with_eng ine ckan | return f(*a, **kw) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/migrate/versioning/api.py", line 366, in _migrate ckan | schema.runchange(ver, change, changeset.step) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/migrate/versioning/schema.py", line 93, in runchange ckan | change.run(self.engine, step) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/migrate/versioning/script/py.py", line 148, in run ckan | script_func(engine) ckan | File "/usr/lib/ckan/venv/src/ckan/ckan/migration/versions/001_add_existing_tables.py", line 105, in upgrade ckan | meta.create_all() ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/sql/schema.py", line 3934, in create_all ckan | tables=tables) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1929, in _run_visitor ckan | conn._run_visitor(visitorcallable, element, **kwargs) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1538, in _run_visitor ckan | **kwargs).traverse_single(element) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/sql/visitors.py", line 121, in traverse_single ckan | return meth(obj, **kw) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/sql/ddl.py", line 733, in visit_metadata ckan | _is_metadata_operation=True) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/sql/visitors.py", line 121, in traverse_single ckan | return meth(obj, **kw) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/sql/ddl.py", line 767, in visit_table ckan | include_foreign_key_constraints=include_foreign_key_constraints ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 945, in execute ckan | return meth(self, multiparams, params) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/sql/ddl.py", line 68, in _execute_on_connection ckan | return connection._execute_ddl(self, multiparams, params) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1002, in _execute_ddl ckan | compiled ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1189, in _execute_context ckan | context) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1402, in _handle_dbapi_exc eption ckan | exc_info ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 203, in raise_from_cause ckan | reraise(type(exception), exception, tb=exc_tb, cause=cause) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context ckan | context) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 470, in do_execute ckan | cursor.execute(statement, parameters) ckan | sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) column "id" referenced in foreign key constraint does not e xist ckan | [SQL: '\nCREATE TABLE package (\n\tid SERIAL NOT NULL, \n\tname VARCHAR(100) NOT NULL, \n\ttitle TEXT, \n\tversion VARC HAR(100), \n\turl TEXT, \n\tdownload_url TEXT, \n\tnotes TEXT, \n\tlicense_id INTEGER, \n\tstate_id INTEGER, \n\trevision_id INTEGER, \n \tPRIMARY KEY (id), \n\tUNIQUE (name), \n\tFOREIGN KEY(license_id) REFERENCES license (id), \n\tFOREIGN KEY(state_id) REFERENCES state ( id), \n\tFOREIGN KEY(revision_id) REFERENCES revision (id)\n)\n\n'] ckan exited with code 1 ``` @carlsonp have you pruned your volumes and rebuild your instance? Else the source code won't update properly @gerbyzation Thanks for reply. I believe so, I ran these which I think clears everything out and starts from scratch. https://gist.github.com/JeffBelback/5687bb02f3618965ca8f I then rebuilt: `docker-compose up -d --build` Same behaviour here. Commit 5ee0e074c (HEAD -> master, origin/master, origin/HEAD), removed docker_<image-name> images, all things pruned ``` git pull origin master docker container rm ckan docker container rm solr docker container rm redis docker container rm datapusher docker container rm db docker image rm docker_ckan docker image rm docker_db docker image rm docker_solr docker image prune docker volumes prune ``` docker-compose up --build ``` ckan | context) ckan | File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 470, in do_execute ckan | cursor.execute(statement, parameters) ckan | sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) column "id" referenced in foreign key constraint does not exist ckan | [SQL: '\nCREATE TABLE package (\n\tid SERIAL NOT NULL, \n\tname VARCHAR(100) NOT NULL, \n\ttitle TEXT, \n\tversion VARCHAR(100), \n\turl TEXT, \n\tdownload_url TEXT, \n\tnotes TEXT, \n\tlicense_id INTEGER, \n\tstate_id INTEGER, \n\trevision_id INTEGER, \n\tPRIMARY KEY (id), \n\tUNIQUE (name), \n\tFOREIGN KEY(license_id) REFERENCES license (id), \n\tFOREIGN KEY(state_id) REFERENCES state (id), \n\tFOREIGN KEY(revision_id) REFERENCES revision (id)\n)\n\n'] ckan exited with code 1 ``` @carlsonp @giafar a slightly easier way to do this is to run the following from the `contrib/docker` directory ``` $ docker-compose down $ docker volume prune ``` This will shut down and remove the containers run through compose and then prune all unattached volumes. After this you can (re)build if necessary and use `docker-compose up` again. I'm afraid I can't be of further help at the moment as my internet is extremely poor at the moment and I am unable to rebuild. I might be being daft, but I can't see any autolink/notification here to the PR itself, so just for reference: https://github.com/ckan/ckan/pull/3965 In #4016 I've done a PR for the simpler version @ad-m proposed as an alternative to PR #3965. I think that we shouldn't go to lengths to make the namespace configurable - no-one has asked for that. Let's just fix the specific clash with this one-liner, and backport it to the last release, so that the docker install works again for people. What do you think @amercader ? I'm certainly fine with that (as #3965 author) - the configurability came from suggestion in https://github.com/ckan/ckan/issues/3929#issuecomment-349459395 , not as an additional option, but rather than hard-coding the Postgres setting into each migration, as I didn't think that would be mergeable (as standard as it is). However, at present, docker-compose is still broken, so anything that gets it fixed in master would be helpful for me too :) Are you saying there's a half-way house? If the schema/namespace needs to be configurable, then don't we need your full PR plus also the MetaData @amercader spotted, plus the same for any extensions used? I just don't see anyone ever saying they need that configurability. It might be more proper, but it's a lot of addition. So I'm simply suggesting we are simply explicit about the schema/namespace, for this one case where sqlalchemy needs bringing into line, to fix the issue at hand. What you're suggesting is more about making the schema configurable across the whole application. That's broader, beyond this issue. I spent some time taking a look but, as mentioned there, it would involve explicitly a lot more modification than would be worthwhile. As it stands, CKAN will install to and read from whatever is set as the default schema (public or otherwise, set in postgresql.conf) _except_, due to the bug above, when a relation name exists in another schema. Naming the default schema explicitly then stops that. My understanding of @amercader's comment above is that allowing that to be settable via env beats hard-coding `public`. I've done that in each migration (as a two-liner per migration) for consistency, so that if mdillon/postgis changes (or you have anything in PG alongside CKAN) this doesn't randomly break again - there's nothing specific about the "state" table, other than it's a popular name. Either way - I'm not disagreeing - that's not necessarily better, if it increases complexity. As far as I can see there are three key differences: - I have set the schema consistently in every migration, rather than one, - the schema name can be overridden by env, - but, thanks to CkanMetaData, that happens solely in one place. However, that means all the migrations get touched in the PR, which is a lot of files for a single issue - #4016 may be better trade-off. Ok that's really good to know that my change could screw things if someone changed their default schema in postgresql.conf. On balance, for that little bit of safety, I'd be tempted to use your change then.
2018-02-15T15:38:13
ckan/ckan
4,027
ckan__ckan-4027
[ "4022" ]
eda0b4929b5bbd246ea19d10a81fa873b13560d4
diff --git a/ckan/controllers/api.py b/ckan/controllers/api.py --- a/ckan/controllers/api.py +++ b/ckan/controllers/api.py @@ -38,6 +38,7 @@ 'text': 'text/plain;charset=utf-8', 'html': 'text/html;charset=utf-8', 'json': 'application/json;charset=utf-8', + 'javascript': 'application/javascript;charset=utf-8', } @@ -99,6 +100,7 @@ def _finish(self, status_int, response_data=None, # escape callback to remove '<', '&', '>' chars callback = cgi.escape(request.params['callback']) response_msg = self._wrap_jsonp(callback, response_msg) + response.headers['Content-Type'] = CONTENT_TYPES['javascript'] return response_msg def _finish_ok(self, response_data=None, diff --git a/ckan/views/api.py b/ckan/views/api.py --- a/ckan/views/api.py +++ b/ckan/views/api.py @@ -23,6 +23,7 @@ u'text': u'text/plain;charset=utf-8', u'html': u'text/html;charset=utf-8', u'json': u'application/json;charset=utf-8', + u'javascript': u'application/javascript;charset=utf-8', } API_REST_DEFAULT_VERSION = 1 @@ -69,6 +70,7 @@ def _finish(status_int, response_data=None, # escape callback to remove '<', '&', '>' chars callback = cgi.escape(request.args[u'callback']) response_msg = _wrap_jsonp(callback, response_msg) + headers[u'Content-Type'] = CONTENT_TYPES[u'javascript'] return make_response((response_msg, status_int, headers))
diff --git a/ckan/tests/controllers/test_api.py b/ckan/tests/controllers/test_api.py --- a/ckan/tests/controllers/test_api.py +++ b/ckan/tests/controllers/test_api.py @@ -278,6 +278,19 @@ def test_jsonp_works_on_get_requests(self): eq_(sorted(res_dict['result']), sorted([dataset1['name'], dataset2['name']])) + def test_jsonp_returns_javascript_content_type(self): + url = url_for( + controller='api', + action='action', + logic_function='status_show', + ver='/3') + app = self._get_test_app() + res = app.get( + url=url, + params={'callback': 'my_callback'}, + ) + assert_in('application/javascript', res.headers.get('Content-Type')) + def test_jsonp_does_not_work_on_post_requests(self): dataset1 = factories.Dataset()
making a JSONP call to the CKAN API returns the wrong mime type ### CKAN Version if known (or site URL) 2.7 ### Please describe the expected behaviour When making an api call to the CKAN api, and using the callback parameter to generate jsonp instead of json, the content-type should be set to "application/javascript" ### Please describe the actual behaviour the content-type is set to application/json regardless of whether the callback parameter is used or not ### What steps can be taken to reproduce the issue? Step 1. Make a request to https://demo.ckan.org/api/3/action/package_search?q=spending&callback=myFunc Step 2. Inspect the response headers, and notice that the Content-Type header is set to application/json
2018-02-15T20:38:22
ckan/ckan
4,040
ckan__ckan-4040
[ "3949" ]
a53b7f334e3cc3035684e4ccbb06d683b2fbe58d
diff --git a/ckan/lib/search/index.py b/ckan/lib/search/index.py --- a/ckan/lib/search/index.py +++ b/ckan/lib/search/index.py @@ -314,12 +314,10 @@ def commit(self): log.exception(e) raise SearchIndexError(e) - def delete_package(self, pkg_dict): conn = make_connection() - query = "+%s:%s (+id:\"%s\" OR +name:\"%s\") +site_id:\"%s\"" % (TYPE_FIELD, PACKAGE_TYPE, - pkg_dict.get('id'), pkg_dict.get('id'), - config.get('ckan.site_id')) + query = "+%s:%s AND +(id:\"%s\" OR name:\"%s\") AND +site_id:\"%s\"" % \ + (TYPE_FIELD, PACKAGE_TYPE, pkg_dict.get('id'), pkg_dict.get('id'), config.get('ckan.site_id')) try: commit = asbool(config.get('ckan.search.solr_commit', 'true')) conn.delete(q=query, commit=commit)
diff --git a/ckan/tests/lib/search/test_index.py b/ckan/tests/lib/search/test_index.py --- a/ckan/tests/lib/search/test_index.py +++ b/ckan/tests/lib/search/test_index.py @@ -81,6 +81,28 @@ def test_clear_index(self): response = self.solr_client.search(q='name:monkey', fq=self.fq) assert_equal(len(response), 0) + def test_delete_package(self): + self.package_index.index_package(self.base_package_dict) + + pkg_dict = self.base_package_dict.copy() + pkg_dict.update({ + 'id': 'test-index-2', + 'name': 'monkey2' + }) + self.package_index.index_package(pkg_dict) + + response = self.solr_client.search(q='title:Monkey', fq=self.fq) + assert_equal(len(response), 2) + response_ids = sorted([x['id'] for x in response.docs]) + assert_equal(response_ids, ['test-index', 'test-index-2']) + + self.package_index.delete_package(pkg_dict) + + response = self.solr_client.search(q='title:Monkey', fq=self.fq) + assert_equal(len(response), 1) + response_ids = sorted([x['id'] for x in response.docs]) + assert_equal(response_ids, ['test-index']) + def test_index_illegal_xml_chars(self): pkg_dict = self.base_package_dict.copy()
Deleting one Dataset deletes all datasets of an org; Patch available Dear CKAN developers! ### CKAN Version if known (or site URL) 2.7.2, SOLR 6.6.2 and 7. SOLR in a one core mulitcore setup. OS Debian stretch. CKAN installed from source. SOLR installed from TGZ. ### Please describe the expected behaviour Deleting a single dataset should delete only this dataset. ### Please describe the actual behaviour Deleting a single dataset deletes all dataset of the organisation ### What steps can be taken to reproduce the issue? Mark a dataset and click delete. The data in the PG DB is not affected. In the PG DB only the desired datasets were deleted. But the complete data for the organization in SOLR vanishes. I traced this problem down to the query-string going out to solr. This query kills all the datasets in organization "inqbus" `2017-12-06 21:25:12.561 INFO (qtp128526626-13) [ x:ckan2] o.a.s.u.p.LogUpdateProcessorFactory [ckan2] webapp=/solr path=/update params={commit=true}{deleteByQuery=+entity_type:package (+id:"eddb8f26-dd90-45f4-8404-8690e5fc75a4" OR +name:"eddb8f26-dd90-45f4-8404-8690e5fc75a4") +site_id:"inqbus" (-1586071352148754432),commit=} 0 28` If I feed in the following Query as a select into the SOLR console it returns all the datasets for this organization. +entity_type:package (+id:"eddb8f26-dd90-45f4-8404-8690e5fc75a4" OR +name:"eddb8f26-dd90-45f4-8404-8690e5fc75a4") +site_id:"inqbus" Therefore it is correct that all datasets were deleted. I am surely no SOLR guru but the parenthesis may cause the trouble. I patched ckan/src/ckan/ckan/lib/search/index.py to be more explicit on the boolean nature of the query. ``` def delete_package(self, pkg_dict): conn = make_connection() # query = "+%s:%s (+id:\"%s\" OR +name:\"%s\") +site_id:\"%s\"" % (TYPE_FIELD, PACKAGE_TYPE, # pkg_dict.get('id'), pkg_dict.get('id'), # config.get('ckan.site_id')) query = "%s:%s AND (id:\"%s\" OR name:\"%s\") AND site_id:\"%s\"" % (TYPE_FIELD, PACKAGE_TYPE, pkg_dict.get('id'), pkg_dict.get('id'), config.get('ckan.site_id')) ``` Yielding the following delete query: `2017-12-06 21:28:06.769 INFO (qtp128526626-14) [ x:ckan2] o.a.s.u.p.LogUpdateProcessorFactory [ckan2] webapp=/solr path=/update params={commit=true}{deleteByQuery=entity_type:package AND (id:"4001437b-7d33-46c9-9653-939257fe418d" OR name:"4001437b-7d33-46c9-9653-939257fe418d") AND site_id:"inqbus" (-1586071534809645056),commit=} 0 38` This query deletes only the desired dataset. Being a beginner with CKAN maybe I got some things messed up in my installation causing this trouble. But I double checked with SOLR 6.6 and SOLR 7 and got the same result. I volunteer to make CKAN better. If you like to have a pull request let me know. Cheers, Volker
2018-02-24T01:53:09
ckan/ckan
4,052
ckan__ckan-4052
[ "4039" ]
6e8e5d1b0fa16e79062d6f589442f1559efd8c27
diff --git a/ckan/lib/munge.py b/ckan/lib/munge.py --- a/ckan/lib/munge.py +++ b/ckan/lib/munge.py @@ -158,8 +158,8 @@ def munge_filename(filename): # Clean up filename = filename.lower().strip() filename = substitute_ascii_equivalents(filename) - filename = re.sub(ur'[^a-zA-Z0-9_. -]', '', filename).replace(u' ', u'-') - filename = re.sub(ur'-+', u'-', filename) + filename = re.sub(u'[^a-zA-Z0-9_. -]', '', filename).replace(u' ', u'-') + filename = re.sub(u'-+', u'-', filename) # Enforce length constraints name, ext = os.path.splitext(filename)
diff --git a/ckan/tests/test_coding_standards.py b/ckan/tests/test_coding_standards.py --- a/ckan/tests/test_coding_standards.py +++ b/ckan/tests/test_coding_standards.py @@ -18,6 +18,7 @@ import sys from six import text_type +from six.moves import xrange FILESYSTEM_ENCODING = text_type( sys.getfilesystemencoding() or sys.getdefaultencoding() @@ -125,7 +126,7 @@ def test_source_files_specify_encoding(): Empty files and files that only contain comments are ignored. ''' - pattern = re.compile(ur'#.*?coding[:=][ \t]*utf-?8') + pattern = re.compile(u'#.*?coding[:=][ \\t]*utf-?8') decode_errors = [] no_specification = [] for abs_path, rel_path in walk_python_files():
ur'strings' are a Syntax Errors in Python 3 In Python 3, you can have __u'strings'__ and you can have __r'strings'__ but you can not have __ur'strings'__. * __python3 -c "print(ur'string')"__ # --> Syntax Error ur'strings' currently appear in three files... $ __python3 -m flake8 . --count --select=E901,E999 --show-source --statistics__ ``` ./ckan/tests/test_coding_standards.py:127:55: E999 SyntaxError: invalid syntax pattern = re.compile(ur'#.*?coding[:=][ \t]*utf-?8') ^ ./ckan/lib/munge.py:159:42: E999 SyntaxError: invalid syntax filename = re.sub(ur'[^a-zA-Z0-9_. -]', '', filename).replace(u' ', u'-') ^ ./doc/conf.py:341:49: E999 SyntaxError: invalid syntax ('contents', 'CKAN.tex', ur'CKAN documentation', ^ 3 E999 SyntaxError: invalid syntax ``` The last one is governed by: * http://www.sphinx-doc.org/en/stable/config.html#confval-latex_documents Based on the [example __conf.py__ file](http://www.sphinx-doc.org/en/stable/config.html#example-of-configuration-file), I believe that we should use u'strings' in this context. #4049
Related to https://github.com/ckan/ckan/issues/3309. Discussed in https://github.com/ckan/ckan/pull/4035#issuecomment-368993517 @torfsen @amercader What about converting __ur'string'__ --> __six.u(r'string')__? ``` python2 -c "print(ur'你好 Lüsai' == '你好 Lüsai')" # False python2 -c "print(ur'你好 Lüsai' == r'你好 Lüsai')" # False python2 -c "print(ur'你好 Lüsai' == u'你好 Lüsai')" # True python2 -c "import six ; print(ur'你好 Lüsai' == six.u('你好 Lüsai'))" # True python2 -c "import six ; print(ur'你好 Lüsai' == six.u(r'你好 Lüsai'))" # True # python2 -c "import six ; print(ur'你好 Lüsai' == six.u(u'你好 Lüsai'))" # TypeError python2 -c "print(type('你好 Lüsai'))" # <type 'str'> python2 -c "print(type(r'你好 Lüsai'))" # <type 'str'> python2 -c "print(type(ur'你好 Lüsai'))" # <type 'unicode'> python2 -c "import six ; print(type(six.u(r'你好 Lüsai')))" # <type 'unicode'> ``` In general, we don't have many `ur` strings in CKAN: ``` $ grep -rI "\<ur[\"']" --include "*.py" ckan/lib/munge.py: filename = re.sub(ur'[^a-zA-Z0-9_. -]', '', filename).replace(u' ', u'-') ckan/lib/munge.py: filename = re.sub(ur'-+', u'-', filename) ckan/tests/test_coding_standards.py: pattern = re.compile(ur'#.*?coding[:=][ \t]*utf-?8') ckan/tests/test_coding_standards.py: if (i > 1) and (line[i - 2:i].lower() == u'ur'): doc/conf.py: ('contents', 'CKAN.tex', ur'CKAN documentation', doc/conf.py: ur'CKAN contributors', 'manual'), ``` All of these are ASCII-only strings, so from an encoding point of view, nothing is lost when they are simply converted to `r` strings. Judging from my experiments, the return type of Python 2's regular expression functions depends on the type of the input string, but not on the type of the pattern string: ``` >>> re.match(r'\w*', 'aä').group() 'a' >>> re.match(r'\w*', u'aä').group() u'a' >>> re.match(ur'\w*', 'aä').group() 'a' >>> re.match(ur'\w*', u'aä').group() u'a' ``` Also, the type of the pattern string doesn't influence whether character classes like `\w` capture non-ASCII characters (as seen above, the `ä` is never matched, even when both the pattern and the input are `unicode`) -- that is decided by the presence of the `re.UNICODE` (or `re.U`) flag (in Python 2 at least). In conclusion, it should be OK to convert all the `ur` instances of the current code base to `r` strings. As mentioned before, we also should update [our Unicode handling documentation](https://github.com/ckan/ckan/blob/master/doc/contributing/unicode.rst) which currently says > In CKAN, every string literal must carry either a u or a b prefix. While the latter is redundant in Python 2, it makes the developer's intention explicit and eases a future migration to Python 3. > > This rule also holds for raw strings, which are created using an r prefix. Simply use ur instead: > > m = re.match(ur'A\s+Unicode\s+pattern')
2018-03-01T08:56:36
ckan/ckan
4,082
ckan__ckan-4082
[ "4081" ]
400f17458217424b130d90577edef763316a2c80
diff --git a/ckan/controllers/package.py b/ckan/controllers/package.py --- a/ckan/controllers/package.py +++ b/ckan/controllers/package.py @@ -311,6 +311,9 @@ def pager_url(q=None, page=None): c.query_error = True c.search_facets = {} c.page = h.Page(collection=[]) + except NotAuthorized: + abort(403, _('Not authorized to see this page')) + c.search_facets_limits = {} for facet in c.search_facets.keys(): try:
Exception in search page when not authorized If someone customized the `package_search` auth function to restrict access the frontend returns an uncaught exception as this case is not handled in the controller
2018-03-08T11:35:49
ckan/ckan
4,084
ckan__ckan-4084
[ "4083" ]
400f17458217424b130d90577edef763316a2c80
diff --git a/ckan/config/environment.py b/ckan/config/environment.py --- a/ckan/config/environment.py +++ b/ckan/config/environment.py @@ -143,7 +143,8 @@ def find_controller(self, controller): 'smtp.starttls': 'CKAN_SMTP_STARTTLS', 'smtp.user': 'CKAN_SMTP_USER', 'smtp.password': 'CKAN_SMTP_PASSWORD', - 'smtp.mail_from': 'CKAN_SMTP_MAIL_FROM' + 'smtp.mail_from': 'CKAN_SMTP_MAIL_FROM', + 'ckan.max_resource_size': 'CKAN_MAX_UPLOAD_SIZE_MB' } # End CONFIG_FROM_ENV_VARS
diff --git a/ckan/tests/config/test_environment.py b/ckan/tests/config/test_environment.py --- a/ckan/tests/config/test_environment.py +++ b/ckan/tests/config/test_environment.py @@ -31,7 +31,8 @@ class TestUpdateConfig(h.FunctionalTestBase): ('CKAN_SMTP_STARTTLS', 'True'), ('CKAN_SMTP_USER', 'my_user'), ('CKAN_SMTP_PASSWORD', 'password'), - ('CKAN_SMTP_MAIL_FROM', '[email protected]') + ('CKAN_SMTP_MAIL_FROM', '[email protected]'), + ('CKAN_MAX_UPLOAD_SIZE_MB', '50') ] def _setup_env_vars(self): @@ -71,6 +72,7 @@ def test_update_config_env_vars(self): nosetools.assert_equal(config['smtp.user'], 'my_user') nosetools.assert_equal(config['smtp.password'], 'password') nosetools.assert_equal(config['smtp.mail_from'], '[email protected]') + nosetools.assert_equal(config['ckan.max_resource_size'], '50') def test_update_config_db_url_precedence(self): '''CKAN_SQLALCHEMY_URL in the env takes precedence over CKAN_DB'''
Specify max resource size in an env variable ### CKAN Version if known (or site URL) 2.7.2 (applies to head of master as well) ### Please describe the expected behaviour When deploying CKAN through docker it is not ideal to have to edit the configuration file in order to set maximum resource upload size. This would be better done through environment variables. ### Please describe the actual behaviour Currently the ckan.max_upload_size config can only changed via editing the config .ini files. ### What steps can be taken to reproduce the issue? Running CKAN through Docker via Docker Compose.
2018-03-08T11:57:42
ckan/ckan
4,090
ckan__ckan-4090
[ "4089" ]
2b9ddced8e1eac15bab314cf6e43e9a8ea2f24a0
diff --git a/ckan/lib/search/common.py b/ckan/lib/search/common.py --- a/ckan/lib/search/common.py +++ b/ckan/lib/search/common.py @@ -6,6 +6,7 @@ import pysolr import simplejson from six import string_types +import urllib log = logging.getLogger(__name__) @@ -65,6 +66,16 @@ def is_available(): def make_connection(decode_dates=True): solr_url, solr_user, solr_password = SolrSettings.get() + + if solr_url and solr_user: + # Rebuild the URL with the username/password + protocol = re.search('http(?:s)?://', solr_url).group() + solr_url = re.sub(protocol, '', solr_url) + solr_url = "{}{}:{}@{}".format(protocol, + urllib.quote_plus(solr_user), + urllib.quote_plus(solr_password), + solr_url) + if decode_dates: decoder = simplejson.JSONDecoder(object_hook=solr_datetime_decoder) return pysolr.Solr(solr_url, decoder=decoder)
Solr user/password not honoured for basic authentication When using Solr with username/password basic authentication, a connection cannot be made to check if Solr is available, even when the `solr_user` and `solr_password` are set in `ckan.ini`. ### CKAN version Tested with 2.7.2. The culprit code looks unchanged in master. ### To reproduce 1. Create a Solr instance with basic authentication. 2. Add the following to `ckan.ini`: ``` solr_user=solr solr_password=my_password ``` 3. Restart CKAN ### Expected behaviour Everything works ;) ### Actual behaviour CKAN outputs the following error on startup: ``` 2018-03-08 15:27:53,460 ERROR [pysolr] Solr responded with an error (HTTP 401): [Reason: Error 401 require authentication] 2018-03-08 15:27:53,460 ERROR [ckan.lib.search.common] Solr responded with an error (HTTP 401): [Reason: Error 401 require authentication] Traceback (most recent call last): File "/usr/lib/ckan/default/src/ckan/ckan/lib/search/common.py", line 57, in is_available conn.search(q="*:*", rows=1) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/pysolr.py", line 720, in search response = self._select(params, handler=search_handler) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/pysolr.py", line 418, in _select return self._send_request('get', path) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/pysolr.py", line 393, in _send_request raise SolrError(error_message % (resp.status_code, solr_message)) SolrError: Solr responded with an error (HTTP 401): [Reason: Error 401 require authentication] 2018-03-08 15:27:53,461 WARNI [ckan.lib.search] Problems were found while connecting to the SOLR server ``` Subsequent searches yield a server error: ``` 2018-03-08 15:35:24,487 ERROR [pysolr] Solr responded with an error (HTTP 401): [Reason: Error 401 require authentication] 2018-03-08 15:35:24,487 ERROR [ckan.controllers.package] Dataset search error: ('SOLR returned an error running query: {\'sort\': \'score desc, metadata_modified desc\', \'fq\': [u\'+dataset_type:dataset\', u\'+site_id:"default"\', \'+state:active\'], \'facet.mincount\': 1, \'rows\': 21, \'facet.field\': [u\'organization\', u\'groups\', u\'tags\', u\'res_format\', u\'license_id\'], \'facet.limit\': \'50\', \'mm\': \'2<-1 5<80%\', \'facet\': \'true\', \'q\': u\'test\', \'start\': 0, \'wt\': \'json\', \'qf\': \'name^4 title^4 tags^2 groups^2 text\', \'tie\': \'0.1\', \'fl\': \'id validated_data_dict\', \'defType\': \'dismax\'} Error: SolrError(u\'Solr responded with an error (HTTP 401): [Reason: Error 401 require authentication]\',)',) 2018-03-08 15:35:24,492 ERROR [pysolr] Solr responded with an error (HTTP 401): [Reason: Error 401 require authentication] Error - <class 'ckan.lib.search.common.SearchError'>: SOLR returned an error running query: {'fq': [u'+site_id:"default"', '+state:active'], 'facet.mincount': 1, 'rows': 2, 'facet.field': ['groups', 'owner_org'], 'facet': 'true', 'q': '+capacity:public', 'facet.limit': -1, 'wt': 'json', 'fl': 'groups'} Error: SolrError(u'Solr responded with an error (HTTP 401): [Reason: Error 401 require authentication]',) URL: http://docker.for.mac.localhost:5000/dataset?q=test File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/weberror/errormiddleware.py', line 171 in __call__ app_iter = self.application(environ, sr_checker) File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/dec.py', line 147 in __call__ resp = self.call_func(req, *args, **self.kwargs) File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/dec.py', line 208 in call_func return self.func(req, *args, **kwargs) File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/fanstatic/publisher.py', line 234 in __call__ return request.get_response(self.app) File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/request.py', line 1053 in get_response application, catch_exc_info=False) File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/request.py', line 1022 in call_application app_iter = application(self.environ, start_response) File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/dec.py', line 147 in __call__ resp = self.call_func(req, *args, **self.kwargs) File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/dec.py', line 208 in call_func return self.func(req, *args, **kwargs) File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/fanstatic/injector.py', line 54 in __call__ response = request.get_response(self.app) File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/request.py', line 1053 in get_response application, catch_exc_info=False) File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/request.py', line 1022 in call_application app_iter = application(self.environ, start_response) File '/usr/lib/ckan/default/src/ckan/ckan/config/middleware/pylons_app.py', line 250 in inner result = application(environ, start_response) File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/middleware.py', line 73 in __call__ return self.app(environ, start_response) File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/middleware.py', line 156 in __call__ return self.wrap_app(environ, session_start_response) File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/routes/middleware.py', line 131 in __call__ response = self.app(environ, start_response) File '/usr/lib/ckan/default/src/ckan/ckan/config/middleware/common_middleware.py', line 80 in __call__ return self.app(environ, start_response) File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/pylons/wsgiapp.py', line 125 in __call__ response = self.dispatch(controller, environ, start_response) File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/pylons/wsgiapp.py', line 324 in dispatch return controller(environ, start_response) File '/usr/lib/ckan/default/src/ckan/ckan/lib/base.py', line 212 in __call__ res = WSGIController.__call__(self, environ, start_response) File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/pylons/controllers/core.py', line 221 in __call__ response = self._dispatch_call() File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/pylons/controllers/core.py', line 172 in _dispatch_call response = self._inspect_call(func) File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/pylons/controllers/core.py', line 107 in _inspect_call result = self._perform_call(func, args) File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/pylons/controllers/core.py', line 60 in _perform_call return func(**args) File '/usr/lib/ckan/default/src/ckan/ckan/controllers/package.py', line 310 in search package_type=package_type) File '/usr/lib/ckan/default/src/ckan/ckan/controllers/package.py', line 72 in _setup_template_variables setup_template_variables(context, data_dict) File '/usr/lib/ckan/default/src/ckan/ckan/lib/plugins.py', line 286 in setup_template_variables c.groups_authz = authz_fn(context, data_dict) File '/usr/lib/ckan/default/src/ckan/ckan/logic/__init__.py', line 457 in wrapped result = _action(context, data_dict, **kw) File '/usr/lib/ckan/default/src/ckan/ckan/logic/action/get.py', line 592 in group_list_authz group_list = model_dictize.group_list_dictize(groups, context) File '/usr/lib/ckan/default/src/ckan/ckan/lib/dictization/model_dictize.py', line 51 in group_list_dictize group_dictize_context['dataset_counts'] = get_group_dataset_counts() File '/usr/lib/ckan/default/src/ckan/ckan/lib/dictization/model_dictize.py', line 337 in get_group_dataset_counts query.run(q) File '/usr/lib/ckan/default/src/ckan/ckan/lib/search/query.py', line 372 in run (query, e)) SearchError: SOLR returned an error running query: {'fq': [u'+site_id:"default"', '+state:active'], 'facet.mincount': 1, 'rows': 2, 'facet.field': ['groups', 'owner_org'], 'facet': 'true', 'q': '+capacity:public', 'facet.limit': -1, 'wt': 'json', 'fl': 'groups'} Error: SolrError(u'Solr responded with an error (HTTP 401): [Reason: Error 401 require authentication]',) ``` Both of these errors appear to be caused by `make_connection()` in [lib/search/common.py](https://github.com/ckan/ckan/blob/master/ckan/lib/search/common.py#L66), where the `solr_user` and `solr_password` settings are not honoured when the connection is established. ### Attempted workaround Because I love a dirty hack, I tried dropping the username & password into the solr_url (e.g. https://user:pass@solr:8983/solr/ckan). This yielded a much more obscure error, because `urllib2` appears not to handle user/pass in the URL: ``` Traceback (most recent call last): File "/usr/local/bin/ckan-paster", line 11, in <module> sys.exit(run()) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/script/command.py", line 102, in run invoke(command, command_name, options, args[1:]) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/script/command.py", line 141, in invoke exit_code = runner.run(args) File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/paste/script/command.py", line 236, in run result = self.command() File "/usr/lib/ckan/default/src/ckan/ckan/lib/cli.py", line 333, in command self._load_config(cmd!='upgrade') File "/usr/lib/ckan/default/src/ckan/ckan/lib/cli.py", line 306, in _load_config self.site_user = load_config(self.options.config, load_site_user) File "/usr/lib/ckan/default/src/ckan/ckan/lib/cli.py", line 221, in load_config load_environment(conf.global_conf, conf.local_conf) File "/usr/lib/ckan/default/src/ckan/ckan/config/environment.py", line 99, in load_environment p.load_all() File "/usr/lib/ckan/default/src/ckan/ckan/plugins/core.py", line 129, in load_all unload_all() File "/usr/lib/ckan/default/src/ckan/ckan/plugins/core.py", line 182, in unload_all unload(*reversed(_PLUGINS)) File "/usr/lib/ckan/default/src/ckan/ckan/plugins/core.py", line 210, in unload plugins_update() File "/usr/lib/ckan/default/src/ckan/ckan/plugins/core.py", line 121, in plugins_update environment.update_config() File "/usr/lib/ckan/default/src/ckan/ckan/config/environment.py", line 207, in update_config search.check_solr_schema_version() File "/usr/lib/ckan/default/src/ckan/ckan/lib/search/__init__.py", line 291, in check_solr_schema_version res = urllib2.urlopen(req) File "/usr/lib/python2.7/urllib2.py", line 154, in urlopen return opener.open(url, data, timeout) File "/usr/lib/python2.7/urllib2.py", line 431, in open response = self._open(req, data) File "/usr/lib/python2.7/urllib2.py", line 449, in _open '_open', req) File "/usr/lib/python2.7/urllib2.py", line 409, in _call_chain result = func(*args) File "/usr/lib/python2.7/urllib2.py", line 1227, in http_open return self.do_open(httplib.HTTPConnection, req) File "/usr/lib/python2.7/urllib2.py", line 1197, in do_open raise URLError(err) urllib2.URLError: <urlopen error [Errno -2] Name or service not known> ``` ### Proposed solution Updating `make_connection` to create the connection with the username/password resolves this issue.
2018-03-08T16:10:03
ckan/ckan
4,092
ckan__ckan-4092
[ "4091" ]
2b9ddced8e1eac15bab314cf6e43e9a8ea2f24a0
diff --git a/ckan/config/environment.py b/ckan/config/environment.py --- a/ckan/config/environment.py +++ b/ckan/config/environment.py @@ -135,6 +135,8 @@ def find_controller(self, controller): 'ckan.datastore.read_url': 'CKAN_DATASTORE_READ_URL', 'ckan.redis.url': 'CKAN_REDIS_URL', 'solr_url': 'CKAN_SOLR_URL', + 'solr_user': 'CKAN_SOLR_USER', + 'solr_password': 'CKAN_SOLR_PASSWORD', 'ckan.site_id': 'CKAN_SITE_ID', 'ckan.site_url': 'CKAN_SITE_URL', 'ckan.storage_path': 'CKAN_STORAGE_PATH',
Solr credential ENV vars not passed alongside CKAN_SOLR_URL ### CKAN Version if known (or site URL) 2.7.2 ### Please describe the expected behaviour Setting the following environment variables enables basic authentication for a Solr instance: ``` CKAN_SOLR_URL CKAN_SOLR_USER CKAN_SOLR_PASSWORD ``` ### Please describe the actual behaviour `CKAN_SOLR_URL` is honoured, but `CKAN_SOLR_USER` and `CKAN_SOLR_PASSWORD` are ignored and must be set in `ckan.ini`. ### What steps can be taken to reproduce the issue? 1. Set the following environment variables: ``` CKAN_SOLR_USER=my_missing_user CKAN_SOLR_PASSWORD=my_password ``` 2. Restart CKAN 3. Observe that nothing has changed Alternatively, create a Solr instance with Basic authentication, set the correct credentials as environment variables, then restart CKAN and watch the Solr connection fail.
2018-03-08T16:29:31
ckan/ckan
4,100
ckan__ckan-4100
[ "4094" ]
24c092c2fe60c7b07657fde5ccbb7f2735de7488
diff --git a/ckan/lib/dictization/model_save.py b/ckan/lib/dictization/model_save.py --- a/ckan/lib/dictization/model_save.py +++ b/ckan/lib/dictization/model_save.py @@ -133,19 +133,6 @@ def package_extras_save(extra_dicts, obj, context): state = 'deleted' extra.state = state -def group_extras_save(extras_dicts, context): - - model = context["model"] - session = context["session"] - - result_dict = {} - for extra_dict in extras_dicts: - if extra_dict.get("deleted"): - continue - result_dict[extra_dict["key"]] = extra_dict["value"] - - return result_dict - def package_tag_list_save(tag_dicts, package, context): allow_partial_update = context.get("allow_partial_update", False) if tag_dicts is None and allow_partial_update: @@ -412,14 +399,17 @@ def group_dict_save(group_dict, context, prevent_packages_update=False): 'Groups: %r Tags: %r', pkgs_edited, group_users_changed, group_groups_changed, group_tags_changed) - extras = group_extras_save(group_dict.get("extras", {}), context) - if extras or not allow_partial_update: - old_extras = set(group.extras.keys()) - new_extras = set(extras.keys()) - for key in old_extras - new_extras: + extras = group_dict.get("extras", []) + new_extras = {i['key'] for i in extras} + if extras: + old_extras = group.extras + for key in set(old_extras) - new_extras: del group.extras[key] - for key in new_extras: - group.extras[key] = extras[key] + for x in extras: + if 'deleted' in x and x['key'] in old_extras: + del group.extras[x['key']] + continue + group.extras[x['key']] = x['value'] # We will get a list of packages that we have either added or # removed from the group, and trigger a re-index.
Deleting first Group and Organization custom field is not possible ### CKAN Version if known (or site URL) 2.6+ - https://demo.ckan.org/organization/edit/20171207_mk - https://demo.ckan.org/group/edit/16848646846 - https://beta.ckan.org/organization/edit/avg-data - https://beta.ckan.org/group/edit/anotheraillysgroup ### Please describe the expected behaviour Each **Group or Organization custom field** marked for deletion should be deleted once the Update button is clicked. The deletion button should be displayed as a **red button with an icon**. ### Please describe the actual behaviour Whey you try to delete the first Group or Organization custom field, it only gets deleted when there are *at least two custom fields set*. When you try to delete the first custom field, when it's the only one in the group with paired values added, it does not get deleted once the Update button is clicked. Also the **delete icon is not rendered** in < 2.8 and it's displayed as a simple checkbox. ### What steps can be taken to reproduce the issue? Navigate to any of the links above and mark the first custom field for deletion, then click Update. The field will not be deleted. Then add values to at least two custom fields, Update and mark the first one for deletion. When you click on Update again, it will be deleted. Also, note that the delete icon is not rendered and only a simple checkbox is shown for marking. The custom fields functionality is fully working for datasets, so please check the Manage dataset page for reference.
2018-03-09T19:48:17
ckan/ckan
4,102
ckan__ckan-4102
[ "4061" ]
c5c92504e594752d8b2f047614e0f943f60db54c
diff --git a/ckan/lib/app_globals.py b/ckan/lib/app_globals.py --- a/ckan/lib/app_globals.py +++ b/ckan/lib/app_globals.py @@ -42,7 +42,6 @@ # has been setup in load_environment(): 'ckan.site_id': {}, 'ckan.recaptcha.publickey': {'name': 'recaptcha_publickey'}, - 'ckan.recaptcha.version': {'name': 'recaptcha_version', 'default': '1'}, 'ckan.template_title_deliminater': {'default': '-'}, 'ckan.template_head_end': {}, 'ckan.template_footer_end': {}, diff --git a/ckan/lib/captcha.py b/ckan/lib/captcha.py --- a/ckan/lib/captcha.py +++ b/ckan/lib/captcha.py @@ -13,48 +13,29 @@ def check_recaptcha(request): if not recaptcha_private_key: # Recaptcha not enabled return - + client_ip_address = request.environ.get('REMOTE_ADDR', 'Unknown IP Address') - - recaptcha_version = config.get('ckan.recaptcha.version', '1') - if recaptcha_version is '1': - recaptcha_response_field = request.params.get('recaptcha_response_field', '') - recaptcha_server_name = 'http://api-verify.recaptcha.net/verify' - recaptcha_challenge_field = request.params.get('recaptcha_challenge_field') - - # recaptcha_response_field will be unicode if there are foreign chars in - # the user input. So we need to encode it as utf8 before urlencoding or - # we get an exception (#1431). - params = urllib.urlencode(dict(privatekey=recaptcha_private_key, - remoteip=client_ip_address, - challenge=recaptcha_challenge_field, - response=recaptcha_response_field.encode('utf8'))) - f = urllib2.urlopen(recaptcha_server_name, params) - data = f.read() - f.close() - - if not data.lower().startswith('true'): - raise CaptchaError() - elif recaptcha_version is '2': - recaptcha_response_field = request.params.get('g-recaptcha-response', '') - recaptcha_server_name = 'https://www.google.com/recaptcha/api/siteverify' - - # recaptcha_response_field will be unicode if there are foreign chars in - # the user input. So we need to encode it as utf8 before urlencoding or - # we get an exception (#1431). - params = urllib.urlencode(dict(secret=recaptcha_private_key, - remoteip=client_ip_address, - response=recaptcha_response_field.encode('utf8'))) - f = urllib2.urlopen(recaptcha_server_name, params) - data = json.load(f) - f.close() - - try: - if not data['success']: - raise CaptchaError() - except IndexError: - # Something weird with recaptcha response + + # reCAPTCHA v2 + recaptcha_response_field = request.params.get('g-recaptcha-response', '') + recaptcha_server_name = 'https://www.google.com/recaptcha/api/siteverify' + + # recaptcha_response_field will be unicode if there are foreign chars in + # the user input. So we need to encode it as utf8 before urlencoding or + # we get an exception (#1431). + params = urllib.urlencode(dict(secret=recaptcha_private_key, + remoteip=client_ip_address, + response=recaptcha_response_field.encode('utf8'))) + f = urllib2.urlopen(recaptcha_server_name, params) + data = json.load(f) + f.close() + + try: + if not data['success']: raise CaptchaError() + except IndexError: + # Something weird with recaptcha response + raise CaptchaError() class CaptchaError(ValueError): - pass \ No newline at end of file + pass
recaptcha v1 will stop working 2018-3-31 ### CKAN Version if known (or site URL) All since 2.0ish ### The problem Users will not be able to register, due to the re-captcha being switched off by Google on 2018-3-31. Google's deprecation info: https://developers.google.com/recaptcha/docs/versions#v1 This affects those sites that: * have setup recaptcha (i.e. registered with Google and [added their keys to the CKAN config](http://docs.ckan.org/en/latest/maintaining/configuration.html?highlight=captcha#ckan-recaptcha-publickey)). This is not part of the default CKAN install. Most installs only use the 'user' functionality for admins, so the impact should be limited. * AND they use v1 of recaptcha. This is the default in the CKAN config, but Google deprecated v1 May 2016 and prevented new sites using it (I imagine it was the same time), so the issue only affects sites set-up before then. ### How to check if you have this problem Show the relevant bits of your CKAN config: ``` grep recaptcha /etc/ckan/default/production.ini ``` IF `ckan.recaptcha.publickey` has a value (i.e. not blank or unset) AND (`ckan.recaptcha.version = 1` OR `ckan.recaptcha.version` is blank or unset) THEN you need to upgrade to recaptcha 2 before 2018-03-31. ### Action I think we should change the default to v2 and warn the community.
@davidread sounds good, do you want a submit a PR chaging the default? This we can backport. And then we can remove support completely for v1 in a separate PR.
2018-03-12T10:55:29
ckan/ckan
4,158
ckan__ckan-4158
[ "4150" ]
db1cd298ca6d695c7941cb5f2cdc7c869d28d27e
diff --git a/ckanext/datastore/controller.py b/ckanext/datastore/controller.py --- a/ckanext/datastore/controller.py +++ b/ckanext/datastore/controller.py @@ -137,6 +137,7 @@ def result_page(offs, lim): PAGINATE_BY if limit is None else min(PAGINATE_BY, lim), 'offset': offs, + 'sort': '_id', 'records_format': records_format, 'include_total': 'false', # XXX: default() is broken })
Datastore dump results are not the same as data in database ### CKAN Version if known (or site URL) 2.7.2 ### Please describe the expected behaviour Downloaded dataset is not consistent with the actual data! ### Please describe the actual behaviour We've upserted data using datastore api. The data is shown correctly in data explorer, Table view, API call or even querying postgres, But the data in downloaded csv file is different! Total number of records are the same but in csv we have random number of duplicates and missing data. ### What steps can be taken to reproduce the issue? Upsert data using API. Download the CSV file using URL. Filter and compare downloaded data and data shown in data explorer or table view.
Are you updating the data while dumping it by any chance? Dump is using row offsets which can change while data is being inserted. It's highly unlikely. update is done once a week. I can provide a link if you want to check. a link to the resource and examples of the duplicate+missing rows would help for sure. Link to resource: https://data.illinois.gov/dataset/725state_employee_pay_hired_after_112011/resource/f86e27e4-67e4-4d50-9c52-a56c1159ace0 If you download the resource and filter the data using for example Agency = Human Rights you can see we have 145 records in CSV and we have 106 records in Data Explorer. This does seem to be a pagination issue. We're requesting 25000 records at a time from the database and e.g. record `7301,...,2013,CORRECTIONS,SOUTHWESTERN IL..` appears at line 63899 and 88902 (25003 lines apart). We can force an ordering on `_id` here https://github.com/ckan/ckan/blob/master/ckanext/datastore/controller.py#L136 ```python def result_page(offs, lim): return get_action('datastore_search')(None, { 'resource_id': resource_id, 'limit': PAGINATE_BY if limit is None else min(PAGINATE_BY, lim), 'offset': offs, 'sort': '_id', # <---------------- add this line 'records_format': records_format, 'include_total': 'false', }) ``` and we should stop seeing duplicates in the dump output Thanks, I'll test it out and let you know. I closed it for now since I cannot test it right now Reopened because this one is serious. We need to fix & backport it even if you can't reproduce right now
2018-03-29T15:22:05
ckan/ckan
4,180
ckan__ckan-4180
[ "4179" ]
da9a01ad56ccb8d6f47237740f8cd24ab7da2854
diff --git a/ckan/model/__init__.py b/ckan/model/__init__.py --- a/ckan/model/__init__.py +++ b/ckan/model/__init__.py @@ -4,6 +4,7 @@ import logging import re from datetime import datetime +from time import sleep from six import text_type import vdm.sqlalchemy @@ -138,6 +139,7 @@ log = logging.getLogger(__name__) +DB_CONNECT_RETRIES = 10 # set up in init_model after metadata is bound version_table = None @@ -152,11 +154,18 @@ def init_model(engine): meta.metadata.bind = engine # sqlalchemy migrate version table import sqlalchemy.exc - try: - global version_table - version_table = Table('migrate_version', meta.metadata, autoload=True) - except sqlalchemy.exc.NoSuchTableError: - pass + for i in reversed(range(DB_CONNECT_RETRIES)): + try: + global version_table + version_table = Table('migrate_version', meta.metadata, autoload=True) + break + except sqlalchemy.exc.NoSuchTableError: + break + except sqlalchemy.exc.OperationalError as e: + if 'database system is starting up' in repr(e.orig) and i: + sleep(DB_CONNECT_RETRIES - i) + continue + raise class Repository(vdm.sqlalchemy.Repository):
database system is starting up error ### CKAN Version if known (or site URL) master ### Please describe the expected behaviour when forcibly stopping postgres it can take longer to restart than normal. The CKAN process should wait for database while it is repairing. ### Please describe the actual behaviour CKAN fails with a "database system is starting up" error message ### What steps can be taken to reproduce the issue? Not consistent, but use CKAN with docker and kill the postgres container then restart both postgres and ckan images.
2018-04-09T19:12:45
ckan/ckan
4,190
ckan__ckan-4190
[ "4066" ]
5634fd1724824dd1785ab901095acb27baa3448f
diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py --- a/ckan/lib/helpers.py +++ b/ckan/lib/helpers.py @@ -305,6 +305,9 @@ def url_for(*args, **kw): _auto_flask_context.push() # First try to build the URL with the Flask router + # Temporary mapping for pylons to flask route names + if len(args): + args = (map_pylons_to_flask_route_name(args[0]),) my_url = _url_for_flask(*args, **kw) except FlaskRouteBuildError: @@ -873,6 +876,28 @@ def build_nav(menu_item, title, **kw): return _make_menu_item(menu_item, title, icon=None, **kw) +# Legacy route names +LEGACY_ROUTE_NAMES = { + 'home': 'home.index', + 'about': 'home.about', +} + + +def map_pylons_to_flask_route_name(menu_item): + '''returns flask routes for old fashioned route names''' + # Pylons to Flask legacy route names mappings + if config.get('ckan.legacy_route_mappings'): + if isinstance(config.get('ckan.legacy_route_mappings'), string_types): + LEGACY_ROUTE_NAMES.update(json.loads(config.get( + 'ckan.legacy_route_mappings'))) + + if menu_item in LEGACY_ROUTE_NAMES: + log.info('Route name "{}" is deprecated and will be removed.\ + Please update calls to use "{}" instead'.format( + menu_item, LEGACY_ROUTE_NAMES[menu_item])) + return LEGACY_ROUTE_NAMES.get(menu_item, menu_item) + + @core_helper def build_extra_admin_nav(): '''Build extra navigation items used in ``admin/base.html`` for values @@ -906,6 +931,7 @@ def _make_menu_item(menu_item, title, **kw): This function is called by wrapper functions. ''' + menu_item = map_pylons_to_flask_route_name(menu_item) _menu_items = config['routes.named_routes'] if menu_item not in _menu_items: raise Exception('menu item `%s` cannot be found' % menu_item)
diff --git a/ckan/tests/controllers/test_home.py b/ckan/tests/controllers/test_home.py --- a/ckan/tests/controllers/test_home.py +++ b/ckan/tests/controllers/test_home.py @@ -56,6 +56,16 @@ def test_email_address_no_nag(self): assert 'add your email address' not in response + @helpers.change_config('ckan.legacy_route_mappings', + '{"my_home_route": "home.index"}') + def test_map_pylons_to_flask_route(self): + app = self._get_test_app() + response = app.get(url_for('my_home_route')) + assert 'Welcome to CKAN' in response.body + + response = app.get(url_for('home')) + assert 'Welcome to CKAN' in response.body + class TestI18nURLs(helpers.FunctionalTestBase):
Removing pylons routes breaks extensions ### CKAN Version if known (or site URL) 2.8 ### Please describe the expected behaviour The old named routes (e.g. 'home' or 'about') should be kept to improve the backwards compatibility of CKAN core. For extensions that want to support a range of CKAN versions this is important as they otherwise have to define these routes themselves, implement version-specific code or break one version. ### Please describe the actual behaviour The routes were removed frim master and therefore e.g. code that build the main navigation is doomed to fail in extensions. E.g https://github.com/ckan/ckanext-showcase/blob/92c9b2b7d4cc07b68eeb77587a832cb3c7607daa/ckanext/showcase/templates/header.html ### What steps can be taken to reproduce the issue? Try to build a navigation to the homepage or the about page on both CKAN 2.7 and the latest master branch. I would propose to either keep the old named routes or provide a way the old name to the new route.
Named routes that followed the `controller_action` convention should be supported. For cases like `about`, `search` etc we can definitely provide an alias, mapping, etc @smotornyuk @tino097 what do you think it's the best approach? Is it just a matter of defining a new URL rule with a custom endpoint? or do we need an actual mapping in `h.url_for()`? as documentation states, when using blueprints, we should use blueprint name when defining the endpoint, so i think we should keep using 'home.about' and 'dataset.search' and see if we could provide an alias We discussed it last Tuesday, i just had no time to write comment:( Yep, most of `c_a` routes are supported, unless there are no naming changes(which is a case for package controller - now it separated into `dataset` and `resource` controllers). But we have quite a bin of one-word routes, like `home` and `about`. I suggest adding dictionary with mapping of route names, which will be checked at the beginning of `url_for`. This dict can be created even in helpers file and should contain old names of routes as keys and flask-styled names as values. And, sure, we need to raise either warning or log deprecation message, when we find out that this dict is successfully used. I would suggest adding also function, that allows appending new keys into this dict(it potentially will be mutable global variable, what I don't like, but it's the fix for one|two minor releases, so i can go with it) or even some config directive, that can fill gaps in mapping(if we missed something, or there are some problems in extension itself) We need this before 2.8 is released, as some of the breaking routes are already in it. @tino097 can work on this this week
2018-04-17T17:40:04
ckan/ckan
4,249
ckan__ckan-4249
[ "4247" ]
30ca7aae2f2aca6a19a2e6ed29148f8428e25c86
diff --git a/ckan/views/__init__.py b/ckan/views/__init__.py --- a/ckan/views/__init__.py +++ b/ckan/views/__init__.py @@ -98,8 +98,11 @@ def identify_user(): if authenticators: for item in authenticators: item.identify() - if g.user: - break + try: + if g.user: + break + except AttributeError: + continue # We haven't identified the user so try the default methods if not getattr(g, u'user', None):
'_Globals' has no attribute 'user' : exception when using an IAuthenticator on CKAN 2.8.0 I'm putting together a new deployment based on the new CKAN v2.8.0 release. I'm using ckanext-ldap as an authenticator, though it looks like this bug would apply to any authenticator plugin. This exact setup worked fine on CKAN v2.7.3. ### CKAN Version if known (or site URL) CKAN v 2.8.0 ckanext-ldap @ `ckan-upgrade-2.8.0a` ### Please describe the expected behaviour If the IAuthenticator plugin cannot authenticate the user, it does not set `g.user`, and CKAN should run the default authenticator. ### Please describe the actual behaviour If the IAuthenticator plugin cannot authenticate the user, it does not set `g.user`, and CKAN tries to lookup `g.user` and crashes with traceback: ``` Traceback (most recent call last): File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1610, in full_dispatch_request rv = self.preprocess_request() File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1831, in preprocess_request rv = func() File "/usr/lib/ckan/venv/src/ckan/ckan/config/middleware/flask_app.py", line 281, in ckan_before_request identify_user() File "/usr/lib/ckan/venv/src/ckan/ckan/views/__init__.py", line 101, in identify_user if g.user: File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/werkzeug/local.py", line 347, in __getattr__ return getattr(self._get_current_object(), name) File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/werkzeug/local.py", line 347, in __getattr__ return getattr(self._get_current_object(), name) File "/usr/lib/ckan/venv/src/ckan/ckan/config/middleware/flask_app.py", line 334, in __getattr__ return getattr(app_globals.app_globals, name) AttributeError: '_Globals' object has no attribute 'user' ``` ### What steps can be taken to reproduce the issue? * Install CKAN v2.8.0 as per documented instructions * Install a plugin that implements IAuthenticator (In this case I am using the ckanext-ldap plugin in the 2.8.0 branch), that may not be able to authenticate the user, so may not set `g.user`. * Run CKAN normally * Attempt to load any page. What is odd is that this section of code at `identify_user` in `ckan/views/__init__.py` has not changed between v2.7.3 and v2.8.0. And the way the authenticator plugin handles/sets `g.user` has not changed either. I'm guessing this is caused by a change in the way the _Globals object behaves when it cannot find an attribute.
2018-05-11T05:09:17
ckan/ckan
4,265
ckan__ckan-4265
[ "4262" ]
4e018d913370ca809ec723319d9e1ad69e271f19
diff --git a/ckan/views/admin.py b/ckan/views/admin.py --- a/ckan/views/admin.py +++ b/ckan/views/admin.py @@ -110,11 +110,14 @@ def get(self): def post(self): try: + req = request.form.copy() + req.update(request.files.to_dict()) data_dict = logic.clean_dict( dict_fns.unflatten( logic.tuplize_dict( logic.parse_params( - request.form, ignore_keys=CACHE_PARAMETERS)))) + req, ignore_keys=CACHE_PARAMETERS)))) + del data_dict['save'] data = logic.get_action(u'config_option_update')({ u'user': g.user
Upload logo is not working ### CKAN Version if known (or site URL) 2.8+ ### Please describe the expected behaviour When uploading logo from config page, we should see new logo on the portal ### Please describe the actual behaviour Logo is not uploaded ### What steps can be taken to reproduce the issue? Go to https://beta.ckan.org/ckan-admin/config Upload an image Update config
2018-05-23T15:22:40
ckan/ckan
4,274
ckan__ckan-4274
[ "4255" ]
dbd7460554a17c7e0f0e694960890224135a1f50
diff --git a/doc/conf.py b/doc/conf.py --- a/doc/conf.py +++ b/doc/conf.py @@ -183,10 +183,26 @@ def get_status_of_this_version(): return 'unsupported' +def get_current_release_tag(): + ''' Return the name of the tag for the current release + + e.g.: "ckan-2.7.4" + + ''' + release_tags_ = get_release_tags() + + current_tag = "ckan-{}".format(version) + + if release_tags_.__contains__(current_tag): + return current_tag + else: + return 'COULD_NOT_DETECT_TAG_VERSION' + + def get_latest_release_tag(): '''Return the name of the git tag for the latest stable release. - e.g.: "ckan-2.1.1" + e.g.: "ckan-2.7.4" This requires git to be installed. @@ -212,6 +228,19 @@ def get_latest_release_version(): return version +def get_current_release_version(): + '''Return the version number of the current release. + + e.g. "2.1.1" + + ''' + version = get_current_release_tag()[len('ckan-'):] + + # TODO: We could assert here that latest_version matches X.Y.Z. + + return version + + def get_latest_package_name(distro='trusty'): '''Return the filename of the Ubuntu package for the latest stable release. @@ -266,7 +295,8 @@ def write_substitutions_file(**kwargs): f.write('.. |{name}| replace:: {substitution}\n'.format( name=name, substitution=substitution)) - +current_release_tag = get_current_release_tag() +current_release_version = get_current_release_version() latest_release_tag_value = get_latest_release_tag() latest_release_version = get_latest_release_version() latest_minor_version = latest_release_version[:3] @@ -276,7 +306,7 @@ def write_substitutions_file(**kwargs): write_substitutions_file( latest_release_tag=latest_release_tag_value, - latest_release_version=get_latest_release_version(), + latest_release_version=latest_release_version, latest_package_name_precise=get_latest_package_name('precise'), latest_package_name_trusty=get_latest_package_name('trusty'), latest_package_name_xenial=get_latest_package_name('xenial'),
Installation instructions for 2.7.4 actually install 2.7.3 ### CKAN Version if known (or site URL) 2.7.4 ### Please describe the expected behaviour The installation instructions for CKAN version 2.7.4 mentions and installs CKAN version 2.7.4 ### Please describe the actual behaviour Following the 'Install CKAN from source' instructions the documentation still states that 2.7.3 is the latest stable version and the terminal command downloads CKAN 2.7.3 (http://docs.ckan.org/en/2.7/maintaining/installing/install-from-source.html#install-ckan-into-a-python-virtual-environment Step C). The chapter 'Installing CKAN from package' correctly reference the 2.7.4 release. ### What steps can be taken to reproduce the issue? Follow the installation instructions via http://docs.ckan.org/en/2.7/maintaining/installing/install-from-source.html#install-ckan-into-a-python-virtual-environment
Ups, thanks for flagging @WterBerg , we'll fix this asap Something changed and all versions of the installation instructions now point to the latest stable ( 2.8.0 ). Is this intentional? I would expect the instructions for CKAN 2.6.6 to install CKAN 2.6.6. No, @WterBerg this is not working as expected, there is a problem with the variables being used in the docs. As you say they should display the latest patch release for that minor version (ie 2.6.6). We need to fix this. @tino097 can you add this to your list? one of the variables set in `doc/conf.py` probably needs to be cahnged to use the branch that the docs are on rather than the latest one.
2018-06-05T20:19:09
ckan/ckan
4,285
ckan__ckan-4285
[ "4277" ]
23ca1d7b05b086abdfdbbca9011c6d38bdf6f2cd
diff --git a/ckan/lib/cli.py b/ckan/lib/cli.py --- a/ckan/lib/cli.py +++ b/ckan/lib/cli.py @@ -339,10 +339,6 @@ class ManageDb(CkanCommand): search index db upgrade [version no.] - Data migrate db version - returns current version of data schema - db dump FILE_PATH - dump to a pg_dump file [DEPRECATED] - db load FILE_PATH - load a pg_dump from a file [DEPRECATED] - db load-only FILE_PATH - load a pg_dump from a file but don\'t do - the schema upgrade or search indexing [DEPRECATED] db create-from-model - create database from the model (indexes not made) db migrate-filestore - migrate all uploaded data from the 2.1 filesore. ''' @@ -384,12 +380,6 @@ def command(self): model.repo.upgrade_db() elif cmd == 'version': self.version() - elif cmd == 'dump': - self.dump() - elif cmd == 'load': - self.load() - elif cmd == 'load-only': - self.load(only_load=True) elif cmd == 'create-from-model': model.repo.create_db() if self.verbose: @@ -399,79 +389,6 @@ def command(self): else: error('Command %s not recognized' % cmd) - def _get_db_config(self): - return parse_db_config() - - def _get_postgres_cmd(self, command): - self.db_details = self._get_db_config() - if self.db_details.get('db_type') not in ('postgres', 'postgresql'): - raise AssertionError('Expected postgres database - not %r' % self.db_details.get('db_type')) - pg_cmd = command - pg_cmd += ' -U %(db_user)s' % self.db_details - if self.db_details.get('db_pass') not in (None, ''): - pg_cmd = 'export PGPASSWORD=%(db_pass)s && ' % self.db_details + pg_cmd - if self.db_details.get('db_host') not in (None, ''): - pg_cmd += ' -h %(db_host)s' % self.db_details - if self.db_details.get('db_port') not in (None, ''): - pg_cmd += ' -p %(db_port)s' % self.db_details - return pg_cmd - - def _get_psql_cmd(self): - psql_cmd = self._get_postgres_cmd('psql') - psql_cmd += ' -d %(db_name)s' % self.db_details - return psql_cmd - - def _postgres_dump(self, filepath): - pg_dump_cmd = self._get_postgres_cmd('pg_dump') - pg_dump_cmd += ' %(db_name)s' % self.db_details - pg_dump_cmd += ' > %s' % filepath - self._run_cmd(pg_dump_cmd) - print('Dumped database to: %s' % filepath) - - def _postgres_load(self, filepath): - import ckan.model as model - assert not model.repo.are_tables_created(), "Tables already found. You need to 'db clean' before a load." - pg_cmd = self._get_psql_cmd() + ' -f %s' % filepath - self._run_cmd(pg_cmd) - print('Loaded CKAN database: %s' % filepath) - - def _run_cmd(self, command_line): - import subprocess - retcode = subprocess.call(command_line, shell=True) - if retcode != 0: - raise SystemError('Command exited with errorcode: %i' % retcode) - - def dump(self): - deprecation_warning(u"Use PostgreSQL's pg_dump instead.") - if len(self.args) < 2: - print('Need pg_dump filepath') - return - dump_path = self.args[1] - - psql_cmd = self._get_psql_cmd() + ' -f %s' - pg_cmd = self._postgres_dump(dump_path) - - def load(self, only_load=False): - deprecation_warning(u"Use PostgreSQL's pg_restore instead.") - if len(self.args) < 2: - print('Need pg_dump filepath') - return - dump_path = self.args[1] - - psql_cmd = self._get_psql_cmd() + ' -f %s' - pg_cmd = self._postgres_load(dump_path) - if not only_load: - print('Upgrading DB') - import ckan.model as model - model.repo.upgrade_db() - - print('Rebuilding search index') - import ckan.lib.search - ckan.lib.search.rebuild() - else: - print('Now remember you have to call \'db upgrade\' and then \'search-index rebuild\'.') - print('Done') - def migrate_filestore(self): from ckan.model import Session import requests @@ -2003,13 +1920,17 @@ def command(self): def less(self): ''' Compile less files ''' import subprocess - command = 'npm bin' - process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) + command = ('npm', 'bin') + process = subprocess.Popen( + command, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + universal_newlines=True) output = process.communicate() directory = output[0].strip() if not directory: raise error('Command "{}" returned nothing. Check that npm is ' - 'installed.'.format(command)) + 'installed.'.format(' '.join(command))) less_bin = os.path.join(directory, 'lessc') public = config.get(u'ckan.base_public_folder') @@ -2033,9 +1954,12 @@ def compile_less(self, root, less_bin, color): main_less = os.path.join(root, 'less', 'main.less') main_css = os.path.join(root, 'css', '%s.css' % color) - command = '%s %s %s' % (less_bin, main_less, main_css) - - process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) + command = (less_bin, main_less, main_css) + process = subprocess.Popen( + command, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + universal_newlines=True) output = process.communicate() print(output)
Remove shell=True from subprocess calls ### CKAN Version if known (or site URL) CKAN 2.7.3+ ### Please describe the expected behaviour Remove unneeded subprocesses with shell=True. Otherwise I would appreciate an explanation why shell=True must be set as a comment. ### Please describe the actual behaviour In a recent security audit/code review performed on one of our client installations the following findings are considered harmful due to potential Code-Injections. There are a couple occurrences where the argument `shell=True` is given. https://github.com/ckan/ckan/blob/3c7ad610cba7e9db8ea9a8467af516826773542d/ckan/lib/cli.py#L438-L442 https://github.com/ckan/ckan/blob/3c7ad610cba7e9db8ea9a8467af516826773542d/ckan/lib/cli.py#L2007 https://github.com/ckan/ckan/blob/3c7ad610cba7e9db8ea9a8467af516826773542d/ckan/lib/cli.py#L2038 The last one is literally legacy. https://github.com/ckan/ckan/blob/3c7ad610cba7e9db8ea9a8467af516826773542d/ckan/tests/legacy/test_versions.py#L11 ### What steps can be taken to reproduce the issue? See the above Code-Snippets.
2018-06-07T13:55:35
ckan/ckan
4,307
ckan__ckan-4307
[ "4305", "4305" ]
033282956d3743611e880a22db6c289059a41309
diff --git a/ckan/views/dashboard.py b/ckan/views/dashboard.py --- a/ckan/views/dashboard.py +++ b/ckan/views/dashboard.py @@ -18,6 +18,9 @@ @dashboard.before_request def before_request(): try: + if not g.userobj: + raise logic.NotAuthorized() + context = dict(model=model, user=g.user, auth_user_obj=g.userobj) logic.check_access(u'site_read', context) except logic.NotAuthorized:
diff --git a/ckan/tests/controllers/test_user.py b/ckan/tests/controllers/test_user.py --- a/ckan/tests/controllers/test_user.py +++ b/ckan/tests/controllers/test_user.py @@ -192,6 +192,15 @@ def test_non_root_user_logout_url_redirect(self): class TestUser(helpers.FunctionalTestBase): + def test_not_logged_in_dashboard(self): + app = self._get_test_app() + + for route in ['index', 'organizations', 'datasets', 'groups']: + app.get( + url=url_for(u'dashboard.{}'.format(route)), + status=403 + ) + def test_own_datasets_show_up_on_user_dashboard(self): user = factories.User() dataset_title = 'My very own dataset'
Internal server error when viewing /dashboard when logged out ### CKAN Version if known (or site URL) 2.8.0 ### Please describe the expected behaviour When attempting to visit /dashboard as a non-logged in user, the user should be sent to the login page. ### Please describe the actual behaviour An internal server error occurs. ``` File "/usr/lib/ckan/default/src/ckan/ckan/views/dashboard.py", line 99, in index u'id': g.userobj.id, AttributeError: 'NoneType' object has no attribute 'id' ``` ### What steps can be taken to reproduce the issue? Visit http://demo.ckan.org/dashboard when not logged in Internal server error when viewing /dashboard when logged out ### CKAN Version if known (or site URL) 2.8.0 ### Please describe the expected behaviour When attempting to visit /dashboard as a non-logged in user, the user should be sent to the login page. ### Please describe the actual behaviour An internal server error occurs. ``` File "/usr/lib/ckan/default/src/ckan/ckan/views/dashboard.py", line 99, in index u'id': g.userobj.id, AttributeError: 'NoneType' object has no attribute 'id' ``` ### What steps can be taken to reproduce the issue? Visit http://demo.ckan.org/dashboard when not logged in
2018-06-27T10:06:02
ckan/ckan
4,309
ckan__ckan-4309
[ "3879" ]
033282956d3743611e880a22db6c289059a41309
diff --git a/ckan/migration/versions/087_remove_old_authorization_tables.py b/ckan/migration/versions/087_remove_old_authorization_tables.py new file mode 100644 --- /dev/null +++ b/ckan/migration/versions/087_remove_old_authorization_tables.py @@ -0,0 +1,10 @@ +# encoding: utf-8 + + +def upgrade(migrate_engine): + migrate_engine.execute( + ''' + DROP TABLE IF EXISTS "authorization_group_user"; + DROP TABLE IF EXISTS "authorization_group"; + ''' + )
Remove authorization_group tables ### CKAN Version if known (or site URL) Newest. ### Please describe the expected behaviour Tables authorization_group, authorization_group_role, authorization_group_user should not exist. There are no migrations to delete them. ### Please describe the actual behaviour I've seen some work on cleaning authz: @rossjones working on it here https://github.com/ckan/ckan/commit/45c31815ea3282d185bde284788baf5da1b1749d, @tobes here https://github.com/ckan/ckan/commit/dc2ca3fe7185126cd455a7b96c7c72ca958411da, plus a PR https://github.com/ckan/ckan/pull/349. I don't see migrations to delete those tables. ### What steps can be taken to reproduce the issue?
Yes, these tables were used a long time ago. Feel free to submit a PR with a migration to get rid of them.
2018-06-27T10:51:15
ckan/ckan
4,317
ckan__ckan-4317
[ "4316" ]
d7efea1d0e2729b22dd8377d3fcc9177ae69853b
diff --git a/ckan/controllers/group.py b/ckan/controllers/group.py --- a/ckan/controllers/group.py +++ b/ckan/controllers/group.py @@ -225,6 +225,12 @@ def read(self, id, limit=20): except (NotFound, NotAuthorized): abort(404, _('Group not found')) + # if the user specified a group id, redirect to the group name + if data_dict['id'] == c.group_dict['id'] and \ + data_dict['id'] != c.group_dict['name']: + h.redirect_to(controller=group_type, action='read', + id=c.group_dict['name']) + self._read(id, limit, group_type) return render(self._read_template(c.group_dict['type']), extra_vars={'group_type': group_type}) @@ -860,6 +866,7 @@ def follow(self, id): group_dict = get_action('group_show')(context, data_dict) h.flash_success(_("You are now following {0}").format( group_dict['title'])) + id = group_dict['name'] except ValidationError as e: error_message = (e.message or e.error_summary or e.error_dict) @@ -880,6 +887,7 @@ def unfollow(self, id): group_dict = get_action('group_show')(context, data_dict) h.flash_success(_("You are no longer following {0}").format( group_dict['title'])) + id = group_dict['name'] except ValidationError as e: error_message = (e.message or e.error_summary or e.error_dict) diff --git a/ckan/views/dataset.py b/ckan/views/dataset.py --- a/ckan/views/dataset.py +++ b/ckan/views/dataset.py @@ -412,6 +412,12 @@ def read(package_type, id): g.pkg_dict = pkg_dict g.pkg = pkg + # if the user specified a package id, redirect to the package name + if data_dict['id'] == pkg_dict['id'] and \ + data_dict['id'] != pkg_dict['name']: + return h.redirect_to(u'dataset.read', + id=pkg_dict['name']) + # can the resources be previewed? for resource in pkg_dict[u'resources']: resource_views = get_action(u'resource_view_list')( @@ -828,6 +834,7 @@ def follow(package_type, id): try: get_action(u'follow_dataset')(context, data_dict) package_dict = get_action(u'package_show')(context, data_dict) + id = package_dict['name'] except ValidationError as e: error_message = (e.message or e.error_summary or e.error_dict) h.flash_error(error_message) @@ -854,6 +861,7 @@ def unfollow(package_type, id): try: get_action(u'unfollow_dataset')(context, data_dict) package_dict = get_action(u'package_show')(context, data_dict) + id = package_dict['name'] except ValidationError as e: error_message = (e.message or e.error_summary or e.error_dict) h.flash_error(error_message)
diff --git a/ckan/tests/controllers/test_group.py b/ckan/tests/controllers/test_group.py --- a/ckan/tests/controllers/test_group.py +++ b/ckan/tests/controllers/test_group.py @@ -189,21 +189,34 @@ def test_all_fields_saved(self): class TestGroupRead(helpers.FunctionalTestBase): - def setup(self): - super(TestGroupRead, self).setup() - self.app = helpers._get_test_app() - self.user = factories.User() - self.user_env = {'REMOTE_USER': self.user['name'].encode('ascii')} - self.group = factories.Group(user=self.user) def test_group_read(self): - response = self.app.get(url=url_for(controller='group', - action='read', - id=self.group['id']), - status=200, - extra_environ=self.user_env) - assert_in(self.group['title'], response) - assert_in(self.group['description'], response) + group = factories.Group() + app = helpers._get_test_app() + response = app.get(url=url_for(controller='group', + action='read', + id=group['name'])) + assert_in(group['title'], response) + assert_in(group['description'], response) + + def test_redirect_when_given_id(self): + group = factories.Group() + app = helpers._get_test_app() + response = app.get(url_for(controller='group', action='read', + id=group['id']), + status=302) + # redirect replaces the ID with the name in the URL + redirected_response = response.follow() + expected_url = url_for(controller='group', action='read', + id=group['name']) + assert_equal(redirected_response.request.path, expected_url) + + def test_no_redirect_loop_when_name_is_the_same_as_the_id(self): + group = factories.Group(id='abc', name='abc') + app = helpers._get_test_app() + app.get(url_for(controller='group', action='read', + id=group['id']), + status=200) # ie no redirect class TestGroupDelete(helpers.FunctionalTestBase): @@ -537,7 +550,8 @@ def test_group_unfollow_not_following(self): id=group['id']) unfollow_response = app.post(unfollow_url, extra_environ=env, status=302) - unfollow_response = unfollow_response.follow() + unfollow_response = unfollow_response.follow() # /group/[id] 302s to: + unfollow_response = unfollow_response.follow() # /group/[name] assert_true('You are not following {0}'.format(group['id']) in unfollow_response) @@ -660,7 +674,7 @@ def test_group_search_within_org(self): groups=[{'id': grp['id']}]) grp_url = url_for(controller='group', action='read', - id=grp['id']) + id=grp['name']) grp_response = app.get(grp_url) grp_response_html = BeautifulSoup(grp_response.body) @@ -688,7 +702,7 @@ def test_group_search_within_org_results(self): groups=[{'id': grp['id']}]) grp_url = url_for(controller='group', action='read', - id=grp['id']) + id=grp['name']) grp_response = app.get(grp_url) search_form = grp_response.forms['group-datasets-search-form'] search_form['q'] = 'One' @@ -721,7 +735,7 @@ def test_group_search_within_org_no_results(self): groups=[{'id': grp['id']}]) grp_url = url_for(controller='group', action='read', - id=grp['id']) + id=grp['name']) grp_response = app.get(grp_url) search_form = grp_response.forms['group-datasets-search-form'] search_form['q'] = 'Nout' diff --git a/ckan/tests/controllers/test_organization.py b/ckan/tests/controllers/test_organization.py --- a/ckan/tests/controllers/test_organization.py +++ b/ckan/tests/controllers/test_organization.py @@ -82,21 +82,33 @@ def test_error_message_shown_when_no_organization_list_permission(self, mock_che class TestOrganizationRead(helpers.FunctionalTestBase): - def setup(self): - super(TestOrganizationRead, self).setup() - self.app = helpers._get_test_app() - self.user = factories.User() - self.user_env = {'REMOTE_USER': self.user['name'].encode('ascii')} - self.organization = factories.Organization(user=self.user) + def test_group_read(self): + org = factories.Organization() + app = helpers._get_test_app() + response = app.get(url=url_for(controller='organization', + action='read', + id=org['name'])) + assert_in(org['title'], response) + assert_in(org['description'], response) - def test_organization_read(self): - response = self.app.get(url=url_for(controller='organization', - action='read', - id=self.organization['id']), - status=200, - extra_environ=self.user_env) - assert_in(self.organization['title'], response) - assert_in(self.organization['description'], response) + def test_read_redirect_when_given_id(self): + org = factories.Organization() + app = helpers._get_test_app() + response = app.get(url_for(controller='organization', action='read', + id=org['id']), + status=302) + # redirect replaces the ID with the name in the URL + redirected_response = response.follow() + expected_url = url_for(controller='organization', action='read', + id=org['name']) + assert_equal(redirected_response.request.path, expected_url) + + def test_no_redirect_loop_when_name_is_the_same_as_the_id(self): + org = factories.Organization(id='abc', name='abc') + app = helpers._get_test_app() + app.get(url_for(controller='organization', action='read', + id=org['id']), + status=200) # ie no redirect class TestOrganizationEdit(helpers.FunctionalTestBase): @@ -397,7 +409,7 @@ def test_organization_search_within_org(self): owner_org=org['id']) org_url = url_for(controller='organization', action='read', - id=org['id']) + id=org['name']) org_response = app.get(org_url) org_response_html = BeautifulSoup(org_response.body) @@ -426,7 +438,7 @@ def test_organization_search_within_org_results(self): owner_org=org['id']) org_url = url_for(controller='organization', action='read', - id=org['id']) + id=org['name']) org_response = app.get(org_url) search_form = org_response.forms['organization-datasets-search-form'] search_form['q'] = 'One' @@ -459,7 +471,7 @@ def test_organization_search_within_org_no_results(self): owner_org=org['id']) org_url = url_for(controller='organization', action='read', - id=org['id']) + id=org['name']) org_response = app.get(org_url) search_form = org_response.forms['organization-datasets-search-form'] search_form['q'] = 'Nout' diff --git a/ckan/tests/controllers/test_package.py b/ckan/tests/controllers/test_package.py --- a/ckan/tests/controllers/test_package.py +++ b/ckan/tests/controllers/test_package.py @@ -9,12 +9,11 @@ assert_in ) -from mock import patch, MagicMock from ckan.lib.helpers import url_for import ckan.model as model import ckan.plugins as p -from ckan.lib import search +from ckan.logic import get_action import ckan.tests.helpers as helpers import ckan.tests.factories as factories @@ -1655,7 +1654,8 @@ def test_package_unfollow_not_following(self): id=package['id']) unfollow_response = app.post(unfollow_url, extra_environ=env, status=302) - unfollow_response = unfollow_response.follow() + unfollow_response = unfollow_response.follow() # /package/[id] 302s to + unfollow_response = unfollow_response.follow() # /package/[name] assert_true('You are not following {0}'.format(package['id']) in unfollow_response) @@ -1703,6 +1703,22 @@ def test_dataset_read(self): dataset = factories.Dataset() url = url_for('dataset.read', - id=dataset['id']) + id=dataset['name']) response = app.get(url) assert_in(dataset['title'], response) + + def test_redirect_when_given_id(self): + dataset = factories.Dataset() + app = helpers._get_test_app() + response = app.get(url_for('dataset.read', id=dataset['id']), + status=302) + # redirect replaces the ID with the name in the URL + redirected_response = response.follow() + expected_url = url_for('dataset.read', id=dataset['name']) + assert_equal(redirected_response.request.path, expected_url) + + def test_no_redirect_loop_when_name_is_the_same_as_the_id(self): + dataset = factories.Dataset(id='abc', name='abc') + app = helpers._get_test_app() + app.get(url_for('dataset.read', id=dataset['id']), + status=200) # ie no redirect
Redirect /dataset/[id] -> /dataset/[name] etc Redirects: * /dataset/[id] -> /dataset/[name] * /group/[id] -> /group/[name] * /organization/[id] -> /organization/[name] Specifying these objects by *id* is hidden functionality really. There are no links to it. I've added it for two reasons: 1. As a developer it's occasionally I know a dataset's id and want to look at it, and it is useful to have it instead display on the normal url with the name in it. Why would you want the current functionality and keep it as the weird id url anyway? It's functionality I've wanted on many occasions over the years - maybe it's just me! 2. In Activity Stream the links to old versions of datasets/groups/organizations are currently given using the 'name' of those objects *as they were at the time of the change*. Obviously there are ways that these objects can change name, and in this case the link gets broken. So with my changes in PR https://github.com/ckan/ckan/pull/3972 I'm keen to change the link to be the id of the objects, so we avoid the broken link problem, and we don't add a whole bunch of joins on these queries that are potentially already quite big.
2018-06-29T20:53:53
ckan/ckan
4,319
ckan__ckan-4319
[ "4310" ]
600be27ef380b791dbadeda5d32c0021dca41a09
diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py --- a/ckan/config/middleware/flask_app.py +++ b/ckan/config/middleware/flask_app.py @@ -32,6 +32,7 @@ from ckan.views import (identify_user, set_cors_headers_for_response, check_session_cookie, + set_controller_and_action ) @@ -279,6 +280,10 @@ def ckan_before_request(): # Sets g.user and g.userobj identify_user() + # Provide g.controller and g.action for backward compatibility + # with extensions + set_controller_and_action() + def ckan_after_request(response): u'''Common handler executed after all Flask requests''' diff --git a/ckan/plugins/toolkit.py b/ckan/plugins/toolkit.py --- a/ckan/plugins/toolkit.py +++ b/ckan/plugins/toolkit.py @@ -44,6 +44,8 @@ class _Toolkit(object): 'literal', # get logic action function 'get_action', + # get flask/pylons endpoint fragments + 'get_endpoint', # decorator for chained action 'chained_action', # get navl schema converter @@ -283,6 +285,7 @@ def _initialize(self): t['add_ckan_admin_tab'] = self._add_ckan_admin_tabs t['requires_ckan_version'] = self._requires_ckan_version t['check_ckan_version'] = self._check_ckan_version + t['get_endpoint'] = self._get_endpoint t['CkanVersionException'] = CkanVersionException t['HelperError'] = HelperError t['enqueue_job'] = enqueue_job @@ -456,6 +459,26 @@ def _requires_ckan_version(cls, min_version, max_version=None): ) raise CkanVersionException(error) + @classmethod + def _get_endpoint(cls): + """Returns tuple in format: (controller|blueprint, action|view). + """ + import ckan.common as common + try: + # CKAN >= 2.8 + endpoint = tuple(common.request.endpoint.split('.')) + except AttributeError: + try: + return common.c.controller, common.c.action + except AttributeError: + return (None, None) + # there are some routes('hello_world') that are not using blueprint + # For such case, let's assume that view function is a controller + # itself and action is None. + if len(endpoint) is 1: + return endpoint + (None,) + return endpoint + def __getattr__(self, name): ''' return the function/object requested ''' if not self._toolkit: diff --git a/ckan/views/__init__.py b/ckan/views/__init__.py --- a/ckan/views/__init__.py +++ b/ckan/views/__init__.py @@ -179,3 +179,14 @@ def _get_user_for_apikey(): query = model.Session.query(model.User) user = query.filter_by(apikey=apikey).first() return user + + +def set_controller_and_action(): + try: + controller, action = request.endpoint.split(u'.') + except ValueError: + log.debug( + u'Endpoint does not contain dot: {}'.format(request.endpoint) + ) + controller = action = request.endpoint + g.controller, g.action = controller, action
Missing c.action attribute in 2.8.0 templates It seems that in CKAN 2.8.0, the `c.action` attribute is at least sometimes missing when templates are being rendered. I can reproduce this for the `home/index.html` template, which currently breaks ckanext-pages for CKAN 2.8.0 (see ckan/ckanext-pages#78). It seems that this is a consequence of [a change to `routing.py`](https://github.com/ckan/ckan/pull/3891/files#diff-eb995cd7c3a1045a463f8172c7adb128) as part of #3891, although I'm not sure about that.
@smotornyuk can you have a look at this? I'm not sure whether this is the same problem, but it seems that `c` is also missing the `controller` attribute in some cases in 2.8.0. See stadt-karlsruhe/ckanext-discovery#1.
2018-07-03T13:27:33
ckan/ckan
4,348
ckan__ckan-4348
[ "4346" ]
f6caf33b0f60645269e3013a5056761d22697557
diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py --- a/ckan/lib/helpers.py +++ b/ckan/lib/helpers.py @@ -68,6 +68,8 @@ LEGACY_ROUTE_NAMES = { 'home': 'home.index', 'about': 'home.about', + 'search': 'dataset.search', + 'organizations_index': 'organization.index' }
`search` legacy route missing ### CKAN Version if known (or site URL) 2.8+ (master) ### Please describe the expected behaviour There is a shortcut for the `search` legacy route in CKAN 2.8+, I guess it's missing in [LEGACY_ROUTE_NAMES](https://github.com/ckan/ckan/blob/df35eec2f5229bc60176cf96dc83ca1fcc259d1e/ckan/lib/helpers.py#L68-L71). ### Please describe the actual behaviour On master `search` is not available as route, basically the same as described in #4066 ### What steps can be taken to reproduce the issue? ```python h.build_nav_main( ('home', _('Homepage')), ('search', _('Datasets')), ('group_index', _('Groups')) ) ```
@metaodi it was not added as the 'package' controller was not merged in that time, but i think it could be added in the .ini file http://docs.ckan.org/en/2.8/maintaining/configuration.html#ckan-legacy-route-mappings edit: but you are right, we should add it in the helper Well yes, but I think all legacy routes should be added there for compatibility reasons. If I provide a CKAN extension, it should work on all CKAN versions. The ini file might be a solution for tests, but I don't want all users of an extension to add `ckan.legacy_route_mappings` to their instances ini file, just because the extension runs on multiple versions of CKAN.
2018-07-18T19:04:46
ckan/ckan
4,349
ckan__ckan-4349
[ "4303" ]
f6caf33b0f60645269e3013a5056761d22697557
diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py --- a/ckan/config/middleware/flask_app.py +++ b/ckan/config/middleware/flask_app.py @@ -415,6 +415,9 @@ def _register_error_handler(app): def error_handler(e): if isinstance(e, HTTPException): extra_vars = {u'code': [e.code], u'content': e.description} + # TODO: Remove + g.code = [e.code] + return base.render( u'error_document_template.html', extra_vars), e.code extra_vars = {u'code': [500], u'content': u'Internal server error'}
Undocumented changes breaking error_document_template It seems that #4225 changed how the HTTP error code is passed to `error_document_template.html`. In CKAN 2.7.3, `error_document_template.html` [says](https://github.com/ckan/ckan/blob/ckan-2.7.3/ckan/templates/error_document_template.html#L3): {% block subtitle %}{{ gettext('Error %(error_code)s', error_code=c.code[0]) }}{% endblock %} In CKAN 2.8.0, however, the (BS2-) template [says](https://github.com/ckan/ckan/blob/ckan-2.8.0/ckan/templates-bs2/error_document_template.html#L3): {% block subtitle %}{{ gettext('Error %(error_code)s', error_code=code[0]) }}{% endblock %} Note `c.code[0]` vs. `code[0]`. Hence, custom variants of `error_document_template.html` need to be updated to work under CKAN 2.8.0. However, that change is not mentioned in the [change log](http://docs.ckan.org/en/2.8/changelog.html).
You are right @torfsen, we should have kept the `c.code` version deprecated for a version before removing it. We are gradually removing stuff from `c` in favour of passing vars explicitly to templates, but we should keep the values in `c` for at least a version. @tino097 can you set `c.code` in the Flask error handler (or `g.code` rather) but don't use it anywhere. I like @torfsen 's suggestion of adding the change to the changelog. For this issue we could support old copied and modified templates as @amercader says, and try to remember to remove the dead code later. For general template changes I don't want to be held to the same deprecation process that we have for things like plugin interfaces. When we get around to reducing the template `extends` and `snippet` nesting we can't sensibly support every customized theme at the same time. @wardi Just to be clear, are you happy to keep support for all `c.*` vars for a version and remove them later or just this particular one on the error template? We've followed this approach so far for the admin, user and home controllers (merged) and for the group and package ones (almost merged) ([example](https://github.com/ckan/ckan/pull/4062/files#diff-2c4f7feb385fad48e72f4de013976946R1019). My plan was to list all of the deprecated `c` vars in the changelog or dedicated docs page, we just missed the one mentioned on this issue. The fix in the extension templates is quite straight-forward (`c.var -> var`) but on templates like the package ones there is a ton of them. So in general, leaving this particular var on the error template aside when dropping support for `c` vars do you want to: 1. Keep them in `c` in master/2.9 + Announce on 2.9 Changelog + Drop them from `c` in 2.10 2. Drop them from `c` in master/2.9 + Announce on 2.9 Changelog that they have been removed I think 1 at least will give a bit more time to people to update their extensions, and tackle the unsolved issue of how to support different CKAN versions with the same templates. But maybe I'm being too conservative and given our release schedule we can go for 2. (Some previous discussion on https://github.com/ckan/ckan/pull/3203 and more recently in #4062) Should have kept my mouth shut, I'm thinking about not tying our hands for larger unrelated template changes. @amercader's suggested fix is good for this issue, and I'm happy with either approach 1 or 2 above. For what it's worth, as a user of and developer of custom templates I'm perfectly fine with having to update my templates when upgrading to a new CKAN minor version (as long as the changes are small, as in this case -- the switch to Bootstrap 3 is a bigger task, so the provision of the legacy BS2-templates is much appreciated). Hence, mentioning the change in the change log would have been enough for me. > Should have kept my mouth shut Please don't! Yours and @torfsen is really valuable feedback! We'll stick to 1 for now but we can revisit and go for 2 when we finish the migration of the controllers.
2018-07-18T19:16:54
ckan/ckan
4,367
ckan__ckan-4367
[ "4346" ]
a7f72f1babece6ce1ebeced6fc6f8c3036a7f8da
diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py --- a/ckan/lib/helpers.py +++ b/ckan/lib/helpers.py @@ -69,6 +69,7 @@ 'home': 'home.index', 'about': 'home.about', 'search': 'dataset.search', + 'group_index': 'group.index', 'organizations_index': 'organization.index' }
diff --git a/ckan/tests/lib/test_helpers.py b/ckan/tests/lib/test_helpers.py --- a/ckan/tests/lib/test_helpers.py +++ b/ckan/tests/lib/test_helpers.py @@ -532,6 +532,38 @@ def test_non_string(self): u'2018-01-05 10:48:23.463511') +class TestBuildNavMain(object): + def test_flask_routes(self): + menu = ( + ('home.index', 'Home'), + ('dataset.search', 'Datasets'), + ('organization.index', 'Organizations'), + ('group.index', 'Groups'), + ('home.about', 'About') + ) + eq_(h.build_nav_main(*menu), ( + '<li><a href="/">Home</a></li>' + '<li><a href="/dataset/">Datasets</a></li>' + '<li><a href="/organization/">Organizations</a></li>' + '<li><a href="/group/">Groups</a></li>' + '<li><a href="/about">About</a></li>')) + + def test_legacy_pylon_routes(self): + menu = ( + ('home', 'Home'), + ('search', 'Datasets'), + ('organizations_index', 'Organizations'), + ('group_index', 'Groups'), + ('about', 'About') + ) + eq_(h.build_nav_main(*menu), ( + '<li><a href="/">Home</a></li>' + '<li><a href="/dataset/">Datasets</a></li>' + '<li><a href="/organization/">Organizations</a></li>' + '<li><a href="/group/">Groups</a></li>' + '<li><a href="/about">About</a></li>')) + + class TestHelperException(helpers.FunctionalTestBase): @raises(ckan.exceptions.HelperError)
`search` legacy route missing ### CKAN Version if known (or site URL) 2.8+ (master) ### Please describe the expected behaviour There is a shortcut for the `search` legacy route in CKAN 2.8+, I guess it's missing in [LEGACY_ROUTE_NAMES](https://github.com/ckan/ckan/blob/df35eec2f5229bc60176cf96dc83ca1fcc259d1e/ckan/lib/helpers.py#L68-L71). ### Please describe the actual behaviour On master `search` is not available as route, basically the same as described in #4066 ### What steps can be taken to reproduce the issue? ```python h.build_nav_main( ('home', _('Homepage')), ('search', _('Datasets')), ('group_index', _('Groups')) ) ```
@metaodi it was not added as the 'package' controller was not merged in that time, but i think it could be added in the .ini file http://docs.ckan.org/en/2.8/maintaining/configuration.html#ckan-legacy-route-mappings edit: but you are right, we should add it in the helper Well yes, but I think all legacy routes should be added there for compatibility reasons. If I provide a CKAN extension, it should work on all CKAN versions. The ini file might be a solution for tests, but I don't want all users of an extension to add `ckan.legacy_route_mappings` to their instances ini file, just because the extension runs on multiple versions of CKAN. @tino097 Why have you removed `group_index` again? Now my build fails, because this route is still missing. Here is the link to the build: https://travis-ci.org/opendatazurich/ckanext-stadtzh-theme/jobs/405325390#L1427 I'd propose to add a test for this, calling build_nav_main() with the legacy routes should not raise an exception. @metaodi in the [review](https://github.com/ckan/ckan/pull/4348#discussion_r203759217) was pointed out that those routes should be handled in the helper ping @amercader @tino097 @amercader just let me know if you want help. Happy to provide a PR with the test and/or the updated legacy routes. @metaodi why just not update the nav menu in the template in your extension? As the migration to Flask will be finishing, those routes would be deprecated @tino097 because the extension runs on multiple versions of CKAN, older version do not support the new flask-based names obviously, so the new CKAN version should support the old names to be backwards compatible. I was mistaken in the way `build_nav_main` works (a truly terrible way btw), I assumed it was calling `url_for` directly (which is where the support for old Pylons routes exists) but apparently is doing some other voodoo first, which means that yes, we need to add it to `LEGACY_ROUTE_NAMES`. @tino097 just to be clear the `group_index` item only affects master so it doesn't need to go to 2.8.1 @metaodi a PR readding the route would be great thanks.
2018-07-25T13:53:31
ckan/ckan
4,370
ckan__ckan-4370
[ "4332" ]
561e4bd112a0b24cc0dd8af6c455781a86fb7bb2
diff --git a/ckanext/datapusher/plugin.py b/ckanext/datapusher/plugin.py --- a/ckanext/datapusher/plugin.py +++ b/ckanext/datapusher/plugin.py @@ -68,7 +68,11 @@ def resource_data(self, id, resource_id): base.abort(403, _('Not authorized to see this page')) return base.render('datapusher/resource_data.html', - extra_vars={'status': datapusher_status}) + extra_vars={ + 'status': datapusher_status, + 'pkg_dict': toolkit.c.pkg_dict, + 'resource': toolkit.c.resource, + }) class DatapusherPlugin(p.SingletonPlugin): diff --git a/ckanext/datastore/controller.py b/ckanext/datastore/controller.py --- a/ckanext/datastore/controller.py +++ b/ckanext/datastore/controller.py @@ -109,7 +109,11 @@ def dictionary(self, id, resource_id): return render( 'datastore/dictionary.html', - extra_vars={'fields': fields}) + extra_vars={ + 'fields': fields, + 'pkg_dict': c.pkg_dict, + 'resource': c.resource, + }) def dump_to(resource_id, output, fmt, offset, limit, options):
diff --git a/ckanext/datapusher/tests/test_controller.py b/ckanext/datapusher/tests/test_controller.py new file mode 100644 --- /dev/null +++ b/ckanext/datapusher/tests/test_controller.py @@ -0,0 +1,34 @@ +# encoding: utf-8 + +import nose + +import ckan.tests.legacy as tests +from ckan.tests.helpers import FunctionalTestBase +import ckan.tests.factories as factories + + +class TestController(FunctionalTestBase): + sysadmin_user = None + normal_user = None + + _load_plugins = [u'datastore', u'datapusher'] + + @classmethod + def setup_class(cls): + cls.app = cls._get_test_app() + if not tests.is_datastore_supported(): + raise nose.SkipTest(u'Datastore not supported') + super(TestController, cls).setup_class() + + def test_resource_data(self): + user = factories.User() + dataset = factories.Dataset(creator_user_id=user['id']) + resource = factories.Resource(package_id=dataset['id'], + creator_user_id=user['id']) + auth = {u'Authorization': str(user['apikey'])} + + self.app.get( + url=u'/dataset/{id}/resource_data/{resource_id}' + .format(id=str(dataset['name']), + resource_id=str(resource['id'])), + extra_environ=auth) diff --git a/ckanext/datastore/tests/test_dictionary.py b/ckanext/datastore/tests/test_dictionary.py new file mode 100644 --- /dev/null +++ b/ckanext/datastore/tests/test_dictionary.py @@ -0,0 +1,34 @@ +# encoding: utf-8 + +from ckanext.datastore.tests.helpers import DatastoreFunctionalTestBase, DatastoreLegacyTestBase +import ckan.tests.factories as factories +import ckan.tests.helpers as helpers + + +class TestDatastoreDictionary(DatastoreLegacyTestBase): + + @classmethod + def setup_class(cls): + cls.app = helpers._get_test_app() + super(TestDatastoreDictionary, cls).setup_class() + + def test_read(self): + user = factories.User() + dataset = factories.Dataset(creator_user_id=user['id']) + resource = factories.Resource(package_id=dataset['id'], + creator_user_id=user['id']) + data = { + u'resource_id': resource['id'], + u'force': True, + u'records': [ + {u'from': u'Brazil', u'to': u'Brazil', u'num': 2}, + {u'from': u'Brazil', u'to': u'Italy', u'num': 22} + ], + } + helpers.call_action(u'datastore_create', **data) + auth = {u'Authorization': str(user['apikey'])} + self.app.get( + url=u'/dataset/{id}/dictionary/{resource_id}' + .format(id=str(dataset['name']), + resource_id=str(resource['id'])), + extra_environ=auth)
DataStore view fails with UndefinedError: 'resource' is undefined ### CKAN Version if known (or site URL) Any commit from master git branch after 8209814cbd0db62eeebcbf21bbebf0383e78c5a3 (e.g. current HEAD - ac1bbc1e681c6b9cda41bbe2d878d0f81c302e4a) ### Please describe the expected behaviour DataStore view is rendered i.e. exception when rendering these two highlighted tabs: <img width="838" alt="screen shot 2018-07-27 at 10 43 51" src="https://user-images.githubusercontent.com/307612/43314207-2d5daf92-918a-11e8-8c8b-bc490475b65d.png"> ### Please describe the actual behaviour DataStore view fails with `UndefinedError: 'resource' is undefined`. This happens after commit 8209814cbd0db62eeebcbf21bbebf0383e78c5a3 in git master branch. I suspect that one of the @smotornyuk's changes from PR #4062 is at fault. Stack trace ``` Error - <class 'jinja2.exceptions.UndefinedError'>: 'resource' is undefined URL: http://172.17.0.7:8080/test/resource_data/4ed8742f-a95b-4e53-94ad-b136a2ff8501 File '/usr/lib/python2.7/site-packages/weberror/errormiddleware.py', line 171 in __call__ app_iter = self.application(environ, sr_checker) File '/usr/lib/python2.7/site-packages/webob/dec.py', line 147 in __call__ resp = self.call_func(req, *args, **self.kwargs) File '/usr/lib/python2.7/site-packages/webob/dec.py', line 208 in call_func return self.func(req, *args, **kwargs) File '/usr/lib/python2.7/site-packages/fanstatic/publisher.py', line 234 in __call__ return request.get_response(self.app) File '/usr/lib/python2.7/site-packages/webob/request.py', line 1053 in get_response application, catch_exc_info=False) File '/usr/lib/python2.7/site-packages/webob/request.py', line 1022 in call_application app_iter = application(self.environ, start_response) File '/usr/lib/python2.7/site-packages/webob/dec.py', line 147 in __call__ resp = self.call_func(req, *args, **self.kwargs) File '/usr/lib/python2.7/site-packages/webob/dec.py', line 208 in call_func return self.func(req, *args, **kwargs) File '/usr/lib/python2.7/site-packages/fanstatic/injector.py', line 54 in __call__ response = request.get_response(self.app) File '/usr/lib/python2.7/site-packages/webob/request.py', line 1053 in get_response application, catch_exc_info=False) File '/usr/lib/python2.7/site-packages/webob/request.py', line 1022 in call_application app_iter = application(self.environ, start_response) File '/srv/ckan/src/ckan/ckan/config/middleware/pylons_app.py', line 265 in inner result = application(environ, start_response) File '/usr/lib/python2.7/site-packages/beaker/middleware.py', line 73 in __call__ return self.app(environ, start_response) File '/usr/lib/python2.7/site-packages/beaker/middleware.py', line 156 in __call__ return self.wrap_app(environ, session_start_response) File '/usr/lib/python2.7/site-packages/routes/middleware.py', line 131 in __call__ response = self.app(environ, start_response) File '/srv/ckan/src/ckan/ckan/config/middleware/common_middleware.py', line 30 in __call__ return self.app(environ, start_response) File '/srv/ckan/src/ckan/ckan/config/middleware/common_middleware.py', line 56 in __call__ return self.app(environ, start_response) File '/usr/lib/python2.7/site-packages/pylons/wsgiapp.py', line 125 in __call__ response = self.dispatch(controller, environ, start_response) File '/usr/lib/python2.7/site-packages/pylons/wsgiapp.py', line 324 in dispatch return controller(environ, start_response) File '/srv/ckan/src/ckan/ckan/lib/base.py', line 241 in __call__ res = WSGIController.__call__(self, environ, start_response) File '/usr/lib/python2.7/site-packages/pylons/controllers/core.py', line 221 in __call__ response = self._dispatch_call() File '/usr/lib/python2.7/site-packages/pylons/controllers/core.py', line 172 in _dispatch_call response = self._inspect_call(func) File '/usr/lib/python2.7/site-packages/pylons/controllers/core.py', line 107 in _inspect_call result = self._perform_call(func, args) File '/usr/lib/python2.7/site-packages/pylons/controllers/core.py', line 60 in _perform_call return func(**args) File '/srv/ckan/src/ckan/ckanext/datapusher/plugin.py', line 71 in resource_data extra_vars={'status': datapusher_status}) File '/srv/ckan/src/ckan/ckan/lib/base.py', line 126 in render return cached_template(template_name, renderer) File '/usr/lib/python2.7/site-packages/pylons/templating.py', line 249 in cached_template return render_func() File '/srv/ckan/src/ckan/ckan/lib/base.py', line 163 in render_template return render_jinja2(template_name, globs) File '/srv/ckan/src/ckan/ckan/lib/base.py', line 95 in render_jinja2 return template.render(**extra_vars) File '/usr/lib/python2.7/site-packages/jinja2/environment.py', line 989 in render return self.environment.handle_exception(exc_info, True) File '/usr/lib/python2.7/site-packages/jinja2/environment.py', line 754 in handle_exception reraise(exc_type, exc_value, tb) File '/srv/ckan/src/ckan/ckanext/datapusher/templates/datapusher/resource_data.html', line 1 in top-level template code {% extends "package/resource_edit_base.html" %} File '/srv/ckan/src/ckan/ckanext/datastore/templates/package/resource_edit_base.html', line 1 in top-level template code {% ckan_extends %} File '/srv/ckan/src/ckan/ckanext/datapusher/templates/package/resource_edit_base.html', line 1 in top-level template code {% ckan_extends %} File '/srv/ckan/src/ckan/ckan/templates/package/resource_edit_base.html', line 4 in top-level template code {% set res = resource %} File '/srv/ckan/src/ckan/ckan/templates/package/base.html', line 3 in top-level template code {% set pkg = pkg_dict or c.pkg_dict %} File '/srv/ckan/src/ckan/ckan/templates/page.html', line 1 in top-level template code {% extends "base.html" %} File '/srv/ckan/src/ckanext-geoview/ckanext/geoview/templates/base.html', line 1 in top-level template code {% ckan_extends %} File '/srv/ckan/src/ckan/ckan/templates/base.html', line 41 in top-level template code {%- block title -%} File '/srv/ckan/src/ckan/ckan/templates/base.html', line 42 in block "title" {%- block subtitle %}{% endblock -%} File '/srv/ckan/src/ckan/ckanext/datapusher/templates/datapusher/resource_data.html', line 3 in block "subtitle" {% block subtitle %}{{ h.dataset_display_name(pkg) }} - {{ h.resource_display_name(res) }}{% endblock %} File '/srv/ckan/src/ckan/ckan/lib/helpers.py', line 1607 in resource_display_name name = get_translated(resource_dict, 'name') File '/srv/ckan/src/ckan/ckan/lib/helpers.py', line 2565 in get_translated return data_dict[field + u'_translated'][language] UndefinedError: 'resource' is undefined ``` ### What steps can be taken to reproduce the issue? 1. Install any CKAN from git master after 8209814cbd0db62eeebcbf21bbebf0383e78c5a3. 2. Install any compatible DataPusher (e.g. current git master - https://github.com/ckan/datapusher/commit/bd990de116adf76e685938b2266aa7e8b5187bfd). 3. Enable CKAN integration with DataPusher. 4. Create a dataset and upload a file. 5. Try to visit DataStore status view.
Yeah, this is correct. I suppose this comes with living on the edge. This fixes the exceptions for the "DataStore" and "Data Dictionary" tabs, but @smotornyuk is this the right way to go? If so, I'm happy to add a test and submit a PR. ``` diff --git a/ckanext/datapusher/plugin.py b/ckanext/datapusher/plugin.py index d46a819bb..10736a665 100644 --- a/ckanext/datapusher/plugin.py +++ b/ckanext/datapusher/plugin.py @@ -68,7 +68,10 @@ class ResourceDataController(base.BaseController): base.abort(403, _('Not authorized to see this page')) return base.render('datapusher/resource_data.html', - extra_vars={'status': datapusher_status}) + extra_vars={ + 'status': datapusher_status, + 'resource': toolkit.c.resource, + }) class DatapusherPlugin(p.SingletonPlugin): diff --git a/ckanext/datastore/controller.py b/ckanext/datastore/controller.py index bd7fcb452..6fdec567e 100644 --- a/ckanext/datastore/controller.py +++ b/ckanext/datastore/controller.py @@ -109,7 +109,10 @@ class DatastoreController(BaseController): return render( 'datastore/dictionary.html', - extra_vars={'fields': fields}) + extra_vars={ + 'fields': fields, + 'resource': c.resource, + }) def dump_to(resource_id, output, fmt, offset, limit, options): ``` Yes, @davidread , it's the most adequate solution. During the migration of package controller, I updated all templates to use local variables instead of trying to fetch them from `c` object and missed these datastore/datapusher moments . Thank you for helping in this :)
2018-07-27T09:59:11
ckan/ckan
4,376
ckan__ckan-4376
[ "3510" ]
4c46765a63966cbf078ad9d4f547b2412bcf27f5
diff --git a/ckan/lib/search/query.py b/ckan/lib/search/query.py --- a/ckan/lib/search/query.py +++ b/ckan/lib/search/query.py @@ -20,7 +20,7 @@ VALID_SOLR_PARAMETERS = set([ 'q', 'fl', 'fq', 'rows', 'sort', 'start', 'wt', 'qf', 'bf', 'boost', 'facet', 'facet.mincount', 'facet.limit', 'facet.field', - 'extras', 'fq_list', 'tie', 'defType', 'mm' + 'extras', 'fq_list', 'tie', 'defType', 'mm', 'df' ]) # for (solr) package searches, this specifies the fields that are searched diff --git a/ckan/logic/action/get.py b/ckan/logic/action/get.py --- a/ckan/logic/action/get.py +++ b/ckan/logic/action/get.py @@ -1814,6 +1814,9 @@ def package_search(context, data_dict): for key in [key for key in data_dict.keys() if key.startswith('ext_')]: data_dict['extras'][key] = data_dict.pop(key) + # set default search field + data_dict['df'] = 'text' + # check if some extension needs to modify the search params for item in plugins.PluginImplementations(plugins.IPackageController): data_dict = item.before_search(data_dict)
Quirks with Solr6 Some quirks with CKAN and up-to-date versions of Solr: - default field in the schema is deprecated: `[ckan] default search field in schema is text. WARNING: Deprecated,&#8203; please use 'df' on request instead.` - When multiple terms are provided (like an org filter) the field name to search must be explicit. This is currently breaking searching for terms within an organization (`q=test +owner_org:...` fails, `q=text:test +owner_org:...` works, `q=test` works). - While we're here, owner org should be a filter not part of the query.
For point 2, a very small change should be forward and backwards compatible and safe for back-porting. Ex: ```diff diff --git a/ckan/controllers/group.py b/ckan/controllers/group.py index 087209f..912c402 100644 --- a/ckan/controllers/group.py +++ b/ckan/controllers/group.py @@ -236,6 +236,9 @@ class GroupController(base.BaseController): 'for_view': True, 'extras_as_string': True} q = c.q = request.params.get('q', '') + if q is not None and q.strip(): + q = 'text:{q}'.format(q=q) + # Search within group if c.group_dict.get('is_organization'): q += ' owner_org:"%s"' % c.group_dict.get('id') ``` Is solR 6.0.0 supported with CKAN 2.7.2 ? I'm getting this error: > [Reason: sort param field can't be found: metadata_modified] [Tue Apr > 03 15:56:11.881767 2018] [:error] [pid 10485] 2018-04-03 15:56:11,881 > ERROR [ckan.controllers.package] Dataset search error: ('SOLR returned > an error running query: {\\'sort\\': \\'score desc, metadata_modified > desc\\', \\'fq\\': [u\\'+dataset_type:dataset\\', > u\\'+site_id:"default"\\', \\'+state:active\\', > u\\'+permission_labels:("public")\\'], \\'facet.mincount\\': 1, > \\'rows\\': 21, \\'facet.field\\': [u\\'organization\\', > u\\'groups\\', u\\'tags\\', u\\'res_format\\', u\\'license_id\\'], > \\'facet.limit\\': \\'50\\', \\'facet\\': \\'true\\', \\'q\\': > \\'*:*\\', \\'start\\': 0, \\'wt\\': \\'json\\', \\'fl\\': \\'id > validated_data_dict\\'} Error: SolrError(u"Solr responded with an > error (HTTP 400): [Reason: sort param field can\\'t be found: > metadata_modified]",)',) [Tue Apr 03 15:56:11.934996 2018] [:error] > [pid 10485] 2018-04-03 15:56:11,934 INFO [ckan.lib.base] /dataset > render time 0.084 seconds [Tue Apr 03 15:56:12.445289 2018] [:error] > [pid 10485] 2018-04-03 15:56:12,445 INFO [ckan.lib.base] > /api/i18n/en render time 0.006 seconds I read in stack overflow to downgrade the solR to v5.0.0.
2018-07-31T06:51:14
ckan/ckan
4,384
ckan__ckan-4384
[ "4382" ]
332bc573354d1f88d90bb753c91f267669afd774
diff --git a/ckan/lib/dictization/model_dictize.py b/ckan/lib/dictization/model_dictize.py --- a/ckan/lib/dictization/model_dictize.py +++ b/ckan/lib/dictization/model_dictize.py @@ -108,6 +108,7 @@ def resource_dictize(res, context): ## for_edit is only called at the times when the dataset is to be edited ## in the frontend. Without for_edit the whole qualified url is returned. if resource.get('url_type') == 'upload' and not context.get('for_edit'): + url = url.rsplit('/')[-1] cleaned_name = munge.munge_filename(url) resource['url'] = h.url_for('resource.download', id=resource['package_id'], diff --git a/ckan/lib/dictization/model_save.py b/ckan/lib/dictization/model_save.py --- a/ckan/lib/dictization/model_save.py +++ b/ckan/lib/dictization/model_save.py @@ -13,7 +13,9 @@ log = logging.getLogger(__name__) + def resource_dict_save(res_dict, context): + model = context["model"] session = context["session"] @@ -30,6 +32,10 @@ def resource_dict_save(res_dict, context): table = class_mapper(model.Resource).mapped_table fields = [field.name for field in table.c] + # Strip the full url for resources of type 'upload' + if res_dict.get('url') and res_dict.get('url_type') == u'upload': + res_dict['url'] = res_dict['url'].rsplit('/')[-1] + # Resource extras not submitted will be removed from the existing extras # dict new_extras = {}
diff --git a/ckan/tests/lib/dictization/test_model_dictize.py b/ckan/tests/lib/dictization/test_model_dictize.py --- a/ckan/tests/lib/dictization/test_model_dictize.py +++ b/ckan/tests/lib/dictization/test_model_dictize.py @@ -5,7 +5,7 @@ from nose.tools import assert_equal -from ckan.lib.dictization import model_dictize +from ckan.lib.dictization import model_dictize, model_save from ckan import model from ckan.lib import search @@ -401,8 +401,7 @@ def test_package_dictize_resource(self): result = model_dictize.package_dictize(dataset_obj, context) - assert_equal_for_keys(result['resources'][0], resource, - 'name', 'url') + assert_equal_for_keys(result['resources'][0], resource, 'name', 'url') expected_dict = { u'cache_last_updated': None, u'cache_url': None, @@ -422,6 +421,40 @@ def test_package_dictize_resource(self): } self.assert_equals_expected(expected_dict, result['resources'][0]) + def test_package_dictize_resource_upload_and_striped(self): + dataset = factories.Dataset() + resource = factories.Resource(package=dataset['id'], + name='test_pkg_dictize', + url_type='upload', + url='some_filename.csv') + + context = {'model': model, 'session': model.Session} + + result = model_save.resource_dict_save(resource, context) + + expected_dict = { + u'url': u'some_filename.csv', + u'url_type': u'upload' + } + assert expected_dict['url'] == result.url + + def test_package_dictize_resource_upload_with_url_and_striped(self): + dataset = factories.Dataset() + resource = factories.Resource(package=dataset['id'], + name='test_pkg_dictize', + url_type='upload', + url='http://some_filename.csv') + + context = {'model': model, 'session': model.Session} + + result = model_save.resource_dict_save(resource, context) + + expected_dict = { + u'url': u'some_filename.csv', + u'url_type': u'upload' + } + assert expected_dict['url'] == result.url + def test_package_dictize_tags(self): dataset = factories.Dataset(tags=[{'name': 'fish'}]) dataset_obj = model.Package.get(dataset['id'])
Full URL of the resource stored in the DB ### CKAN Version if known (or site URL) 2.6+ Reported in #4070 ### Please describe the expected behaviour When editing resource metadata, we should store the filename in the database, at `resource` table `URL` column. ### Please describe the actual behaviour When editing resource metadata, full URL is saved in the database ### What steps can be taken to reproduce the issue? 1.Go to edit resource page 2.Save the changes I've tested of this occurs on edit dataset and the issue is not reproducible.It occurs only on edit resource. This occurs because we are generating the full url on [reading](https://github.com/ckan/ckan/blob/master/ckan/lib/dictization/model_dictize.py#L110) the resource and it is stored as it in the DB on save
Here what's happening: * When creating the resource, the uploader stores just the file name in the `url` field * This is what gets stored in the database, by `ckan.lib.dictization.model_save.resource_dict_save()` So far so good. Now, when we add a new resource to the same dataset, or edit the existing resource: * `resource_create` and `resource_update` call `package_show` internally to update the whole dataset dict with the new/updated resource and pass it to `package_update`. * `package_show` (correctly) translates the single file name in `url` to a fully qualified URL so it can be displayed in the frontend or the API * But we are passing the dict with fully qualified URLs to `package_update`, which will store them on the database We need to strip the full URL and store just the file name again when storing resources (only for resources where `url_type=upload` of course!). We can do that: 1. At the [`model_save.resource_dict_save`](https://github.com/ckan/ckan/blob/master/ckan/lib/dictization/model_save.py#L16) level 2. At the [`default_update_resource_schema`](https://github.com/ckan/ckan/blob/master/ckan/logic/schema.py#L61) level (validation) Note that the creation of the fully qualified URL is done at the same level of 1 in [`model_dictize.resource_dictize`](https://github.com/ckan/ckan/blob/master/ckan/lib/dictization/model_dictize.py#L100) so perhaps it make sense to be consistent and do it there as well.
2018-08-03T17:55:50
ckan/ckan
4,448
ckan__ckan-4448
[ "4446" ]
0cfd687ccdad83772a851d1526dfdf2c3c3a78f9
diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py --- a/ckan/lib/helpers.py +++ b/ckan/lib/helpers.py @@ -2280,7 +2280,8 @@ def resource_view_get_fields(resource): data = { 'resource_id': resource['id'], - 'limit': 0 + 'limit': 0, + 'include_total': False, } result = logic.get_action('datastore_search')({}, data) diff --git a/ckan/lib/navl/validators.py b/ckan/lib/navl/validators.py --- a/ckan/lib/navl/validators.py +++ b/ckan/lib/navl/validators.py @@ -74,11 +74,13 @@ def ignore(key, data, errors, context): raise StopOnError def default(default_value): + '''When key is missing or value is an empty string or None, replace it with + a default value''' def callable(key, data, errors, context): value = data.get(key) - if not value or value is missing: + if value is None or value == '' or value is missing: data[key] = default_value return callable diff --git a/ckanext/datastore/controller.py b/ckanext/datastore/controller.py --- a/ckanext/datastore/controller.py +++ b/ckanext/datastore/controller.py @@ -143,7 +143,7 @@ def result_page(offs, lim): 'offset': offs, 'sort': '_id', 'records_format': records_format, - 'include_total': 'false', # XXX: default() is broken + 'include_total': False, }) result = result_page(offset, limit)
diff --git a/ckan/tests/legacy/lib/test_navl.py b/ckan/tests/legacy/lib/test_navl.py --- a/ckan/tests/legacy/lib/test_navl.py +++ b/ckan/tests/legacy/lib/test_navl.py @@ -186,21 +186,6 @@ def test_basic_errors(): assert errors == {('__junk',): [u"The input field [('4', 1, '30')] was not expected."], ('1',): [u'Missing value'], ('__extras',): [u'The input field __extras was not expected.']}, errors -def test_default(): - schema = { - "__junk": [ignore], - "__extras": [ignore, default("weee")], - "__before": [ignore], - "__after": [ignore], - "0": [default("default")], - "1": [default("default")], - } - - converted_data, errors = validate_flattened(data, schema) - - assert not errors - assert converted_data == {('1',): 'default', ('0',): '0 value'}, converted_data - def test_flatten(): diff --git a/ckan/tests/lib/navl/test_validators.py b/ckan/tests/lib/navl/test_validators.py --- a/ckan/tests/lib/navl/test_validators.py +++ b/ckan/tests/lib/navl/test_validators.py @@ -8,6 +8,10 @@ import nose.tools import ckan.tests.factories as factories +import ckan.lib.navl.validators as validators + + +eq_ = nose.tools.eq_ def returns_None(function): @@ -222,7 +226,6 @@ def test_ignore_missing_with_value_missing(self): ''' import ckan.lib.navl.dictization_functions as df - import ckan.lib.navl.validators as validators for value in (None, df.missing, 'skip'): @@ -251,8 +254,6 @@ def test_ignore_missing_with_a_value(self): nothing. ''' - import ckan.lib.navl.validators as validators - key = ('key to be validated',) data = factories.validator_data_dict() data[key] = 'value to be validated' @@ -265,3 +266,32 @@ def test_ignore_missing_with_a_value(self): def call_validator(*args, **kwargs): return validators.ignore_missing(*args, **kwargs) call_validator(key=key, data=data, errors=errors, context={}) + + +class TestDefault(object): + def test_key_doesnt_exist(self): + dict_ = {} + validators.default('default_value')('key', dict_, {}, {}) + eq_(dict_, {'key': 'default_value'}) + + def test_value_is_none(self): + dict_ = {'key': None} + validators.default('default_value')('key', dict_, {}, {}) + eq_(dict_, {'key': 'default_value'}) + + def test_value_is_empty_string(self): + dict_ = {'key': ''} + validators.default('default_value')('key', dict_, {}, {}) + eq_(dict_, {'key': 'default_value'}) + + def test_value_is_false(self): + # False is a consciously set value, so should not be changed to the + # default + dict_ = {'key': False} + validators.default('default_value')('key', dict_, {}, {}) + eq_(dict_, {'key': False}) + + def test_already_has_a_value(self): + dict_ = {'key': 'original'} + validators.default('default_value')('key', dict_, {}, {}) + eq_(dict_, {'key': 'original'}) diff --git a/ckanext/datastore/tests/test_search.py b/ckanext/datastore/tests/test_search.py --- a/ckanext/datastore/tests/test_search.py +++ b/ckanext/datastore/tests/test_search.py @@ -100,6 +100,23 @@ def test_all_params_work_with_fields_with_whitespaces(self): result_years = [r['the year'] for r in result['records']] assert_equals(result_years, [2013]) + def test_search_without_total(self): + resource = factories.Resource() + data = { + 'resource_id': resource['id'], + 'force': True, + 'records': [ + {'the year': 2014}, + {'the year': 2013}, + ], + } + result = helpers.call_action('datastore_create', **data) + search_data = { + 'resource_id': resource['id'], + 'include_total': False + } + result = helpers.call_action('datastore_search', **search_data) + assert 'total' not in result class TestDatastoreSearch(DatastoreLegacyTestBase):
In datastore_search, parameter include_total=False doesn't work ### CKAN Version if known (or site URL) master ### Please describe the expected behaviour When calling action function `datastore_search` you can set parameter include_total=False when you don't need the count. This should prevent an SQL query e.g. `SELECT count(*) FROM "47e77d3c-6c77-44f2-bbf4-740b1b28bf5f" ;` Counting rows is notoriously expensive, so we should avoid this when possible. ### Please describe the actual behaviour The parameter didn't change behaviour. The `SELECT count(*)...` occurred anyway. This causes the resource page to display slowly. This is not normally a problem, but when the datastore db is being taxed (e.g. by ckan-xloader loading in data) the resource page for large datasets [can become unresponsive](https://github.com/ckan/ckanext-xloader/issues/41). So it is important to save on these expensive requests where we can. ### What steps can be taken to reproduce the issue? You can see the `SELECT count(*) ...` occurring by turning on sqlalchemy logging, viewing a resource page (e.g. `/dataset/abc/resource/xyz` for a CSV that has been xloaded/datapushed. If you put a pdb breakpoint in `ckan/ckanext/datastore/helpers.py:datastore_dictionary()` you see it calls datastore_search with include_total=False, however in datastore_search you see that gets changed to True when stepping past this line: ``` data_dict, errors = _validate(data_dict, schema, context) ```
2018-09-07T13:25:25
ckan/ckan
4,458
ckan__ckan-4458
[ "4457" ]
16cda2d54d12477fbe321ec3d2677212a7e24911
diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py --- a/ckan/lib/helpers.py +++ b/ckan/lib/helpers.py @@ -69,8 +69,17 @@ 'home': 'home.index', 'about': 'home.about', 'search': 'dataset.search', + 'dataset_read': 'dataset.read', + 'dataset_activity': 'dataset.activity', + 'dataset_groups': 'dataset.groups', 'group_index': 'group.index', - 'organizations_index': 'organization.index' + 'group_about': 'group.about', + 'group_read': 'group.read', + 'group_activity': 'group.activity', + 'organizations_index': 'organization.index', + 'organization_activity': 'organization.activity', + 'organization_read': 'organization.read', + 'organization_about': 'organization.about', }
diff --git a/ckan/tests/lib/test_helpers.py b/ckan/tests/lib/test_helpers.py --- a/ckan/tests/lib/test_helpers.py +++ b/ckan/tests/lib/test_helpers.py @@ -563,6 +563,51 @@ def test_legacy_pylon_routes(self): '<li><a href="/group/">Groups</a></li>' '<li><a href="/about">About</a></li>')) + def test_dataset_navigation_legacy_routes(self): + dataset_name = 'test-dataset' + eq_( + h.build_nav_icon('dataset_read', 'Datasets', id=dataset_name), + '<li><a href="/dataset/test-dataset">Datasets</a></li>' + ) + eq_( + h.build_nav_icon('dataset_groups', 'Groups', id=dataset_name), + '<li><a href="/dataset/groups/test-dataset">Groups</a></li>' + ) + eq_( + h.build_nav_icon('dataset_activity', 'Activity Stream', id=dataset_name), + '<li><a href="/dataset/activity/test-dataset">Activity Stream</a></li>' + ) + + def test_group_navigation_legacy_routes(self): + group_name = 'test-group' + eq_( + h.build_nav_icon('group_read', 'Datasets', id=group_name), + '<li><a href="/group/test-group">Datasets</a></li>' + ) + eq_( + h.build_nav_icon('group_activity', 'Activity Stream', id=group_name), + '<li><a href="/group/activity/test-group">Activity Stream</a></li>' + ) + eq_( + h.build_nav_icon('group_about', 'About', id=group_name), + '<li><a href="/group/about/test-group">About</a></li>' + ) + + def test_organization_navigation_legacy_routes(self): + org_name = 'test-org' + eq_( + h.build_nav_icon('organization_read', 'Datasets', id=org_name), + '<li><a href="/organization/test-org">Datasets</a></li>' + ) + eq_( + h.build_nav_icon('organization_activity', 'Activity Stream', id=org_name), + '<li><a href="/organization/activity/test-org">Activity Stream</a></li>' + ) + eq_( + h.build_nav_icon('organization_about', 'About', id=org_name), + '<li><a href="/organization/about/test-org">About</a></li>' + ) + class TestHelperException(helpers.FunctionalTestBase):
`dataset_read` legacy route missing ### CKAN Version if known (or site URL) master ### Please describe the expected behaviour There is a alias for the `dataset_read` legacy route in CKAN 2.8+, I guess it's missing in [LEGACY_ROUTE_NAMES](https://github.com/ckan/ckan/blob/f3a9c0d99e0bbd404052f49a1ec36a208af634c5/ckan/lib/helpers.py#L68-L74). ### Please describe the actual behaviour When running the tests on my CKAN extension against the current master, it fails with the following error: ``` File "/home/travis/build/opendatazurich/ckanext-stadtzh-theme/ckan/ckan/lib/helpers.py", line 938, in _make_menu_item raise Exception('menu item `%s` cannot be found' % menu_item) Exception: menu item `dataset_read` cannot be found ``` See previous issues https://github.com/ckan/ckan/issues/4346 and https://github.com/ckan/ckan/issues/4066 ### What steps can be taken to reproduce the issue? Create a menu navigation to a dataset detail page, e.g. https://github.com/ckan/ckan/blob/406be328f3af0c07a8e811b2f395cf6bc2cb13ee/ckan/templates/package/read_base.html#L18-L22
I propose to create unit tests for **all** routes we still want to support, otherwise I will have to open issues forever. Alternatively we could change `_make_menu_item()` in master to handle these cases better. The current implementation looks like this: https://github.com/ckan/ckan/blob/7aa42d2ab146a601f0ceefedb376f0f2400a5f01/ckan/lib/helpers.py#L935-L938 Maybe it would be better to call `url_for` instead of checking against `config['routes.named_routes']`
2018-09-13T11:22:22
ckan/ckan
4,489
ckan__ckan-4489
[ "4452" ]
1e65b0644e46ba02d88c18c35c1bfcd2dcfdf2f3
diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py --- a/ckan/config/middleware/flask_app.py +++ b/ckan/config/middleware/flask_app.py @@ -367,8 +367,8 @@ def can_handle_request(self, environ): `origin` can be either 'core' or 'extension' depending on where the route was defined. ''' - urls = self.url_map.bind_to_environ(environ) + try: rule, args = urls.match(return_rule=True) origin = 'core' @@ -376,6 +376,12 @@ def can_handle_request(self, environ): origin = 'extension' log.debug('Flask route match, endpoint: {0}, args: {1}, ' 'origin: {2}'.format(rule.endpoint, args, origin)) + + # Disable built-in flask's ability to prepend site root to + # generated url, as we are going to use locale and existing + # logic is not flexible enough for this purpose + environ['SCRIPT_NAME'] = '' + return (True, self.app_name, origin) except HTTPException: return (False, self.app_name)
diff --git a/ckan/tests/lib/test_helpers.py b/ckan/tests/lib/test_helpers.py --- a/ckan/tests/lib/test_helpers.py +++ b/ckan/tests/lib/test_helpers.py @@ -199,6 +199,16 @@ def test_url_for_qualified_with_root_path_locale_and_script_name_env(self): locale='de') eq_(generated_url, url) + @helpers.set_extra_environ('SCRIPT_NAME', '/my/custom/path') + @helpers.change_config('ckan.site_url', 'http://example.com') + @helpers.change_config('ckan.root_path', '/my/custom/path/{{LANG}}/foo') + def test_url_for_with_root_path_locale_and_script_name_env(self): + url = '/my/custom/path/de/foo/dataset/my_dataset' + generated_url = h.url_for('dataset.read', + id='my_dataset', + locale='de') + eq_(generated_url, url) + class TestHelpersUrlForFlaskandPylons2(BaseUrlFor):
CKAN root path repeated in URL ### CKAN Version if known (or site URL) 2.8.0 ### Please describe the expected behaviour We have a CKAN site that should be accessed via http://192.168.183.128/data The expected CKAN URL should be http://192.168.183.128/data/<ckan_page> ### Please describe the actual behaviour When viewing some of the CKAN pages in a browser, the url root is repeated. Therefore the site cannot be reached. The browser tries to access http://192.168.183.128/data/data/<ckan_page> Examples are the login, logout and admin pages http://192.168.183.128/data/data/user/login http://192.168.183.128/data/data/user/logged_out_redirect http://192.168.183.128/data/data/user/ckan_admin Once logged in, the URLs are correct for dataset, organization, group etc pages. ### What steps can be taken to reproduce the issue? production.ini: ckan.site_url http://192.168.183.128 ckan.root_path = /data/{{LANG}} ckan_default.conf: WSGIScriptAlias /data /etc/ckan/default/apache.wsgi datapusher.conf: WSGIScriptAlias /data /etc/ckan/datapusher.wsgi
2018-10-02T12:01:16
ckan/ckan
4,492
ckan__ckan-4492
[ "4483" ]
1e65b0644e46ba02d88c18c35c1bfcd2dcfdf2f3
diff --git a/ckan/config/routing.py b/ckan/config/routing.py --- a/ckan/config/routing.py +++ b/ckan/config/routing.py @@ -112,19 +112,6 @@ def make_map(): if not hasattr(route, '_ckan_core'): route._ckan_core = False - # CKAN API versioned. - register_list = [ - 'package', 'dataset', 'resource', 'group', 'revision', - 'licenses', 'rating', 'user', 'activity' - ] - register_list_str = '|'.join(register_list) - - # /api ver 1, 2, 3 or none - with SubMapper( - map, controller='api', path_prefix='/api{ver:/1|/2|/3|}', - ver='/1') as m: - m.connect('/search/{register}', action='search') - # /api/util ver 1, 2 or none with SubMapper( map, controller='api', path_prefix='/api{ver:/1|/2|}', diff --git a/ckan/controllers/api.py b/ckan/controllers/api.py --- a/ckan/controllers/api.py +++ b/ckan/controllers/api.py @@ -257,143 +257,6 @@ def action(self, logic_function, ver=None): return self._finish(500, return_dict, content_type='json') return self._finish_ok(return_dict) - def _get_action_from_map(self, action_map, register, subregister): - ''' Helper function to get the action function specified in - the action map''' - - # translate old package calls to use dataset - if register == 'package': - register = 'dataset' - - action = action_map.get((register, subregister)) - if not action: - action = action_map.get(register) - if action: - return get_action(action) - - def search(self, ver=None, register=None): - - log.debug('search %s params: %r', register, request.params) - if register == 'revision': - since_time = None - if 'since_id' in request.params: - id = request.params['since_id'] - if not id: - return self._finish_bad_request( - _(u'No revision specified')) - rev = model.Session.query(model.Revision).get(id) - if rev is None: - return self._finish_not_found( - _(u'There is no revision with id: %s') % id) - since_time = rev.timestamp - elif 'since_time' in request.params: - since_time_str = request.params['since_time'] - try: - since_time = h.date_str_to_datetime(since_time_str) - except ValueError as inst: - return self._finish_bad_request('ValueError: %s' % inst) - else: - return self._finish_bad_request( - _("Missing search term ('since_id=UUID' or " + - " 'since_time=TIMESTAMP')")) - revs = model.Session.query(model.Revision) \ - .filter(model.Revision.timestamp > since_time) \ - .order_by(model.Revision.timestamp) \ - .limit(50) # reasonable enough for a page - return self._finish_ok([rev.id for rev in revs]) - elif register in ['dataset', 'package', 'resource']: - try: - params = MultiDict(self._get_search_params(request.params)) - except ValueError as e: - return self._finish_bad_request( - _('Could not read parameters: %r' % e)) - - # if using API v2, default to returning the package ID if - # no field list is specified - if register in ['dataset', 'package'] and not params.get('fl'): - params['fl'] = 'id' if ver == 2 else 'name' - - try: - if register == 'resource': - query = search.query_for(model.Resource) - - # resource search still uses ckan query parser - options = search.QueryOptions() - for k, v in params.items(): - if (k in search.DEFAULT_OPTIONS.keys()): - options[k] = v - options.update(params) - options.username = c.user - options.search_tags = False - options.return_objects = False - query_fields = MultiDict() - for field, value in params.items(): - field = field.strip() - if field in search.DEFAULT_OPTIONS.keys() or \ - field in IGNORE_FIELDS: - continue - values = [value] - if isinstance(value, list): - values = value - for v in values: - query_fields.add(field, v) - - results = query.run( - query=params.get('q'), - fields=query_fields, - options=options - ) - else: - # For package searches in API v3 and higher, we can pass - # parameters straight to Solr. - if ver in [1, 2]: - # Otherwise, put all unrecognised ones into the q - # parameter - params = search.\ - convert_legacy_parameters_to_solr(params) - query = search.query_for(model.Package) - - # Remove any existing fq param and set the capacity to - # public - if 'fq' in params: - del params['fq'] - params['fq'] = '+capacity:public' - # if callback is specified we do not want to send that to - # the search - if 'callback' in params: - del params['callback'] - results = query.run(params) - return self._finish_ok(results) - except search.SearchError as e: - log.exception(e) - return self._finish_bad_request( - _('Bad search option: %s') % e) - else: - return self._finish_not_found( - _('Unknown register: %s') % register) - - @classmethod - def _get_search_params(cls, request_params): - if 'qjson' in request_params: - try: - qjson_param = request_params['qjson'].replace('\\\\u', '\\u') - params = h.json.loads(qjson_param, encoding='utf8') - except ValueError as e: - raise ValueError(_('Malformed qjson value: %r') - % e) - elif len(request_params) == 1 and \ - len(request_params.values()[0]) < 2 and \ - request_params.keys()[0].startswith('{'): - # e.g. {some-json}='1' or {some-json}='' - params = h.json.loads(request_params.keys()[0], encoding='utf8') - else: - params = request_params - if not isinstance(params, (UnicodeMultiDict, dict)): - msg = _('Request params must be in form ' + - 'of a json encoded dictionary.') - raise ValueError(msg) - return params - @jsonp.jsonpify def user_autocomplete(self): q = request.params.get('q', '') @@ -444,59 +307,6 @@ def organization_autocomplete(self): get_action('organization_autocomplete')(context, data_dict) return organization_list - def dataset_autocomplete(self): - q = request.params.get('incomplete', '') - limit = request.params.get('limit', 10) - package_dicts = [] - if q: - context = {'model': model, 'session': model.Session, - 'user': c.user, 'auth_user_obj': c.userobj} - - data_dict = {'q': q, 'limit': limit} - - package_dicts = get_action('package_autocomplete')(context, - data_dict) - - resultSet = {'ResultSet': {'Result': package_dicts}} - return self._finish_ok(resultSet) - - def tag_autocomplete(self): - q = request.str_params.get('incomplete', '') - q = text_type(urllib.unquote(q), 'utf-8') - limit = request.params.get('limit', 10) - tag_names = [] - if q: - context = {'model': model, 'session': model.Session, - 'user': c.user, 'auth_user_obj': c.userobj} - - data_dict = {'q': q, 'limit': limit} - - tag_names = get_action('tag_autocomplete')(context, data_dict) - - resultSet = { - 'ResultSet': { - 'Result': [{'Name': tag} for tag in tag_names] - } - } - return self._finish_ok(resultSet) - - def format_autocomplete(self): - q = request.params.get('incomplete', '') - limit = request.params.get('limit', 5) - formats = [] - if q: - context = {'model': model, 'session': model.Session, - 'user': c.user, 'auth_user_obj': c.userobj} - data_dict = {'q': q, 'limit': limit} - formats = get_action('format_autocomplete')(context, data_dict) - - resultSet = { - 'ResultSet': { - 'Result': [{'Format': format} for format in formats] - } - } - return self._finish_ok(resultSet) - def munge_package_name(self): name = request.params.get('name') munged_name = munge.munge_name(name) diff --git a/ckan/logic/auth/create.py b/ckan/logic/auth/create.py --- a/ckan/logic/auth/create.py +++ b/ckan/logic/auth/create.py @@ -149,10 +149,12 @@ def user_create(context, data_dict=None): 'create users')} return {'success': True} + def user_invite(context, data_dict): data_dict['id'] = data_dict['group_id'] return group_member_create(context, data_dict) + def _check_group_auth(context, data_dict): '''Has this user got update permission for all of the given groups? If there is a package in the context then ignore that package's groups. @@ -205,14 +207,17 @@ def vocabulary_create(context, data_dict): # sysadmins only return {'success': False} + def activity_create(context, data_dict): # sysadmins only return {'success': False} + def tag_create(context, data_dict): # sysadmins only return {'success': False} + def _group_or_org_member_create(context, data_dict): user = context['user'] group_id = data_dict['id'] @@ -220,12 +225,15 @@ def _group_or_org_member_create(context, data_dict): return {'success': False, 'msg': _('User %s not authorized to add members') % user} return {'success': True} + def organization_member_create(context, data_dict): return _group_or_org_member_create(context, data_dict) + def group_member_create(context, data_dict): return _group_or_org_member_create(context, data_dict) + def member_create(context, data_dict): group = logic_auth.get_group_object(context, data_dict) user = context['user']
diff --git a/ckan/tests/controllers/test_api.py b/ckan/tests/controllers/test_api.py --- a/ckan/tests/controllers/test_api.py +++ b/ckan/tests/controllers/test_api.py @@ -314,87 +314,3 @@ def test_jsonp_does_not_work_on_post_requests(self): eq_(res_dict['success'], True) eq_(sorted(res_dict['result']), sorted([dataset1['name'], dataset2['name']])) - - -class TestRevisionSearch(helpers.FunctionalTestBase): - - # Error cases - - def test_no_search_term(self): - app = self._get_test_app() - response = app.get('/api/search/revision', status=400) - assert_in('Bad request - Missing search term', response.body) - - def test_no_search_term_api_v2(self): - app = self._get_test_app() - response = app.get('/api/2/search/revision', status=400) - assert_in('Bad request - Missing search term', response.body) - - def test_date_instead_of_revision(self): - app = self._get_test_app() - response = app.get('/api/search/revision' - '?since_id=2010-01-01T00:00:00', status=404) - assert_in('Not found - There is no revision', response.body) - - def test_date_invalid(self): - app = self._get_test_app() - response = app.get('/api/search/revision' - '?since_time=2010-02-31T00:00:00', status=400) - assert_in('Bad request - ValueError: day is out of range for month', - response.body) - - def test_no_value(self): - app = self._get_test_app() - response = app.get('/api/search/revision?since_id=', status=400) - assert_in('Bad request - No revision specified', response.body) - - def test_revision_doesnt_exist(self): - app = self._get_test_app() - response = app.get('/api/search/revision?since_id=1234', status=404) - assert_in('Not found - There is no revision', response.body) - - def test_revision_doesnt_exist_api_v2(self): - app = self._get_test_app() - response = app.get('/api/2/search/revision?since_id=1234', status=404) - assert_in('Not found - There is no revision', response.body) - - # Normal usage - - @classmethod - def _create_revisions(cls, num_revisions): - rev_ids = [] - for i in xrange(num_revisions): - rev = model.repo.new_revision() - rev.id = text_type(i) - model.Session.commit() - rev_ids.append(rev.id) - return rev_ids - - def test_revision_since_id(self): - rev_ids = self._create_revisions(4) - app = self._get_test_app() - - response = app.get('/api/2/search/revision?since_id=%s' % rev_ids[1]) - - res = json.loads(response.body) - assert_equal(res, rev_ids[2:]) - - def test_revision_since_time(self): - rev_ids = self._create_revisions(4) - app = self._get_test_app() - - rev1 = model.Session.query(model.Revision).get(rev_ids[1]) - response = app.get('/api/2/search/revision?since_time=%s' - % rev1.timestamp.isoformat()) - - res = json.loads(response.body) - assert_equal(res, rev_ids[2:]) - - def test_revisions_returned_are_limited(self): - rev_ids = self._create_revisions(55) - app = self._get_test_app() - - response = app.get('/api/2/search/revision?since_id=%s' % rev_ids[1]) - - res = json.loads(response.body) - assert_equal(res, rev_ids[2:52]) # i.e. limited to 50 diff --git a/ckan/tests/legacy/functional/api/test_package_search.py b/ckan/tests/legacy/functional/api/test_package_search.py --- a/ckan/tests/legacy/functional/api/test_package_search.py +++ b/ckan/tests/legacy/functional/api/test_package_search.py @@ -1,17 +1,12 @@ # encoding: utf-8 -from nose.tools import assert_raises -from nose.plugins.skip import SkipTest - from urllib import quote -from ckan import plugins import ckan.lib.search as search from ckan.tests.legacy import setup_test_search_index from ckan.tests.legacy.functional.api.base import * from ckan.tests.legacy import TestController as ControllerTestCase -from ckan.controllers.api import ApiController -from webob.multidict import UnicodeMultiDict + class PackageSearchApiTestCase(ApiTestCase, ControllerTestCase): @@ -31,7 +26,7 @@ def setup_class(self): 'geographic_coverage':'England, Wales'}, } CreateTestData.create_arbitrary(self.package_fixture_data) - self.base_url = self.offset('/search/dataset') + self.base_url = self.offset('/action/package_search') @classmethod def teardown_class(cls): @@ -39,60 +34,23 @@ def teardown_class(cls): search.clear_all() def assert_results(self, res_dict, expected_package_names): - expected_pkgs = [self.package_ref_from_name(expected_package_name) \ - for expected_package_name in expected_package_names] - assert_equal(set(res_dict['results']), set(expected_pkgs)) - - def test_00_read_search_params(self): - def check(request_params, expected_params): - params = ApiController._get_search_params(request_params) - assert_equal(params, expected_params) - # uri parameters - check(UnicodeMultiDict({'q': '', 'ref': 'boris'}), - {"q": "", "ref": "boris"}) - # uri json - check(UnicodeMultiDict({'qjson': '{"q": "", "ref": "boris"}'}), - {"q": "", "ref": "boris"}) - # posted json - check(UnicodeMultiDict({'{"q": "", "ref": "boris"}': u'1'}), - {"q": "", "ref": "boris"}) - check(UnicodeMultiDict({'{"q": "", "ref": "boris"}': u''}), - {"q": "", "ref": "boris"}) - # no parameters - check(UnicodeMultiDict({}), - {}) - - def test_00_read_search_params_with_errors(self): - def check_error(request_params): - assert_raises(ValueError, ApiController._get_search_params, request_params) - # uri json - check_error(UnicodeMultiDict({'qjson': '{"q": illegal json}'})) - # posted json - check_error(UnicodeMultiDict({'{"q": illegal json}': u'1'})) + result = res_dict['result']['results'][0] + assert_equal(result['name'], expected_package_names) def test_01_uri_q(self): offset = self.base_url + '?q=%s' % self.package_fixture_data['name'] res = self.app.get(offset, status=200) res_dict = self.data_from_res(res) - self.assert_results(res_dict, ['testpkg']) - assert res_dict['count'] == 1, res_dict['count'] + self.assert_results(res_dict, 'testpkg') + assert res_dict['result']['count'] == 1, res_dict['result']['count'] def test_02_post_q(self): offset = self.base_url query = {'q':'testpkg'} res = self.app.post(offset, params=query, status=200) res_dict = self.data_from_res(res) - self.assert_results(res_dict, ['testpkg']) - assert res_dict['count'] == 1, res_dict['count'] - - def test_03_uri_qjson(self): - query = {'q': self.package_fixture_data['name']} - json_query = self.dumps(query) - offset = self.base_url + '?qjson=%s' % json_query - res = self.app.get(offset, status=200) - res_dict = self.data_from_res(res) - self.assert_results(res_dict, ['testpkg']) - assert res_dict['count'] == 1, res_dict['count'] + self.assert_results(res_dict, 'testpkg') + assert res_dict['result']['count'] == 1, res_dict['result']['count'] def test_04_post_json(self): query = {'q': self.package_fixture_data['name']} @@ -100,71 +58,40 @@ def test_04_post_json(self): offset = self.base_url res = self.app.post(offset, params=json_query, status=200) res_dict = self.data_from_res(res) - self.assert_results(res_dict, ['testpkg']) - assert res_dict['count'] == 1, res_dict['count'] - - def test_05_uri_json_tags(self): - query = {'q': 'annakarenina tags:russian tags:tolstoy'} - json_query = self.dumps(query) - offset = self.base_url + '?qjson=%s' % json_query - res = self.app.get(offset, status=200) - res_dict = self.data_from_res(res) - self.assert_results(res_dict, [u'annakarenina']) - assert res_dict['count'] == 1, res_dict - - def test_05_uri_json_tags_multiple(self): - query = {'q': 'tags:russian tags:tolstoy'} - json_query = self.dumps(query) - offset = self.base_url + '?qjson=%s' % json_query - res = self.app.get(offset, status=200) - res_dict = self.data_from_res(res) - self.assert_results(res_dict, [u'annakarenina']) - assert res_dict['count'] == 1, res_dict + self.assert_results(res_dict, 'testpkg') + assert res_dict['result']['count'] == 1, res_dict['result']['count'] def test_06_uri_q_tags(self): query = webhelpers.util.html_escape('annakarenina tags:russian tags:tolstoy') offset = self.base_url + '?q=%s' % query res = self.app.get(offset, status=200) res_dict = self.data_from_res(res) - self.assert_results(res_dict, [u'annakarenina']) - assert res_dict['count'] == 1, res_dict['count'] - - def test_08_uri_qjson_malformed(self): - offset = self.base_url + '?qjson="q":""' # user forgot the curly braces - res = self.app.get(offset, status=400) - self.assert_json_response(res, 'Bad request - Could not read parameters') + self.assert_results(res_dict, 'annakarenina') + assert res_dict['result']['count'] == 1, res_dict['count'] def test_09_just_tags(self): offset = self.base_url + '?q=tags:russian' res = self.app.get(offset, status=200) res_dict = self.data_from_res(res) - assert res_dict['count'] == 2, res_dict + assert res_dict['result']['count'] == 2, res_dict def test_10_multiple_tags(self): offset = self.base_url + '?q=tags:tolstoy tags:russian' res = self.app.get(offset, status=200) res_dict = self.data_from_res(res) - assert res_dict['count'] == 1, res_dict - - def test_12_all_packages_qjson(self): - query = {'q': ''} - json_query = self.dumps(query) - offset = self.base_url + '?qjson=%s' % json_query - res = self.app.get(offset, status=200) - res_dict = self.data_from_res(res) - assert_equal(res_dict['count'], 3) + assert res_dict['result']['count'] == 1, res_dict def test_12_all_packages_q(self): offset = self.base_url + '?q=""' res = self.app.get(offset, status=200) res_dict = self.data_from_res(res) - assert_equal(res_dict['count'], 3) + assert_equal(res_dict['result']['count'], 3) def test_12_all_packages_no_q(self): offset = self.base_url res = self.app.get(offset, status=200) res_dict = self.data_from_res(res) - assert_equal(res_dict['count'], 3) + assert_equal(res_dict['result']['count'], 3) def test_12_filter_by_openness(self): offset = self.base_url + '?filter_by_openness=1' @@ -203,95 +130,6 @@ def teardown_class(cls): model.repo.rebuild_db() search.clear_all() - def test_07_uri_qjson_tags(self): - query = {'q': '', 'tags':['tolstoy']} - json_query = self.dumps(query) - offset = self.base_url + '?qjson=%s' % json_query - res = self.app.get(offset, status=200) - res_dict = self.data_from_res(res) - self.assert_results(res_dict, [u'annakarenina']) - assert res_dict['count'] == 1, res_dict - - def test_07_uri_qjson_tags_with_flexible_query(self): - query = {'q': '', 'tags':['Flexible \u30a1']} - json_query = self.dumps(query) - offset = self.base_url + '?qjson=%s' % json_query - res = self.app.get(offset, status=200) - res_dict = self.data_from_res(res) - self.assert_results(res_dict, [u'annakarenina', u'warandpeace']) - assert res_dict['count'] == 2, res_dict - - def test_07_uri_qjson_tags_multiple(self): - query = {'q': '', 'tags':['tolstoy', 'russian', u'Flexible \u30a1']} - json_query = self.dumps(query) - offset = self.base_url + '?qjson=%s' % json_query - print(offset) - res = self.app.get(offset, status=200) - res_dict = self.data_from_res(res) - self.assert_results(res_dict, [u'annakarenina']) - assert res_dict['count'] == 1, res_dict - - def test_07_uri_qjson_tags_reverse(self): - query = {'q': '', 'tags':['russian']} - json_query = self.dumps(query) - offset = self.base_url + '?qjson=%s' % json_query - res = self.app.get(offset, status=200) - res_dict = self.data_from_res(res) - self.assert_results(res_dict, [u'annakarenina', u'warandpeace']) - assert res_dict['count'] == 2, res_dict - - def test_07_uri_qjson_extras(self): - # TODO: solr is not currently set up to allow partial matches - # and extras are not saved as multivalued so this - # test will fail. Make extras multivalued or remove? - raise SkipTest() - - query = {"geographic_coverage":"England"} - json_query = self.dumps(query) - offset = self.base_url + '?qjson=%s' % json_query - res = self.app.get(offset, status=200) - res_dict = self.data_from_res(res) - self.assert_results(res_dict, ['testpkg']) - assert res_dict['count'] == 1, res_dict - - def test_07_uri_qjson_extras_2(self): - query = {"national_statistic":"yes"} - json_query = self.dumps(query) - offset = self.base_url + '?qjson=%s' % json_query - res = self.app.get(offset, status=200) - res_dict = self.data_from_res(res) - self.assert_results(res_dict, ['testpkg']) - assert res_dict['count'] == 1, res_dict - - def test_08_all_fields(self): - rating = model.Rating(user_ip_address=u'123.1.2.3', - package=self.anna, - rating=3.0) - model.Session.add(rating) - model.repo.commit_and_remove() - - query = {'q': 'russian', 'all_fields': 1} - json_query = self.dumps(query) - offset = self.base_url + '?qjson=%s' % json_query - res = self.app.get(offset, status=200) - res_dict = self.data_from_res(res) - assert res_dict['count'] == 2, res_dict - for rec in res_dict['results']: - if rec['name'] == 'annakarenina': - anna_rec = rec - break - assert anna_rec['name'] == 'annakarenina', res_dict['results'] - assert anna_rec['title'] == 'A Novel By Tolstoy', anna_rec['title'] - assert anna_rec['license_id'] == u'other-open', anna_rec['license_id'] - assert len(anna_rec['tags']) == 3, anna_rec['tags'] - for expected_tag in ['russian', 'tolstoy', u'Flexible \u30a1']: - assert expected_tag in anna_rec['tags'], anna_rec['tags'] - - # try alternative syntax - offset = self.base_url + '?q=russian&all_fields=1' - res2 = self.app.get(offset, status=200) - assert_equal(res2.body, res.body) - def test_08_all_fields_syntax_error(self): offset = self.base_url + '?all_fields=should_be_boolean' # invalid all_fields value res = self.app.get(offset, status=400) @@ -331,139 +169,47 @@ def test_10_many_tags_with_ampersand(self): res_dict = self.data_from_res(res) assert res_dict['count'] == 1, res_dict - def test_11_pagination_limit(self): - offset = self.base_url + '?all_fields=1&q=tags:russian&limit=1&order_by=name' - res = self.app.get(offset, status=200) - res_dict = self.data_from_res(res) - assert res_dict['count'] == 2, res_dict - assert len(res_dict['results']) == 1, res_dict - assert res_dict['results'][0]['name'] == 'annakarenina', res_dict['results'][0]['name'] - - def test_11_pagination_offset_limit(self): - offset = self.base_url + '?all_fields=1&q=tags:russian&offset=1&limit=1&order_by=name' - res = self.app.get(offset, status=200) - res_dict = self.data_from_res(res) - assert res_dict['count'] == 2, res_dict - assert len(res_dict['results']) == 1, res_dict - assert res_dict['results'][0]['name'] == 'warandpeace', res_dict['results'][0]['name'] - - def test_11_pagination_syntax_error(self): - offset = self.base_url + '?all_fields=1&q="tags:russian"&start=should_be_integer&rows=1&order_by=name' # invalid offset value - res = self.app.get(offset, status=400) - print(res.body) - assert('should_be_integer' in res.body) - def test_13_just_groups(self): offset = self.base_url + '?groups=roger' res = self.app.get(offset, status=200) res_dict = self.data_from_res(res) - assert res_dict['count'] == 1, res_dict + assert res_dict['result']['count'] == 1, res_dict def test_14_empty_parameter_ignored(self): offset = self.base_url + '?groups=roger&title=' res = self.app.get(offset, status=200) res_dict = self.data_from_res(res) - assert res_dict['count'] == 1, res_dict + assert res_dict['result']['count'] == 1, res_dict class TestPackageSearchApi3(Api3TestCase, PackageSearchApiTestCase): '''Here are tests with URIs in specifically SOLR syntax.''' - def test_07_uri_qjson_tags(self): - query = {'q': 'tags:tolstoy'} - json_query = self.dumps(query) - offset = self.base_url + '?qjson=%s' % json_query - res = self.app.get(offset, status=200) - res_dict = self.data_from_res(res) - self.assert_results(res_dict, [u'annakarenina']) - assert res_dict['count'] == 1, res_dict - - def test_07_uri_qjson_tags_with_unicode(self): - query = {'q': u'tags:"Flexible \u30a1"'} - json_query = self.dumps(query) - offset = self.base_url + '?qjson=%s' % json_query - res = self.app.get(offset, status=200) - res_dict = self.data_from_res(res) - self.assert_results(res_dict, [u'annakarenina', u'warandpeace']) - assert res_dict['count'] == 2, res_dict - - def test_07_uri_qjson_tags_multiple(self): - query = {'q': 'tags:tolstoy tags:russian'} - json_query = self.dumps(query) - offset = self.base_url + '?qjson=%s' % json_query - print(offset) - res = self.app.get(offset, status=200) - res_dict = self.data_from_res(res) - self.assert_results(res_dict, [u'annakarenina']) - assert res_dict['count'] == 1, res_dict - - def test_07_uri_qjson_tags_reverse(self): - query = {'q': 'tags:russian'} - json_query = self.dumps(query) - offset = self.base_url + '?qjson=%s' % json_query - res = self.app.get(offset, status=200) - res_dict = self.data_from_res(res) - self.assert_results(res_dict, [u'annakarenina', u'warandpeace']) - assert res_dict['count'] == 2, res_dict - - def test_07_uri_qjson_extras_2(self): - query = {'q': "national_statistic:yes"} - json_query = self.dumps(query) - offset = self.base_url + '?qjson=%s' % json_query - res = self.app.get(offset, status=200) - res_dict = self.data_from_res(res) - self.assert_results(res_dict, ['testpkg']) - assert res_dict['count'] == 1, res_dict - - def test_08_all_fields(self): - query = {'q': 'russian', 'fl': '*'} - json_query = self.dumps(query) - offset = self.base_url + '?qjson=%s' % json_query - res = self.app.get(offset, status=200) - res_dict = self.data_from_res(res) - assert res_dict['count'] == 2, res_dict - for rec in res_dict['results']: - if rec['name'] == 'annakarenina': - anna_rec = rec - break - assert anna_rec['name'] == 'annakarenina', res_dict['results'] - assert anna_rec['title'] == 'A Novel By Tolstoy', anna_rec['title'] - assert anna_rec['license_id'] == u'other-open', anna_rec['license_id'] - assert len(anna_rec['tags']) == 3, anna_rec['tags'] - for expected_tag in ['russian', 'tolstoy', u'Flexible \u30a1']: - assert expected_tag in anna_rec['tags'] - - # try alternative syntax - offset = self.base_url + '?q=russian&fl=*' - res2 = self.app.get(offset, status=200) - assert_equal(res2.body, res.body) - def test_09_just_tags(self): offset = self.base_url + '?q=tags:russian&fl=*' res = self.app.get(offset, status=200) res_dict = self.data_from_res(res) - assert res_dict['count'] == 2, res_dict + assert res_dict['result']['count'] == 2, res_dict def test_11_pagination_limit(self): offset = self.base_url + '?fl=*&q=tags:russian&rows=1&sort=name asc' res = self.app.get(offset, status=200) res_dict = self.data_from_res(res) - assert res_dict['count'] == 2, res_dict - assert len(res_dict['results']) == 1, res_dict - assert res_dict['results'][0]['name'] == 'annakarenina', res_dict['results'][0]['name'] + assert res_dict['result']['count'] == 2, res_dict + assert len(res_dict['result']['results']) == 1, res_dict + self.assert_results(res_dict, 'annakarenina') def test_11_pagination_offset_limit(self): offset = self.base_url + '?fl=*&q=tags:russian&start=1&rows=1&sort=name asc' res = self.app.get(offset, status=200) res_dict = self.data_from_res(res) - assert res_dict['count'] == 2, res_dict - assert len(res_dict['results']) == 1, res_dict - assert res_dict['results'][0]['name'] == 'warandpeace', res_dict['results'][0]['name'] + assert res_dict['result']['count'] == 2, res_dict + assert len(res_dict['result']['results']) == 1, res_dict + self.assert_results(res_dict, 'warandpeace') - def test_11_pagination_syntax_error(self): + def test_11_pagination_validation_error(self): offset = self.base_url + '?fl=*&q=tags:russian&start=should_be_integer&rows=1&sort=name asc' # invalid offset value - res = self.app.get(offset, status=400) - print(res.body) - assert('should_be_integer' in res.body) + res = self.app.get(offset, status=409) + assert('Validation Error' in res.body) def test_12_v1_or_v2_syntax(self): offset = self.base_url + '?all_fields=1' @@ -474,4 +220,4 @@ def test_13_just_groups(self): offset = self.base_url + '?q=groups:roger' res = self.app.get(offset, status=200) res_dict = self.data_from_res(res) - assert res_dict['count'] == 1, res_dict + assert res_dict['result']['count'] == 1, res_dict diff --git a/ckan/tests/legacy/test_coding_standards.py b/ckan/tests/legacy/test_coding_standards.py --- a/ckan/tests/legacy/test_coding_standards.py +++ b/ckan/tests/legacy/test_coding_standards.py @@ -835,7 +835,6 @@ class TestBadExceptions(object): # and so should be translated. NASTY_EXCEPTION_BLACKLIST_FILES = [ - 'ckan/controllers/api.py', 'ckan/controllers/user.py', 'ckan/lib/mailer.py', 'ckan/logic/action/create.py',
Remove legacy Search API ### CKAN Version if known (or site URL) Can we officially deprecate the legacy [Search API and Utils APIs](https://docs.ckan.org/en/latest/api/legacy-api.html)? These was described as "legacy API"s since CKAN 2.3 (here)[https://github.com/ckan/ckan/commit/254fca2d43ccacbe674df2da42aba83897dcdb96#diff-b4e5718590c95267775a87dafc922c76). However they have not been marked as deprecated in the changelog. These are the APIs: * `/api/search/dataset` / `/api/search/package` (replaced by `package_search`) * `/api/search/resource` (replaced by `resource_search`) * `/api/search/revision` (revisions are deprecated) * `/api/tag_counts` (can be done with `package_search facet.field='tags'`) * `/api/util/dataset/autocomplete` (replaced by `package_autocomplete`) * `/api/util/tag/autocomplete` (replaced by `tag_autocomplete`) * `/api/util/resource/format_autocomplete` (replaced by `format_autocomplete`) * `/api/util/dataset/munge_name` * `/api/util/dataset/munge_title_to_name` * `/api/util/tag/munge` I can't see any replacements for the munge functions and I suspect they are still useful to anyone replacing the CKAN front-end. Should we turn these into action funcs? (We [got rid of the REST API `/api/rest/*` in 2.8](https://github.com/ckan/ckan/pull/4069), having been marked as deprecated in the 2.7 changelog)
That sounds very sensible. I think that that the munge functions can be easily turned into actions as you suggest, and the rest we should just remove.
2018-10-08T12:46:19
ckan/ckan
4,505
ckan__ckan-4505
[ "4504" ]
e70f6e04d28a7284b722cbc67e1ff0437e39fa4b
diff --git a/ckan/views/api.py b/ckan/views/api.py --- a/ckan/views/api.py +++ b/ckan/views/api.py @@ -44,7 +44,8 @@ def _finish(status_int, response_data=None, :param status_int: The HTTP status code to return :type status_int: int :param response_data: The body of the response - :type response_data: object if content_type is `text`, a string otherwise + :type response_data: object if content_type is `text` or `json`, + a string otherwise :param content_type: One of `text`, `html` or `json`. Defaults to `text` :type content_type: string :param headers: Extra headers to serve with the response @@ -82,7 +83,8 @@ def _finish_ok(response_data=None, calling this method will prepare the response. :param response_data: The body of the response - :type response_data: object if content_type is `text`, a string otherwise + :type response_data: object if content_type is `text` or `json`, + a string otherwise :param content_type: One of `text`, `html` or `json`. Defaults to `json` :type content_type: string :param resource_location: Specify this if a new resource has just been @@ -470,7 +472,7 @@ def i18n_js_translations(lang, ver=API_REST_DEFAULT_VERSION): u'base', u'i18n', u'{0}.js'.format(lang))) if not os.path.exists(source): return u'{}' - translations = open(source, u'r').read() + translations = json.load(open(source, u'r')) return _finish_ok(translations)
i18n API returns JSON-encoded JSON ### CKAN Version if known (or site URL) - Correct: https://demo.ckan.org/api/i18n/fi - Incorrect: https://beta.ckan.org/api/i18n/fi Problem probably stems from changes [here](https://github.com/ckan/ckan/blob/master/ckan/views/api.py#L467). ### Please describe the expected behaviour The API should return JSON. ### Please describe the actual behaviour The API returns JSON-encoded JSON. This breaks JavaScript translations, as the returned object deserializes into a string rather than an object. ### What steps can be taken to reproduce the issue? Call the API
[This](https://github.com/ckan/ckan/blob/master/ckan/views/api.py#L47) states `response_data` should be a string when `content_type` is not `text`, but [this](https://github.com/ckan/ckan/blob/master/ckan/views/api.py#L63) calls `json.dumps` on it if it's supposed to be JSON. The calling code conforms to the function documentation, but the function obviously expects a non-serialized value there.
2018-10-17T09:09:17