import logging

from flask import g

from drift.core.extensions.jwt import query_current_user


log = logging.getLogger(__name__)


def _update_analytics():
    client_id = None
    current_user = query_current_user()
    if current_user:
        user_id = current_user["user_id"]
        client_id = current_user.get("client_id")
        if not client_id:
            log.debug("client_id not found in JWT for user %s. Not updating client stats." % user_id)

    if hasattr(g, 'redis') and g.redis and g.redis.conn:
        # use redis pipeline to minimize roundtrips
        pipe = g.redis.conn.pipeline()
        k = g.redis.make_key('stats:numrequests')
        pipe.incr(k)
        pipe.expire(k, 3600)
        if client_id:
            k = g.redis.make_key('stats:numrequestsclient:{}'.format(client_id))
            pipe.incr(k)
            pipe.expire(k, 3600)
        pipe.execute()


def after_request(response):
    _update_analytics()
    return response


def register_extension(app):
    app.after_request(after_request)

@@ -27,17 +27,27 @@
  import 
-g
+current_app
 %0A%0Afrom d
@@ -471,59 +471,281 @@
     
-if hasattr(g, 'redis') and g.redis and g.redis.conn
+# As we are doing this 'after request' we should only acquire the redis session if it's%0A    # already available. A %22hard%22 reference on g.redis could have side effects in this%0A    # context.%0A    redis = current_app.extensions%5B'redis'%5D.get_session_if_available()%0A    if redis
 :%0A  
@@ -809,18 +809,16 @@
  pipe = 
-g.
 redis.co
@@ -835,34 +835,32 @@
 e()%0A        k = 
-g.
 redis.make_key('
@@ -967,18 +967,16 @@
     k = 
-g.
 redis.ma

Change how the analytics middleware acquires redis session