Django session variables sometimes get lost in multi-threaded environment
<p>I'm trying to cache a set of strings per session by storing each one in their own variable and by using django.contrib.session.</p>

<p>I have the following code:</p>

<pre><code>import copy

def get_result(request, operation):
    previous_result = request.session.get(operation.name)
    if previous_result:
        result = copy.deepcopy(previous_result)
    else:
        result = get_json_response(operation)
        request.session[operation.name] = copy.deepcopy(result)
    return result
</code></pre>

<p>get_result() is</p>

<ol>
<li>triggered via ajax requests</li>
<li>used for many different operations which may be called at the same time</li>
<li>may be called multiple times per operation in one session</li>
</ol>

<p>This code works perfectly fine on my local environment. However, in production server where gevent and chausette is installed, it fails.</p>

<p>Most of the time, request.session.get(operation.name) would return None even when it is not the first time that get_result is called for that operation. In some cases, it returns a value but in some, it doesn't. There seems to be no pattern on when it does and doesn't work.</p>

<p>I suspect that the inconsistency is because different threads are referencing the session variable at different states. What would be the proper way to handle session variables in this case?</p>