changeset 6449:0122959e1f1d

lib: move jsonify from utils to base Suggested by Mads Kiilerich. The jsonify method is the only thing in utils that directly uses pylons. Move it to base where it fits better and we can use existing global imports.
author Thomas De Schampheleire <thomas.de.schampheleire@gmail.com>
date Sat, 14 Jan 2017 21:22:51 +0100
parents 7250e5b1ab46
children 26bc2f02d9cd
files kallithea/controllers/admin/gists.py kallithea/controllers/admin/repos.py kallithea/controllers/changeset.py kallithea/controllers/files.py kallithea/controllers/home.py kallithea/controllers/pullrequests.py kallithea/controllers/summary.py kallithea/lib/base.py kallithea/lib/utils.py
diffstat 9 files changed, 40 insertions(+), 46 deletions(-) [+]
line wrap: on
line diff
--- a/kallithea/controllers/admin/gists.py	Sun Jan 22 01:16:52 2017 +0100
+++ b/kallithea/controllers/admin/gists.py	Sat Jan 14 21:22:51 2017 +0100
@@ -40,9 +40,8 @@
 from kallithea.model.meta import Session
 from kallithea.model.db import Gist, User
 from kallithea.lib import helpers as h
-from kallithea.lib.base import BaseController, render
+from kallithea.lib.base import BaseController, render, jsonify
 from kallithea.lib.auth import LoginRequired, NotAnonymous
-from kallithea.lib.utils import jsonify
 from kallithea.lib.utils2 import safe_int, safe_unicode, time_to_datetime
 from kallithea.lib.page import Page
 from sqlalchemy.sql.expression import or_
--- a/kallithea/controllers/admin/repos.py	Sun Jan 22 01:16:52 2017 +0100
+++ b/kallithea/controllers/admin/repos.py	Sat Jan 14 21:22:51 2017 +0100
@@ -38,8 +38,8 @@
 from kallithea.lib import helpers as h
 from kallithea.lib.auth import LoginRequired, \
     HasRepoPermissionAnyDecorator, NotAnonymous, HasPermissionAny
-from kallithea.lib.base import BaseRepoController, render
-from kallithea.lib.utils import action_logger, jsonify
+from kallithea.lib.base import BaseRepoController, render, jsonify
+from kallithea.lib.utils import action_logger
 from kallithea.lib.vcs import RepositoryError
 from kallithea.model.meta import Session
 from kallithea.model.db import User, Repository, UserFollowing, RepoGroup, \
--- a/kallithea/controllers/changeset.py	Sun Jan 22 01:16:52 2017 +0100
+++ b/kallithea/controllers/changeset.py	Sat Jan 14 21:22:51 2017 +0100
@@ -33,7 +33,6 @@
 from pylons.i18n.translation import _
 from webob.exc import HTTPFound, HTTPForbidden, HTTPBadRequest, HTTPNotFound
 
-from kallithea.lib.utils import jsonify
 from kallithea.lib.vcs.exceptions import RepositoryError, \
     ChangesetDoesNotExistError, EmptyRepositoryError
 
@@ -41,7 +40,7 @@
 import kallithea.lib.helpers as h
 from kallithea.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator, \
     NotAnonymous
-from kallithea.lib.base import BaseRepoController, render
+from kallithea.lib.base import BaseRepoController, render, jsonify
 from kallithea.lib.utils import action_logger
 from kallithea.lib.compat import OrderedDict
 from kallithea.lib import diffs
--- a/kallithea/controllers/files.py	Sun Jan 22 01:16:52 2017 +0100
+++ b/kallithea/controllers/files.py	Sat Jan 14 21:22:51 2017 +0100
@@ -37,7 +37,7 @@
 from webob.exc import HTTPFound
 
 from kallithea.config.routing import url
-from kallithea.lib.utils import jsonify, action_logger
+from kallithea.lib.utils import action_logger
 from kallithea.lib import diffs
 from kallithea.lib import helpers as h
 
@@ -45,7 +45,7 @@
 from kallithea.lib.utils2 import convert_line_endings, detect_mode, safe_str, \
     str2bool, safe_int
 from kallithea.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
-from kallithea.lib.base import BaseRepoController, render
+from kallithea.lib.base import BaseRepoController, render, jsonify
 from kallithea.lib.vcs.backends.base import EmptyChangeset
 from kallithea.lib.vcs.conf import settings
 from kallithea.lib.vcs.exceptions import RepositoryError, \
--- a/kallithea/controllers/home.py	Sun Jan 22 01:16:52 2017 +0100
+++ b/kallithea/controllers/home.py	Sat Jan 14 21:22:51 2017 +0100
@@ -33,10 +33,10 @@
 from webob.exc import HTTPBadRequest
 from sqlalchemy.sql.expression import func
 
-from kallithea.lib.utils import jsonify, conditional_cache
+from kallithea.lib.utils import conditional_cache
 from kallithea.lib.compat import json
 from kallithea.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
-from kallithea.lib.base import BaseController, render
+from kallithea.lib.base import BaseController, render, jsonify
 from kallithea.model.db import Repository, RepoGroup
 from kallithea.model.repo import RepoModel
 
--- a/kallithea/controllers/pullrequests.py	Sun Jan 22 01:16:52 2017 +0100
+++ b/kallithea/controllers/pullrequests.py	Sat Jan 14 21:22:51 2017 +0100
@@ -39,12 +39,12 @@
 from kallithea.lib import diffs
 from kallithea.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator, \
     NotAnonymous
-from kallithea.lib.base import BaseRepoController, render
+from kallithea.lib.base import BaseRepoController, render, jsonify
 from kallithea.lib.compat import json, OrderedDict
 from kallithea.lib.diffs import LimitedDiffContainer
 from kallithea.lib.exceptions import UserInvalidException
 from kallithea.lib.page import Page
-from kallithea.lib.utils import action_logger, jsonify
+from kallithea.lib.utils import action_logger
 from kallithea.lib.vcs.exceptions import EmptyRepositoryError, ChangesetDoesNotExistError
 from kallithea.lib.vcs.utils import safe_str
 from kallithea.lib.vcs.utils.hgcompat import unionrepo
--- a/kallithea/controllers/summary.py	Sun Jan 22 01:16:52 2017 +0100
+++ b/kallithea/controllers/summary.py	Sat Jan 14 21:22:51 2017 +0100
@@ -42,11 +42,10 @@
     NodeDoesNotExistError
 from kallithea.config.conf import ALL_READMES, ALL_EXTS, LANGUAGES_EXTENSIONS_MAP
 from kallithea.model.db import Statistics, CacheInvalidation, User
-from kallithea.lib.utils import jsonify
 from kallithea.lib.utils2 import safe_str
 from kallithea.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator, \
     NotAnonymous
-from kallithea.lib.base import BaseRepoController, render
+from kallithea.lib.base import BaseRepoController, render, jsonify
 from kallithea.lib.vcs.backends.base import EmptyChangeset
 from kallithea.lib.markup_renderer import MarkupRenderer
 from kallithea.lib.celerylib.tasks import get_commits_stats
--- a/kallithea/lib/base.py	Sun Jan 22 01:16:52 2017 +0100
+++ b/kallithea/lib/base.py	Sat Jan 14 21:22:51 2017 +0100
@@ -29,9 +29,11 @@
 """
 
 import datetime
+import decorator
 import logging
 import time
 import traceback
+import warnings
 
 import webob.exc
 import paste.httpexceptions
@@ -39,7 +41,7 @@
 import paste.httpheaders
 from webhelpers.pylonslib import secure_form
 
-from pylons import config, tmpl_context as c, request, session
+from pylons import config, tmpl_context as c, request, response, session
 from pylons.controllers import WSGIController
 from pylons.templating import render_mako as render  # don't remove this import
 from pylons.i18n.translation import _
@@ -51,6 +53,7 @@
     safe_str, safe_int
 from kallithea.lib import auth_modules
 from kallithea.lib.auth import AuthUser, HasPermissionAnyMiddleware
+from kallithea.lib.compat import json
 from kallithea.lib.utils import get_repo_slug
 from kallithea.lib.exceptions import UserCreationError
 from kallithea.lib.vcs.exceptions import RepositoryError, EmptyRepositoryError, ChangesetDoesNotExistError
@@ -581,3 +584,28 @@
         if hasattr(self._result, 'close'):
             self._result.close()
         self._close()
+
+
+@decorator.decorator
+def jsonify(func, *args, **kwargs):
+    """Action decorator that formats output for JSON
+
+    Given a function that will return content, this decorator will turn
+    the result into JSON, with a content-type of 'application/json' and
+    output it.
+    """
+    response.headers['Content-Type'] = 'application/json; charset=utf-8'
+    data = func(*args, **kwargs)
+    if isinstance(data, (list, tuple)):
+        # A JSON list response is syntactically valid JavaScript and can be
+        # loaded and executed as JavaScript by a malicious third-party site
+        # using <script>, which can lead to cross-site data leaks.
+        # JSON responses should therefore be scalars or objects (i.e. Python
+        # dicts), because a JSON object is a syntax error if intepreted as JS.
+        msg = "JSON responses with Array envelopes are susceptible to " \
+              "cross-site data leak attacks, see " \
+              "https://web.archive.org/web/20120519231904/http://wiki.pylonshq.com/display/pylonsfaq/Warnings"
+        warnings.warn(msg, Warning, 2)
+        log.warning(msg)
+    log.debug("Returning JSON wrapped action output")
+    return json.dumps(data, encoding='utf-8')
--- a/kallithea/lib/utils.py	Sun Jan 22 01:16:52 2017 +0100
+++ b/kallithea/lib/utils.py	Sat Jan 14 21:22:51 2017 +0100
@@ -34,8 +34,6 @@
 import beaker
 import tarfile
 import shutil
-import decorator
-import warnings
 from os.path import abspath
 from os.path import dirname
 
@@ -706,35 +704,6 @@
     return ver
 
 
-@decorator.decorator
-def jsonify(func, *args, **kwargs):
-    """Action decorator that formats output for JSON
-
-    Given a function that will return content, this decorator will turn
-    the result into JSON, with a content-type of 'application/json' and
-    output it.
-
-    """
-    from pylons.decorators.util import get_pylons
-    from kallithea.lib.compat import json
-    pylons = get_pylons(args)
-    pylons.response.headers['Content-Type'] = 'application/json; charset=utf-8'
-    data = func(*args, **kwargs)
-    if isinstance(data, (list, tuple)):
-        # A JSON list response is syntactically valid JavaScript and can be
-        # loaded and executed as JavaScript by a malicious third-party site
-        # using <script>, which can lead to cross-site data leaks.
-        # JSON responses should therefore be scalars or objects (i.e. Python
-        # dicts), because a JSON object is a syntax error if intepreted as JS.
-        msg = "JSON responses with Array envelopes are susceptible to " \
-              "cross-site data leak attacks, see " \
-              "https://web.archive.org/web/20120519231904/http://wiki.pylonshq.com/display/pylonsfaq/Warnings"
-        warnings.warn(msg, Warning, 2)
-        log.warning(msg)
-    log.debug("Returning JSON wrapped action output")
-    return json.dumps(data, encoding='utf-8')
-
-
 #===============================================================================
 # CACHE RELATED METHODS
 #===============================================================================