[ckan-changes] commit/ckan: 5 new changesets

Bitbucket commits-noreply at bitbucket.org
Thu Jul 21 17:29:18 UTC 2011


5 new changesets in ckan:

http://bitbucket.org/okfn/ckan/changeset/d7fb464a1d3f/
changeset:   d7fb464a1d3f
branch:      feature-1229-db-out-of-controllers
user:        amercader
date:        2011-07-20 15:56:47
summary:     Remove function as it is no longer used
affected #:  1 file (584 bytes)

--- a/ckan/controllers/package.py	Wed Jul 20 12:51:50 2011 +0100
+++ b/ckan/controllers/package.py	Wed Jul 20 14:56:47 2011 +0100
@@ -717,23 +717,6 @@
 
         return render('package/authz.html')
 
-
-
-
-    def rate(self, id):
-        package_name = id
-        package = model.Package.get(package_name)
-        if package is None:
-            abort(404, gettext('Package Not Found'))
-        self._clear_pkg_cache(package)
-        rating = request.params.get('rating', '')
-        if rating:
-            try:
-                ckan.rating.set_my_rating(c, package, rating)
-            except ckan.rating.RatingValueException, e:
-                abort(400, gettext('Rating value invalid'))
-        h.redirect_to(controller='package', action='read', id=package_name, rating=str(rating))
-
     def autocomplete(self):
         q = unicode(request.params.get('q', ''))
         if not len(q): 


http://bitbucket.org/okfn/ckan/changeset/7f062628016c/
changeset:   7f062628016c
branch:      feature-1229-db-out-of-controllers
user:        amercader
date:        2011-07-20 17:45:56
summary:     [logic] Move package history and history_ajax
affected #:  4 files (948 bytes)

--- a/ckan/controllers/package.py	Wed Jul 20 14:56:47 2011 +0100
+++ b/ckan/controllers/package.py	Wed Jul 20 16:45:56 2011 +0100
@@ -257,39 +257,48 @@
                 params['diff_entity'] = 'package'
                 h.redirect_to(controller='revision', action='diff', **params)
 
-        c.pkg = model.Package.get(id)
-        if not c.pkg:
+        context = {'model': model, 'session': model.Session,
+                   'user': c.user or c.author,
+                   'extras_as_string': True,}
+        data_dict = {'id':id}
+        try:
+            c.pkg_dict = get.package_show(context, data_dict)
+            c.pkg_revisions = get.package_revision_list(context, data_dict)
+        except NotAuthorized:
+            abort(401, _('Unauthorized to read package %s') % '')
+        except NotFound:
             abort(404, _('Package not found'))
+
         format = request.params.get('format', '')
         if format == 'atom':
             # Generate and return Atom 1.0 document.
             from webhelpers.feedgenerator import Atom1Feed
             feed = Atom1Feed(
                 title=_(u'CKAN Package Revision History'),
-                link=h.url_for(controller='revision', action='read', id=c.pkg.name),
-                description=_(u'Recent changes to CKAN Package: ') + (c.pkg.title or ''),
+                link=h.url_for(controller='revision', action='read', id=c.pkg_dict['name']),
+                description=_(u'Recent changes to CKAN Package: ') + (c.pkg_dict['title'] or ''),
                 language=unicode(get_lang()),
             )
-            for revision, obj_rev in c.pkg.all_related_revisions:
+            for revision_dict in c.pkg_revisions:
                 try:
                     dayHorizon = int(request.params.get('days'))
                 except:
                     dayHorizon = 30
                 try:
-                    dayAge = (datetime.now() - revision.timestamp).days
+                    dayAge = (datetime.now() - revision_dict['timestamp']).days
                 except:
                     dayAge = 0
                 if dayAge >= dayHorizon:
                     break
-                if revision.message:
-                    item_title = u'%s' % revision.message.split('\n')[0]
+                if revision_dict['message']:
+                    item_title = u'%s' % revision_dict['message'].split('\n')[0]
                 else:
-                    item_title = u'%s' % revision.id
-                item_link = h.url_for(controller='revision', action='read', id=revision.id)
+                    item_title = u'%s' % revision_dict['id']
+                item_link = h.url_for(controller='revision', action='read', id=revision_dict['id'])
                 item_description = _('Log message: ')
-                item_description += '%s' % (revision.message or '')
-                item_author_name = revision.author
-                item_pubdate = revision.timestamp
+                item_description += '%s' % (revision_dict['message'] or '')
+                item_author_name = revision_dict['author']
+                item_pubdate = datetime.datetime.strptime(revision_dict['timestamp'], '%Y-%m-%dT%H:%M:%S.%f')
                 feed.add_item(
                     title=item_title,
                     link=item_link,
@@ -299,7 +308,6 @@
                 )
             feed.content_type = 'application/atom+xml'
             return feed.writeString('utf-8')
-        c.pkg_revisions = c.pkg.all_related_revisions
         return render('package/history.html')
 
     def new(self, data=None, errors=None, error_summary=None):
@@ -387,21 +395,31 @@
 
     def history_ajax(self, id):
 
-        pkg = model.Package.get(id)
+        context = {'model': model, 'session': model.Session,
+                   'user': c.user or c.author,
+                   'extras_as_string': True,}
+        data_dict = {'id':id}
+        try:
+            pkg_revisions = get.package_revision_list(context, data_dict)
+        except NotAuthorized:
+            abort(401, _('Unauthorized to read package %s') % '')
+        except NotFound:
+            abort(404, _('Package not found'))
+
+
         data = []
         approved = False
-        for num, (revision, revision_obj) in enumerate(pkg.all_related_revisions):
-            if not approved and revision.approved_timestamp:
+        for num, revision in enumerate(pkg_revisions):
+            if not approved and revision['approved_timestamp']:
                 current_approved, approved = True, True
             else:
                 current_approved = False
             
-            data.append({'revision_id': revision.id,
-                         'message': revision.message,
-                         'timestamp': format_datetime(revision.timestamp, 
-                                                      locale=(get_lang() or ['en'])[0]),
-                         'author': revision.author,
-                         'approved': bool(revision.approved_timestamp),
+            data.append({'revision_id': revision['id'],
+                         'message': revision['message'],
+                         'timestamp': revision['timestamp'],
+                         'author': revision['author'],
+                         'approved': bool(revision['approved_timestamp']),
                          'current_approved': current_approved})
                 
         response.headers['Content-Type'] = 'application/json;charset=utf-8'


--- a/ckan/model/__init__.py	Wed Jul 20 14:56:47 2011 +0100
+++ b/ckan/model/__init__.py	Wed Jul 20 16:45:56 2011 +0100
@@ -232,6 +232,7 @@
         ('timestamp', strftimestamp(revision.timestamp)),
         ('message', revision.message),
         ('author', revision.author),
+        ('approved_timestamp',revision.approved_timestamp)
         ))
     if include_packages:
         revision_dict['packages'] = [getattr(pkg, ref_package_by) \


--- a/ckan/templates/package/history.html	Wed Jul 20 14:56:47 2011 +0100
+++ b/ckan/templates/package/history.html	Wed Jul 20 16:45:56 2011 +0100
@@ -1,8 +1,9 @@
 <html xmlns:py="http://genshi.edgewall.org/"
+  xmlns:i18n="http://genshi.edgewall.org/i18n"
   xmlns:xi="http://www.w3.org/2001/XInclude"
   py:strip="">
   
-  <py:def function="page_title">${c.pkg.title or c.pkg.name} - Data Packages - History</py:def>
+  <py:def function="page_title">${c.pkg_dict.get('title', c.pkg_dict['name'])} - Data Packages - History</py:def><!-- Sidebar --><py:match path="primarysidebar">
@@ -10,8 +11,8 @@
         <h4>Updates</h4><p class="atom-feed-link package-history-link"><a
-            href="${url(controller='package', action='history', id=c.pkg.name, format='atom', days=7)}"
-            title="${g.site_title} - Package History - ${c.pkg.name}">
+            href="${url(controller='package', action='history', id=c.pkg_dict['name'], format='atom', days=7)}"
+            title="${g.site_title} - Package History - ${c.pkg_dict['name']}">
             Subscribe »</a></p></li>
@@ -21,7 +22,7 @@
 
     <!-- Title --><h2 class="head">
-      ${c.pkg.title} - History
+        ${c.pkg_dict.get('title', c.pkg_dict['name'])} - History
     </h2><h3>Revisions</h3>
@@ -34,24 +35,24 @@
         Error: ${c.error}
       </h3>
       
-      <input type="hidden" name="pkg_name" value="${c.pkg.name}"/>
+      <input type="hidden" name="pkg_name" value="${c.pkg_dict['name']}"/><table><tr><th></th><th>Revision</th><th>Timestamp</th><th>Author</th><th>Log Message</th></tr>
-        <py:for each="index, rev in enumerate([rev for rev, obj_revs in c.pkg_revisions])">
+        <py:for each="index, rev in enumerate(c.pkg_revisions)"><tr><td nowrap="nowrap">
               ${h.radio("selected1", rev.id, checked=(index == 0))}
               ${h.radio("selected2", rev.id, checked=(index == len(c.pkg_revisions)-1))}
             </td><td>
-              <a href="${h.url_for(controller='revision',action='read',id=rev.id)}">${rev.id}</a>
+              <a href="${h.url_for(controller='revision',action='read',id=rev['id'])}">${rev['id']}</a></td>
-            <td>${rev.timestamp}</td>
-            <td>${h.linked_user(rev.author)}</td>
-            <td>${rev.message}</td>
+            <td>${rev['timestamp']}</td>
+            <td>${h.linked_user(rev['author'])}</td>
+            <td>${rev['message']}</td></tr></py:for></table>
@@ -61,7 +62,7 @@
 
   <py:def function="optional_feed"><link rel="alternate" type="application/atom+xml" title="Package History"
-    href="${url(controller='package', action='history', id=c.pkg.name, format='atom', days=7)}" />
+    href="${url(controller='package', action='history', id=c.pkg_dict['name'], format='atom', days=7)}" /></py:def><xi:include href="layout.html" />


--- a/ckan/tests/functional/api/model/test_package.py	Wed Jul 20 14:56:47 2011 +0100
+++ b/ckan/tests/functional/api/model/test_package.py	Wed Jul 20 16:45:56 2011 +0100
@@ -476,7 +476,7 @@
         res = self.app.get(self.offset('/rest/package/%s/revisions' % 'annakarenina'))
         revisions = res.json
         assert len(revisions) == 1, len(revisions)
-        expected_keys = set(('id', 'message', 'author', 'timestamp'))
+        expected_keys = set(('id', 'message', 'author', 'timestamp', 'approved_timestamp'))
         keys = set(revisions[0].keys())
         assert_equal(keys, expected_keys)
 


http://bitbucket.org/okfn/ckan/changeset/e0a1715a7e5c/
changeset:   e0a1715a7e5c
branch:      feature-1229-db-out-of-controllers
user:        amercader
date:        2011-07-20 18:38:06
summary:     [logic] Put autocomplete tests at the right place
affected #:  4 files (423 bytes)

--- a/ckan/controllers/package.py	Wed Jul 20 16:45:56 2011 +0100
+++ b/ckan/controllers/package.py	Wed Jul 20 17:38:06 2011 +0100
@@ -743,7 +743,7 @@
         context = {'model': model, 'session': model.Session,
                    'user': c.user or c.author}
 
-        data_dict = {'query':q}
+        data_dict = {'q':q}
 
         packages = get.package_autocomplete(context,data_dict)
 


--- a/ckan/logic/action/get.py	Wed Jul 20 16:45:56 2011 +0100
+++ b/ckan/logic/action/get.py	Wed Jul 20 17:38:06 2011 +0100
@@ -257,11 +257,11 @@
     return group_dict
 
 def package_autocomplete(context, data_dict):
-
+    '''Returns packages containing the provided string'''
     model = context['model']
     session = context['session']
     user = context['user']
-    q = data_dict['query']
+    q = data_dict['q']
 
     like_q = u"%s%%" % q
 
@@ -278,3 +278,7 @@
         pkg_list.append(result_dict)
 
     return pkg_list
+
+def package_search(context, data_dict):
+    pass
+


--- a/ckan/tests/functional/api/test_action.py	Wed Jul 20 16:45:56 2011 +0100
+++ b/ckan/tests/functional/api/test_action.py	Wed Jul 20 17:38:06 2011 +0100
@@ -22,9 +22,11 @@
                                         "result": ["annakarenina", "warandpeace"]}
 
     def test_02_package_autocomplete(self):
-        query = 'a'
-        res = self.app.get('/package/autocomplete?q=%s' % query)
-        assert res.body == "annakarenina|annakarenina\nA Wonderful Story (warandpeace)|warandpeace"
+        postparams = '%s=1' % json.dumps({'q':'a'})
+        res = self.app.post('/api/action/package_autocomplete', params=postparams)
+        res_obj = json.loads(res.body)
+        assert res_obj['success'] == True
+        assert res_obj['result'][0]['name'] == 'annakarenina'
 
     def test_03_create_update_package(self):
 


--- a/ckan/tests/functional/test_package.py	Wed Jul 20 16:45:56 2011 +0100
+++ b/ckan/tests/functional/test_package.py	Wed Jul 20 17:38:06 2011 +0100
@@ -1463,4 +1463,8 @@
                            extra_environ={'REMOTE_USER':c.user})
         anna_hash = str(PackageController._pkg_cache_key(self.anna))
         self.assert_equal(res.header_dict['ETag'], anna_hash)
-    
+
+    def test_package_autocomplete(self):
+        query = 'a'
+        res = self.app.get('/package/autocomplete?q=%s' % query)
+        assert res.body == "annakarenina|annakarenina\nA Wonderful Story (warandpeace)|warandpeace"


http://bitbucket.org/okfn/ckan/changeset/6aa06d46fc3c/
changeset:   6aa06d46fc3c
branch:      feature-1229-db-out-of-controllers
user:        amercader
date:        2011-07-21 13:18:28
summary:     [logic] Move package search (Not the search API)
affected #:  3 files (1.8 KB)

--- a/ckan/controllers/package.py	Wed Jul 20 17:38:06 2011 +0100
+++ b/ckan/controllers/package.py	Thu Jul 21 12:18:28 2011 +0100
@@ -19,7 +19,7 @@
 from ckan.lib.base import request, c, BaseController, model, abort, h, g, render
 from ckan.lib.base import etag_cache, response, redirect, gettext
 from ckan.authz import Authorizer
-from ckan.lib.search import query_for, SearchError
+from ckan.lib.search import SearchError
 from ckan.lib.cache import proxy_cache
 from ckan.lib.package_saver import PackageSaver, ValidationException
 from ckan.lib.navl.dictization_functions import DataError, unflatten, validate
@@ -106,7 +106,6 @@
         except ValueError, e:
             abort(400, ('"page" parameter must be an integer'))
         limit = 20
-        query = query_for(model.Package)
 
         # most search operations should reset the page counter:
         params_nopage = [(k, v) for k,v in request.params.items() if k != 'page']
@@ -137,25 +136,30 @@
                         and len(value) and not param.startswith('_'):
                     c.fields.append((param, value))
 
-            query.run(query=q,
-                      fields=c.fields,
-                      facet_by=g.facets,
-                      limit=limit,
-                      offset=(page-1)*limit,
-                      return_objects=True,
-                      filter_by_openness=c.open_only,
-                      filter_by_downloadable=c.downloadable_only,
-                      username=c.user)
-                       
+            context = {'model': model, 'session': model.Session,
+                       'user': c.user or c.author}
+
+            data_dict = {'q':q,
+                         'fields':c.fields,
+                         'facet_by':g.facets,
+                         'limit':limit,
+                         'offset':(page-1)*limit,
+                         'return_objects':True,
+                         'filter_by_openness':c.open_only,
+                         'filter_by_downloadable':c.downloadable_only,
+                        }
+
+            query = get.package_search(context,data_dict)
+
             c.page = h.Page(
-                collection=query.results,
+                collection=query['results'],
                 page=page,
                 url=pager_url,
-                item_count=query.count,
+                item_count=query['count'],
                 items_per_page=limit
             )
-            c.facets = query.facets
-            c.page.items = query.results
+            c.facets = query['facets']
+            c.page.items = query['results']
         except SearchError, se:
             c.query_error = True
             c.facets = {}


--- a/ckan/logic/action/get.py	Wed Jul 20 17:38:06 2011 +0100
+++ b/ckan/logic/action/get.py	Thu Jul 21 12:18:28 2011 +0100
@@ -14,7 +14,7 @@
                                                 package_dictize,
                                                 resource_list_dictize,
                                                 group_dictize)
-
+from ckan.lib.search import query_for
 
 def package_list(context, data_dict):
     '''Lists the package by name'''
@@ -280,5 +280,52 @@
     return pkg_list
 
 def package_search(context, data_dict):
-    pass
+    model = context['model']
+    session = context['session']
+    user = context['user']
 
+    q=data_dict.get('q','')
+    fields=data_dict.get('fields',[])
+    facet_by=data_dict.get('facet_by',[])
+    limit=data_dict.get('limit',20)
+    offset=data_dict.get('offset',0)
+    return_objects=data_dict.get('return_objects',False)
+    filter_by_openness=data_dict.get('filter_by_openness',False)
+    filter_by_downloadable=data_dict.get('filter_by_downloadable',False)
+
+    query = query_for(model.Package)
+    query.run(query=q,
+              fields=fields,
+              facet_by=facet_by,
+              limit=limit,
+              offset=offset,
+              return_objects=return_objects,
+              filter_by_openness=filter_by_openness,
+              filter_by_downloadable=filter_by_downloadable,
+              username=user)
+    
+    results = []
+    for package in query.results:
+        result_dict = table_dictize(package, context)
+        resources = session.query(model.Resource)\
+                    .join(model.ResourceGroup)\
+                    .filter(model.ResourceGroup.package_id == package.id)\
+                    .all()
+        if resources:
+            result_dict['resources'] = resource_list_dictize(resources, context)
+        else:
+            result_dict['resources'] = []
+        license_id = result_dict['license_id']
+        if license_id:
+            isopen = model.Package.get_license_register()[license_id].isopen()
+            result_dict['isopen'] = isopen
+        else:
+            result_dict['isopen'] = False
+
+        results.append(result_dict)
+
+    return {
+        'count': query.count,
+        'facets': query.facets,
+        'results': results
+    }


--- a/ckan/templates/package/search.html	Wed Jul 20 17:38:06 2011 +0100
+++ b/ckan/templates/package/search.html	Thu Jul 21 12:18:28 2011 +0100
@@ -59,7 +59,7 @@
       <py:if test="c.page.item_count == 0 and c.q"><p i18n:msg="">Would you like to <a href="${h.url_for(action='new', id=None)}">create a new package?</a></p></py:if>
-      ${package_list(c.page.items)}
+      ${package_list_from_dict(c.page.items)}
       ${c.page.pager(q=c.q)}
 
   </div>


http://bitbucket.org/okfn/ckan/changeset/78359425b838/
changeset:   78359425b838
branch:      feature-1229-db-out-of-controllers
user:        amercader
date:        2011-07-21 19:28:19
summary:     [logic] Move tag index and read. The api controller now calls tag_show_rest. AlphaPage has been adapted to support lists.
affected #:  8 files (2.7 KB)

--- a/ckan/controllers/api.py	Thu Jul 21 12:18:28 2011 +0100
+++ b/ckan/controllers/api.py	Thu Jul 21 18:28:19 2011 +0100
@@ -220,7 +220,7 @@
         action_map = {
             'revision': get.revision_show,
             'group': get.group_show_rest,
-            'tag': get.tag_show,
+            'tag': get.tag_show_rest,
             'package': get.package_show_rest,
             ('package', 'relationships'): get.package_relationships_list,
         }


--- a/ckan/controllers/tag.py	Thu Jul 21 12:18:28 2011 +0100
+++ b/ckan/controllers/tag.py	Thu Jul 21 18:28:19 2011 +0100
@@ -7,6 +7,9 @@
 from ckan.lib.cache import proxy_cache
 from ckan.lib.helpers import AlphaPage, Page
 
+from ckan.logic import NotFound, NotAuthorized
+import ckan.logic.action.get as get
+
 LIMIT = 25
 
 class TagController(BaseController):
@@ -18,26 +21,32 @@
 
     def index(self):
         c.q = request.params.get('q', '')
-        
+
+        context = {'model': model, 'session': model.Session,
+                   'user': c.user or c.author}
+
+        data_dict = {}
+
         if c.q:
             page = int(request.params.get('page', 1))
-            query = query_for('tag', backend='sql')
-            query.run(query=c.q,
-                      limit=LIMIT,
-                      offset=(page-1)*LIMIT,
-                      return_objects=True,
-                      username=c.user)
+            data_dict['q'] = c.q
+            data_dict['limit'] = LIMIT
+            data_dict['offset'] = (page-1)*LIMIT
+            data_dict['return_objects'] = True
+               
+        results = get.tag_list(context,data_dict)
+         
+        if c.q:
             c.page = h.Page(
-                            collection=query.results,
+                            collection=results,
                             page=page,
-                            item_count=query.count,
+                            item_count=len(results),
                             items_per_page=LIMIT
                             )
-            c.page.items = query.results
+            c.page.items = results
         else:
-            query = model.Tag.all()
             c.page = AlphaPage(
-                collection=query,
+                collection=results,
                 page=request.params.get('page', 'A'),
                 alpha_attribute='name',
                 other_text=_('Other'),
@@ -47,13 +56,14 @@
 
     @proxy_cache()
     def read(self, id):
-        query = model.Session.query(model.Tag)
-        query = query.filter(model.Tag.name==id)
-        query = query.options(eagerload_all('package_tags.package'))
-        query = query.options(eagerload_all('package_tags.package.package_tags.tag'))
-        query = query.options(eagerload_all('package_tags.package.resource_groups_all.resources_all'))
-        c.tag = query.first()
-        if c.tag is None:
-            abort(404)
+        context = {'model': model, 'session': model.Session,
+                   'user': c.user or c.author}
+        
+        data_dict = {'id':id}
+        try:
+            c.tag = get.tag_show(context,data_dict)
+        except NotFound:
+            abort(404, _('Tag not found'))
+
         return render('tag/read.html')
 


--- a/ckan/lib/alphabet_paginate.py	Thu Jul 21 12:18:28 2011 +0100
+++ b/ckan/lib/alphabet_paginate.py	Thu Jul 21 18:28:19 2011 +0100
@@ -13,7 +13,7 @@
         ${c.page.pager()}
 '''
 from itertools import dropwhile
-
+import re
 from sqlalchemy import  __version__ as sqav
 from sqlalchemy.orm.query import Query
 from pylons.i18n import _
@@ -92,7 +92,18 @@
                     # regexp search
                     query = query.filter(attribute.op('~')(u'^[^a-zA-Z].*'))
             query.order_by(attribute)
-            return query.all()                                   
+            return query.all()
+        elif isinstance(self.collection,list):
+            if self.item_count >= self.paging_threshold:
+                if self.page != self.other_text:
+                    items = [x for x in self.collection if x[0:1].lower() == self.page.lower()]
+                else:
+                    # regexp search
+                    items = [x for x in self.collection if re.match('^[^a-zA-Z].*',x)]
+                items.sort()
+            else:
+                items = self.collection
+            return items
         else:
             raise NotImplementedError
 
@@ -100,5 +111,7 @@
     def item_count(self):
         if isinstance(self.collection, Query):
             return self.collection.count()
+        elif isinstance(self.collection,list):
+            return len(self.collection)
         else:
             raise NotImplementedError


--- a/ckan/lib/dictization/model_dictize.py	Thu Jul 21 12:18:28 2011 +0100
+++ b/ckan/lib/dictization/model_dictize.py	Thu Jul 21 18:28:19 2011 +0100
@@ -157,6 +157,15 @@
 
     return result_dict
 
+def tag_dictize(tag, context):
+
+    result_dict = table_dictize(tag, context)
+
+    result_dict["packages"] = obj_list_dictize(
+        tag.packages_ordered, context)
+    
+    return result_dict 
+
 
 ## conversion to api
 
@@ -176,6 +185,15 @@
     dictized["packages"] = sorted([package["id"] for package in dictized["packages"]])
     return dictized
 
+def tag_to_api1(tag, context):
+    
+    dictized = tag_dictize(tag, context)
+    return sorted([package["name"] for package in dictized["packages"]])
+
+def tag_to_api2(tag, context):
+
+    dictized = tag_dictize(tag, context)
+    return sorted([package["id"] for package in dictized["packages"]])
 
 def resource_dict_to_api(res_dict, package_id, context):
     res_dict.pop("revision_id")


--- a/ckan/logic/action/get.py	Thu Jul 21 12:18:28 2011 +0100
+++ b/ckan/logic/action/get.py	Thu Jul 21 18:28:19 2011 +0100
@@ -8,12 +8,17 @@
 import ckan.authz
 
 from ckan.lib.dictization import table_dictize
-from ckan.lib.dictization.model_dictize import group_to_api1, group_to_api2
+from ckan.lib.dictization.model_dictize import (package_dictize,
+                                                resource_list_dictize,
+                                                group_dictize,
+                                                tag_dictize)
+
 from ckan.lib.dictization.model_dictize import (package_to_api1,
                                                 package_to_api2,
-                                                package_dictize,
-                                                resource_list_dictize,
-                                                group_dictize)
+                                                group_to_api1,
+                                                group_to_api2,
+                                                tag_to_api1,
+                                                tag_to_api2)
 from ckan.lib.search import query_for
 
 def package_list(context, data_dict):
@@ -119,11 +124,29 @@
     return licences
 
 def tag_list(context, data_dict):
-    model = context["model"]
-    tags = model.Session.query(model.Tag).all() #TODO
+    model = context['model']
+    user = context['user']
+
+    q = data_dict.get('q','')
+    if q:
+        limit = data_dict.get('limit',25)
+        offset = data_dict.get('offset',0)
+        return_objects = data_dict.get('return_objects',True)
+
+        query = query_for(model.Tag, backend='sql')
+        query.run(query=q,
+                  limit=limit,
+                  offset=offset,
+                  return_objects=return_objects,
+                  username=user)
+        tags = query.results
+    else:
+        tags = model.Session.query(model.Tag).all() #TODO
+
     tag_list = [tag.name for tag in tags]
     return tag_list
 
+
 def package_relationships_list(context, data_dict):
 
     ##TODO needs to work with dictization layer
@@ -220,10 +243,22 @@
     model = context['model']
     api = context.get('api_version') or '1'
     id = data_dict['id']
-    ref_package_by = 'id' if api == '2' else 'name'
-    obj = model.Tag.get(id) #TODO tags
-    if obj is None:
+    #ref_package_by = 'id' if api == '2' else 'name'
+
+    tag = model.Tag.get(id) #TODO tags
+    context['tag'] = tag
+
+    if tag is None:
         raise NotFound
+
+    tag_dict = tag_dictize(tag,context)
+    extended_packages = []
+    for package in tag_dict['packages']:
+        extended_packages.append(_extend_package_dict(package,context))
+
+    tag_dict['packages'] = extended_packages
+
+    return tag_dict
     package_list = [getattr(pkgtag.package, ref_package_by)
                     for pkgtag in obj.package_tags]
     return package_list 
@@ -256,6 +291,19 @@
 
     return group_dict
 
+def tag_show_rest(context, data_dict):
+
+    tag_show(context, data_dict)
+    api = context.get('api_version') or '1'
+    tag = context['tag']
+
+    if api == '2':
+        tag_dict = tag_to_api2(tag, context)
+    else:
+        tag_dict = tag_to_api1(tag, context)
+
+    return tag_dict
+
 def package_autocomplete(context, data_dict):
     '''Returns packages containing the provided string'''
     model = context['model']
@@ -307,20 +355,7 @@
     results = []
     for package in query.results:
         result_dict = table_dictize(package, context)
-        resources = session.query(model.Resource)\
-                    .join(model.ResourceGroup)\
-                    .filter(model.ResourceGroup.package_id == package.id)\
-                    .all()
-        if resources:
-            result_dict['resources'] = resource_list_dictize(resources, context)
-        else:
-            result_dict['resources'] = []
-        license_id = result_dict['license_id']
-        if license_id:
-            isopen = model.Package.get_license_register()[license_id].isopen()
-            result_dict['isopen'] = isopen
-        else:
-            result_dict['isopen'] = False
+        result_dict = _extend_package_dict(result_dict,context)
 
         results.append(result_dict)
 
@@ -329,3 +364,23 @@
         'facets': query.facets,
         'results': results
     }
+
+def _extend_package_dict(package_dict,context):
+    model = context['model']
+
+    resources = model.Session.query(model.Resource)\
+                .join(model.ResourceGroup)\
+                .filter(model.ResourceGroup.package_id == package_dict['id'])\
+                .all()
+    if resources:
+        package_dict['resources'] = resource_list_dictize(resources, context)
+    else:
+        package_dict['resources'] = []
+    license_id = package_dict['license_id']
+    if license_id:
+        isopen = model.Package.get_license_register()[license_id].isopen()
+        package_dict['isopen'] = isopen
+    else:
+        package_dict['isopen'] = False
+
+    return package_dict


--- a/ckan/templates/_util.html	Thu Jul 21 12:18:28 2011 +0100
+++ b/ckan/templates/_util.html	Thu Jul 21 18:28:19 2011 +0100
@@ -30,7 +30,15 @@
       ${h.link_to(tag['name'], h.url_for(controller='tag', action='read', id=tag['name']))}
     </li></ul>
-  
+
+  <!--! List of tags: pass in a list of tag name and this renders the standard
+        tag listing -->
+  <ul py:def="tag_list_from_name(tags)" class="tags clearfix">
+    <li py:for="tag in tags">
+      ${h.link_to(tag, h.url_for(controller='tag', action='read', id=tag))}
+    </li>
+  </ul>
+ 
   <!--! List of users: pass in a collection of users and this renders the standard
           user listing --><ul py:def="user_list(users)" class="users">


--- a/ckan/templates/tag/index.html	Thu Jul 21 12:18:28 2011 +0100
+++ b/ckan/templates/tag/index.html	Thu Jul 21 18:28:19 2011 +0100
@@ -27,7 +27,7 @@
     </p>
     
     ${c.page.pager(q=c.q)}
-    ${tag_list(c.page.items)}
+    ${tag_list_from_name(c.page.items)}
     ${c.page.pager(q=c.q)}
     
     <p py:if="c.q">


--- a/ckan/templates/tag/read.html	Thu Jul 21 12:18:28 2011 +0100
+++ b/ckan/templates/tag/read.html	Thu Jul 21 18:28:19 2011 +0100
@@ -3,12 +3,12 @@
   xmlns:xi="http://www.w3.org/2001/XInclude"
   py:strip="">
   
-  <py:def function="page_title">${c.tag.name} - Tags</py:def>
+  <py:def function="page_title">${c.tag['name']} - Tags</py:def><div py:match="content">
-    <h2>Tag: ${c.tag.name}</h2>
-    <p i18n:msg="package_count, tagname">There are ${len(c.tag.packages_ordered)} packages tagged with <strong>${c.tag.name}</strong>:</p>
-    ${package_list(c.tag.packages_ordered)}
+    <h2>Tag: ${c.tag['name']}</h2>
+    <p i18n:msg="package_count, tagname">There are ${len(c.tag['packages'])} packages tagged with <strong>${c.tag['name']}</strong>:</p>
+    ${package_list_from_dict(c.tag['packages'])}
   </div><xi:include href="layout.html" />

Repository URL: https://bitbucket.org/okfn/ckan/

--

This is a commit notification from bitbucket.org. You are receiving
this because you have the service enabled, addressing the recipient of
this email.




More information about the ckan-changes mailing list