Changeset - a40824531f68
[Not reviewed]
default
0 11 0
Thomas De Schampheleire - 11 years ago 2015-02-21 22:04:54
thomas.de_schampheleire@alcatel-lucent.com
controllers: don't pass rendered templates in context variables

Some controllers used the followifng pattern:
- render a data template into a context variable
- for partial (ajax) requests, return the contents of this variable
- for full-page requests, render the full page, which expands the value of
the context variable

Instead, avoid context variables let the controller simply render the full or partial page, and let
the full page template include the partial page.

Remove this context variable for templating and use render exclusively.
From templates, use %include instead of context variables.

This in line with the suggestions in the Pylons documentation:
http://pylons-webframework.readthedocs.org/en/latest/helpers.html#partial-updates-with-ajax
11 files changed with 18 insertions and 21 deletions:
0 comments (0 inline, 0 general)
kallithea/controllers/admin/admin.py
Show inline comments
 
@@ -120,29 +120,29 @@ def _journal_filter(user_log, search_ter
 
class AdminController(BaseController):
 

	
 
    @LoginRequired()
 
    def __before__(self):
 
        super(AdminController, self).__before__()
 

	
 
    @HasPermissionAllDecorator('hg.admin')
 
    def index(self):
 
        users_log = UserLog.query()\
 
                .options(joinedload(UserLog.user))\
 
                .options(joinedload(UserLog.repository))
 

	
 
        #FILTERING
 
        c.search_term = request.GET.get('filter')
 
        users_log = _journal_filter(users_log, c.search_term)
 

	
 
        users_log = users_log.order_by(UserLog.action_date.desc())
 

	
 
        p = safe_int(request.GET.get('page', 1), 1)
 

	
 
        def url_generator(**kw):
 
            return url.current(filter=c.search_term, **kw)
 

	
 
        c.users_log = Page(users_log, page=p, items_per_page=10, url=url_generator)
 
        c.log_data = render('admin/admin_log.html')
 

	
 
        if request.environ.get('HTTP_X_PARTIAL_XHR'):
 
            return c.log_data
 
            return render('admin/admin_log.html')
 

	
 
        return render('admin/admin.html')
kallithea/controllers/followers.py
Show inline comments
 
@@ -32,30 +32,28 @@ from pylons import tmpl_context as c, re
 
from kallithea.lib.helpers import Page
 
from kallithea.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
 
from kallithea.lib.base import BaseRepoController, render
 
from kallithea.model.db import UserFollowing
 
from kallithea.lib.utils2 import safe_int
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class FollowersController(BaseRepoController):
 

	
 
    def __before__(self):
 
        super(FollowersController, self).__before__()
 

	
 
    @LoginRequired()
 
    @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
 
                                   'repository.admin')
 
    def followers(self, repo_name):
 
        p = safe_int(request.GET.get('page', 1), 1)
 
        repo_id = c.db_repo.repo_id
 
        d = UserFollowing.get_repo_followers(repo_id)\
 
            .order_by(UserFollowing.follows_from)
 
        c.followers_pager = Page(d, page=p, items_per_page=20)
 

	
 
        c.followers_data = render('/followers/followers_data.html')
 

	
 
        if request.environ.get('HTTP_X_PARTIAL_XHR'):
 
            return c.followers_data
 
            return render('/followers/followers_data.html')
 

	
 
        return render('/followers/followers.html')
kallithea/controllers/forks.py
Show inline comments
 
@@ -102,52 +102,50 @@ class ForksController(BaseRepoController
 
        # alter the description to indicate a fork
 
        defaults['description'] = ('fork of repository: %s \n%s'
 
                                   % (defaults['repo_name'],
 
                                      defaults['description']))
 
        # add suffix to fork
 
        defaults['repo_name'] = '%s-fork' % defaults['repo_name']
 

	
 
        return defaults
 

	
 
    @LoginRequired()
 
    @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
 
                                   'repository.admin')
 
    def forks(self, repo_name):
 
        p = safe_int(request.GET.get('page', 1), 1)
 
        repo_id = c.db_repo.repo_id
 
        d = []
 
        for r in Repository.get_repo_forks(repo_id):
 
            if not HasRepoPermissionAny(
 
                'repository.read', 'repository.write', 'repository.admin'
 
            )(r.repo_name, 'get forks check'):
 
                continue
 
            d.append(r)
 
        c.forks_pager = Page(d, page=p, items_per_page=20)
 

	
 
        c.forks_data = render('/forks/forks_data.html')
 

	
 
        if request.environ.get('HTTP_X_PARTIAL_XHR'):
 
            return c.forks_data
 
            return render('/forks/forks_data.html')
 

	
 
        return render('/forks/forks.html')
 

	
 
    @LoginRequired()
 
    @NotAnonymous()
 
    @HasPermissionAnyDecorator('hg.admin', 'hg.fork.repository')
 
    @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
 
                                   'repository.admin')
 
    def fork(self, repo_name):
 
        c.repo_info = Repository.get_by_repo_name(repo_name)
 
        if not c.repo_info:
 
            h.not_mapped_error(repo_name)
 
            return redirect(url('home'))
 

	
 
        defaults = self.__load_data(repo_name)
 

	
 
        return htmlfill.render(
 
            render('forks/fork.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False
 
        )
 

	
 
    @LoginRequired()
kallithea/controllers/journal.py
Show inline comments
 
@@ -186,51 +186,50 @@ class JournalController(BaseController):
 
                          description=desc)
 

	
 
        response.content_type = feed.mime_type
 
        return feed.writeString('utf-8')
 

	
 
    @LoginRequired()
 
    @NotAnonymous()
 
    def index(self):
 
        # Return a rendered template
 
        p = safe_int(request.GET.get('page', 1), 1)
 
        c.user = User.get(self.authuser.user_id)
 
        c.following = self.sa.query(UserFollowing)\
 
            .filter(UserFollowing.user_id == self.authuser.user_id)\
 
            .options(joinedload(UserFollowing.follows_repository))\
 
            .all()
 

	
 
        journal = self._get_journal_data(c.following)
 

	
 
        def url_generator(**kw):
 
            return url.current(filter=c.search_term, **kw)
 

	
 
        c.journal_pager = Page(journal, page=p, items_per_page=20, url=url_generator)
 
        c.journal_day_aggreagate = self._get_daily_aggregate(c.journal_pager)
 

	
 
        c.journal_data = render('journal/journal_data.html')
 
        if request.environ.get('HTTP_X_PARTIAL_XHR'):
 
            return c.journal_data
 
            return render('journal/journal_data.html')
 

	
 
        repos_list = Session().query(Repository)\
 
                     .filter(Repository.user_id ==
 
                             self.authuser.user_id)\
 
                     .order_by(func.lower(Repository.repo_name)).all()
 

	
 
        repos_data = RepoModel().get_repos_as_dict(repos_list=repos_list,
 
                                                   admin=True)
 
        #json used to render the grid
 
        c.data = json.dumps(repos_data)
 

	
 
        watched_repos_data = []
 

	
 
        ## watched repos
 
        _render = RepoModel._render_datatable
 

	
 
        def quick_menu(repo_name):
 
            return _render('quick_menu', repo_name)
 

	
 
        def repo_lnk(name, rtype, rstate, private, fork_of):
 
            return _render('repo_name', name, rtype, rstate, private, fork_of,
 
                           short_name=False, admin=False)
 

	
 
        def last_rev(repo_name, cs_cache):
 
@@ -329,51 +328,51 @@ class JournalController(BaseController):
 
                    return 'ok'
 
                except Exception:
 
                    log.error(traceback.format_exc())
 
                    raise HTTPBadRequest()
 

	
 
        log.debug('token mismatch %s vs %s' % (cur_token, token))
 
        raise HTTPBadRequest()
 

	
 
    @LoginRequired()
 
    def public_journal(self):
 
        # Return a rendered template
 
        p = safe_int(request.GET.get('page', 1), 1)
 

	
 
        c.following = self.sa.query(UserFollowing)\
 
            .filter(UserFollowing.user_id == self.authuser.user_id)\
 
            .options(joinedload(UserFollowing.follows_repository))\
 
            .all()
 

	
 
        journal = self._get_journal_data(c.following)
 

	
 
        c.journal_pager = Page(journal, page=p, items_per_page=20)
 

	
 
        c.journal_day_aggreagate = self._get_daily_aggregate(c.journal_pager)
 

	
 
        c.journal_data = render('journal/journal_data.html')
 
        if request.environ.get('HTTP_X_PARTIAL_XHR'):
 
            return c.journal_data
 
            return render('journal/journal_data.html')
 

	
 
        return render('journal/public_journal.html')
 

	
 
    @LoginRequired(api_access=True)
 
    def public_journal_atom(self):
 
        """
 
        Produce an atom-1.0 feed via feedgenerator module
 
        """
 
        c.following = self.sa.query(UserFollowing)\
 
            .filter(UserFollowing.user_id == self.authuser.user_id)\
 
            .options(joinedload(UserFollowing.follows_repository))\
 
            .all()
 

	
 
        return self._atom_feed(c.following)
 

	
 
    @LoginRequired(api_access=True)
 
    def public_journal_rss(self):
 
        """
 
        Produce an rss2 feed via feedgenerator module
 
        """
 
        c.following = self.sa.query(UserFollowing)\
 
            .filter(UserFollowing.user_id == self.authuser.user_id)\
 
            .options(joinedload(UserFollowing.follows_repository))\
 
            .all()
 

	
kallithea/controllers/pullrequests.py
Show inline comments
 
@@ -183,52 +183,50 @@ class PullrequestsController(BaseRepoCon
 
                  ]
 
        return [g for g in groups if g[0]], selected
 

	
 
    def _get_is_allowed_change_status(self, pull_request):
 
        if pull_request.is_closed():
 
            return False
 

	
 
        owner = self.authuser.user_id == pull_request.user_id
 
        reviewer = self.authuser.user_id in [x.user_id for x in
 
                                                   pull_request.reviewers]
 
        return self.authuser.admin or owner or reviewer
 

	
 
    @LoginRequired()
 
    @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
 
                                   'repository.admin')
 
    def show_all(self, repo_name):
 
        c.from_ = request.GET.get('from_') or ''
 
        c.closed = request.GET.get('closed') or ''
 
        c.pull_requests = PullRequestModel().get_all(repo_name, from_=c.from_, closed=c.closed)
 
        c.repo_name = repo_name
 
        p = safe_int(request.GET.get('page', 1), 1)
 

	
 
        c.pullrequests_pager = Page(c.pull_requests, page=p, items_per_page=10)
 

	
 
        c.pullrequest_data = render('/pullrequests/pullrequest_data.html')
 

	
 
        if request.environ.get('HTTP_X_PARTIAL_XHR'):
 
            return c.pullrequest_data
 
            return render('/pullrequests/pullrequest_data.html')
 

	
 
        return render('/pullrequests/pullrequest_show_all.html')
 

	
 
    @LoginRequired()
 
    def show_my(self): # my_account_my_pullrequests
 
        c.show_closed = request.GET.get('pr_show_closed')
 
        return render('/pullrequests/pullrequest_show_my.html')
 

	
 
    @NotAnonymous()
 
    def show_my_data(self):
 
        c.show_closed = request.GET.get('pr_show_closed')
 

	
 
        def _filter(pr):
 
            s = sorted(pr, key=lambda o: o.created_on, reverse=True)
 
            if not c.show_closed:
 
                s = filter(lambda p: p.status != PullRequest.STATUS_CLOSED, s)
 
            return s
 

	
 
        c.my_pull_requests = _filter(PullRequest.query()\
 
                                .filter(PullRequest.user_id ==
 
                                        self.authuser.user_id)\
 
                                .all())
 

	
 
        c.participate_in_pull_requests = _filter(PullRequest.query()\
kallithea/templates/admin/admin.html
Show inline comments
 
@@ -6,49 +6,49 @@
 
</%block>
 

	
 
<%def name="breadcrumbs_links()">
 
    <form id="filter_form">
 
    <input class="q_filter_box ${'' if c.search_term else 'initial'}" id="j_filter" size="15" type="text" name="filter" value="${c.search_term or _('journal filter...')}"/>
 
    <span class="tooltip" title="${h.tooltip(h.journal_filter_help())}">?</span>
 
    <input type='submit' value="${_('Filter')}" class="btn btn-mini" style="padding:0px 2px 0px 2px;margin:0px"/>
 
    ${_('Admin Journal')} - ${ungettext('%s Entry', '%s Entries', c.users_log.item_count) % (c.users_log.item_count)}
 
    </form>
 
    ${h.end_form()}
 
</%def>
 

	
 
<%block name="header_menu">
 
    ${self.menu('admin')}
 
</%block>
 
<%def name="main()">
 
<div class="box">
 
    <!-- box / title -->
 
    <div class="title">
 
        ${self.breadcrumbs()}
 
    </div>
 
    <!-- end box / title -->
 
    <div class="table">
 
        <div id="user_log">
 
            ${c.log_data}
 
            <%include file='admin_log.html'/>
 
        </div>
 
    </div>
 
</div>
 

	
 
<script>
 
$(document).ready(function() {
 
  $('#j_filter').click(function(){
 
    var $jfilter = $('#j_filter');
 
    if($jfilter.hasClass('initial')){
 
        $jfilter.val('');
 
    }
 
  });
 
  var fix_j_filter_width = function(len){
 
      $('#j_filter').css('width', Math.max(80, len*6.50)+'px');
 
  };
 
  $('#j_filter').keyup(function () {
 
    fix_j_filter_width($('#j_filter').val().length);
 
  });
 
  $('#filter_form').submit(function (e) {
 
      e.preventDefault();
 
      var val = $('#j_filter').val();
 
      window.location = "${url.current(filter='__FILTER__')}".replace('__FILTER__',val);
 
  });
 
  fix_j_filter_width($('#j_filter').val().length);
kallithea/templates/followers/followers.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
<%inherit file="/base/base.html"/>
 

	
 
<%block name="title">
 
    ${_('%s Followers') % c.repo_name}
 
</%block>
 

	
 
<%def name="breadcrumbs_links()">
 
    ${_('Followers')}
 
</%def>
 

	
 
<%block name="header_menu">
 
    ${self.menu('repositories')}
 
</%block>
 
<%def name="main()">
 
${self.repo_context_bar('followers')}
 
<div class="box">
 
    <!-- box / title -->
 
    <div class="title">
 
        ${self.breadcrumbs()}
 
    </div>
 
    <!-- end box / title -->
 
    <div class="table">
 
        <div id="followers">
 
            ${c.followers_data}
 
            <%include file='followers_data.html'/>
 
        </div>
 
    </div>
 
</div>
 
</%def>
kallithea/templates/forks/forks.html
Show inline comments
 
@@ -2,29 +2,29 @@
 
<%inherit file="/base/base.html"/>
 

	
 
<%block name="title">
 
    ${_('%s Forks') % c.repo_name}
 
</%block>
 

	
 
<%def name="breadcrumbs_links()">
 
    ${_('Forks')}
 
</%def>
 

	
 
<%block name="header_menu">
 
    ${self.menu('repositories')}
 
</%block>
 

	
 
<%def name="main()">
 
${self.repo_context_bar('showforks')}
 
<div class="box">
 
    <!-- box / title -->
 
    <div class="title">
 
        ${self.breadcrumbs()}
 
    </div>
 
    <!-- end box / title -->
 
    <div class="table">
 
        <div id="forks">
 
            ${c.forks_data}
 
            <%include file='forks_data.html'/>
 
        </div>
 
    </div>
 
</div>
 
</%def>
kallithea/templates/journal/journal.html
Show inline comments
 
@@ -15,49 +15,51 @@
 
    </h5>
 
</%def>
 
<%block name="header_menu">
 
    ${self.menu('journal')}
 
</%block>
 
<%block name="head_extra">
 
  <link href="${h.url('journal_atom', api_key=c.authuser.api_key)}" rel="alternate" title="${_('ATOM journal feed')}" type="application/atom+xml" />
 
  <link href="${h.url('journal_rss', api_key=c.authuser.api_key)}" rel="alternate" title="${_('RSS journal feed')}" type="application/rss+xml" />
 
</%block>
 

	
 
<%def name="main()">
 
    <div class="box box-left">
 
        <!-- box / title -->
 
        <div class="title">
 
         ${self.breadcrumbs()}
 
         <ul class="links icon-only-links">
 
           <li>
 
             <span><a id="refresh" href="${h.url('journal')}"><i class="icon-arrows-cw"></i></a></span>
 
           </li>
 
           <li>
 
             <span><a href="${h.url('journal_atom', api_key=c.authuser.api_key)}"><i class="icon-rss-squared"></i></a></span>
 
           </li>
 
         </ul>
 
        </div>
 
        <div id="journal">${c.journal_data}</div>
 
        <div id="journal">
 
            <%include file='journal_data.html'/>
 
        </div>
 
    </div>
 
    <div class="box box-right">
 
        <!-- box / title -->
 

	
 
        <div class="title">
 
            <h5>
 
            <input class="q_filter_box" id="q_filter" size="15" type="text" name="filter" placeholder="${_('quick filter...')}" value="" style="display: none"/>
 
            <input class="q_filter_box" id="q_filter_watched" size="15" type="text" name="filter" placeholder="${_('quick filter...')}" value="" style="display: none"/>
 
            </h5>
 
            <ul class="links nav nav-tabs">
 
                <li class="active" id="show_watched_li">
 
                    <a id="show_watched" href="#watched"><i class="icon-eye"></i> ${_('Watched')}</a>
 
                </li>
 
                <li id="show_my_li">
 
                    <a id="show_my" href="#my"><i class="icon-database"></i> ${_('My Repos')}</a>
 
               </li>
 
            </ul>
 
        </div>
 

	
 
        <!-- end box / title -->
 
        <div id="my_container" style="display:none">
 
            <div class="table-grid table yui-skin-sam" id="repos_list_wrap"></div>
 
            <div id="user-paginator" style="padding: 0px 0px 0px 20px"></div>
 
        </div>
kallithea/templates/journal/public_journal.html
Show inline comments
 
@@ -7,28 +7,30 @@
 
    ${c.site_name}
 
</%def>
 
<%block name="header_menu">
 
    ${self.menu('journal')}
 
</%block>
 
<%block name="head_extra">
 
  <link href="${h.url('public_journal_atom')}" rel="alternate" title="${_('ATOM public journal feed')}" type="application/atom+xml" />
 
  <link href="${h.url('public_journal_rss')}" rel="alternate" title="${_('RSS public journal feed')}" type="application/rss+xml" />
 
</%block>
 
<%def name="main()">
 

	
 
<div class="box">
 
  <!-- box / title -->
 
  <div class="title">
 
    <h5>${_('Public Journal')}</h5>
 
      <ul class="links">
 
     <li>
 
       <span>
 
         <a href="${h.url('public_journal_atom')}"> <i class="icon-rss-squared" style="color: #fa9b39"></i></a>
 
       </span>
 
     </li>
 
     </ul>
 
  </div>
 

	
 
  <div id="journal">${c.journal_data}</div>
 
  <div id="journal">
 
    <%include file='journal_data.html'/>
 
  </div>
 
</div>
 

	
 
</%def>
kallithea/templates/pullrequests/pullrequest_show_all.html
Show inline comments
 
@@ -30,28 +30,28 @@ ${self.repo_context_bar('showpullrequest
 
                  <a id="open_new_pr" class="btn btn-small btn-success" href="${h.url('pullrequest_home',repo_name=c.repo_name)}"><i class="icon-plus"></i> ${_('Open New Pull Request')}</a>
 
              </span>
 
             %endif
 
              <span>
 
                %if c.from_:
 
                    <a class="btn btn-small" href="${h.url('pullrequest_show_all',repo_name=c.repo_name,closed=c.closed)}"><i class="icon-git-compare"></i> ${_('Show Pull Requests to %s') % c.repo_name}</a>
 
                %else:
 
                    <a class="btn btn-small" href="${h.url('pullrequest_show_all',repo_name=c.repo_name,closed=c.closed,from_=1)}"><i class="icon-git-compare"></i> ${_("Show Pull Requests from '%s'") % c.repo_name}</a>
 
                %endif
 
              </span>
 
          </li>
 
        </ul>
 
    </div>
 

	
 
    <div style="margin: 0 20px">
 
        <div>
 
        %if c.closed:
 
            ${h.link_to(_('Hide closed pull requests (only show open pull requests)'), h.url('pullrequest_show_all',repo_name=c.repo_name,from_=c.from_))}
 
        %else:
 
            ${h.link_to(_('Show closed pull requests (in addition to open pull requests)'), h.url('pullrequest_show_all',repo_name=c.repo_name,from_=c.from_,closed=1))}
 
        %endif
 
        </div>
 
    </div>
 

	
 
    ${c.pullrequest_data}
 
    <%include file='pullrequest_data.html'/>
 

	
 
</div>
 
</%def>
0 comments (0 inline, 0 general)