[Fixed]-Storing and accessing request-response wide object

1👍

One way to store the connection resource so that it can be shared across your components is to use thread local storage.

For example, in myldap.py:

import threading
_local = theading.local()

def get_ldap_connection():
    if not hasattr(_local, 'ldap_connection') or _local.ldap_connection is None:
        _local.ldap_connection = create_ldap_connection()

    return _local.ldap_connection

def close_ldap_connection():
    if hasattr(_local, 'ldap_connection') and _local.ldap_connection is not None:
        close_ldap_connection(_local.ldap_connection)
        _local.ldap_connection = None

So the first time myldap.get_ldap_connection is called from a specific thread it will open the connection. Subsequent calls from the same thread will reuse the connection.

To ensure the connection is closed when you have finished working, you could implement a Django middleware component. Amongst other things this will allow you to specify a hook that gets invoked after the view has returned it’s response object.

The middleware can then invoke myldap.close_ldap_connection() like this:

import myldap

Class CloseLdapMiddleware(object):  
    def process_response(self, response):  
        myldap.close_ldap_connection()
        return response

Finally you will need to add your middleware in settings.py MIDDLEWARE_CLASSES:

MIDDLEWARE_CLASSES = [
    ...
    'path.to.CloseLdapMiddleWare',
    ...
]

Leave a comment