From bfb1ca715c99b3f7bded9d90402fe511c00ae76f Mon Sep 17 00:00:00 2001 From: amercader Date: Thu, 11 Aug 2016 16:11:03 +0100 Subject: [PATCH] [#3196] Fall back to app_globals on Flask g If a property is not found on `g`, check CKAN's own `app_globals`, where stuff like `g.site_title` is kept. The default behaviour for Flask's `g` is to raise an AttributeError if a missing property is accessed. We have kept this behaviour here and handled a couple of cases where `c` was accessed outside of a request. This can be reverted to returning an empty string if necessary. --- ckan/authz.py | 3 +++ ckan/config/middleware/flask_app.py | 14 ++++++++++++++ ckan/logic/__init__.py | 3 +++ 3 files changed, 20 insertions(+) diff --git a/ckan/authz.py b/ckan/authz.py index d77f91b887d..3714bb4e5ff 100644 --- a/ckan/authz.py +++ b/ckan/authz.py @@ -118,6 +118,9 @@ def _get_user(username): try: if c.userobj and c.userobj.name == username: return c.userobj + except AttributeError: + # c.userobj not set + pass except TypeError: # c is not available pass diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py index 6a3e80b4369..e258a82e37e 100644 --- a/ckan/config/middleware/flask_app.py +++ b/ckan/config/middleware/flask_app.py @@ -15,6 +15,7 @@ def make_flask_stack(conf, **app_conf): Pylons used """ app = flask_app = CKANFlask(__name__) + app.app_ctx_globals_class = CKAN_AppCtxGlobals # Update Flask config with the CKAN values. We use the common config # object as values might have been modified on `load_environment` @@ -38,6 +39,19 @@ def hello_world_post(): return app +class CKAN_AppCtxGlobals(_AppCtxGlobals): + + '''Custom Flask AppCtxGlobal class (flask.g).''' + + def __getattr__(self, name): + ''' + If flask.g doesn't have attribute `name`, fall back to CKAN's + app_globals object. + If the key is also not found in there, an AttributeError will be raised + ''' + return getattr(app_globals.app_globals, name) + + class CKANFlask(Flask): '''Extend the Flask class with a special method called on incoming diff --git a/ckan/logic/__init__.py b/ckan/logic/__init__.py index 7f868881477..973e812df68 100644 --- a/ckan/logic/__init__.py +++ b/ckan/logic/__init__.py @@ -220,6 +220,9 @@ def _prepopulate_context(context): context.setdefault('session', model.Session) try: context.setdefault('user', c.user) + except AttributeError: + # c.user not set + pass except TypeError: # c not registered pass