I'm trying to access a session variable with AJAX. I have two different views, the main one (index) and another one only returning the session value (refreshSession).
The main one starts a thread that is changing the session value every second but when the view that only returns the session value access to it, the changes that the thread is doing are being lost.
// views.py //
def refreshSession(request):
sesAlarm = request.session['alarm']
return JsonResponse({'alm': sesAlarm})
def index(request):
request.session['alarm'] = 0
t = Thread(target = threadFunction, args=(request,))
t.daemon = True
t.start()
context={}
return HttpResponse(template.render(context, request))
def threadFunction(request):
while True:
request.session['alarm'] += 1
time.sleep(1)
// JS //
var idAlarm = setInterval(function(){
$.ajax({
type:"POST",
url:"/app/update_session/",
cache: 'false',
success: function(data) {
alert(data.alm);
}
});
}, 5000);
This code always shows alerts with '0'. I think the problem is that changes in the thread are not being reflected in the request in refreshSession() because request is not passed by "reference" to the thread (I'm a main C programmer).
If I use a global variable instead of a session it works perfect, the alert shows the number increasing. But I've read that using global variables in views is not recommended.
So, what am I missing? How should I share the session with threads? Should I use global variables in this case?
Thank you!
Edit: This is just an example of the problem that I have, I've simplified it to be easy to understand and useful to others. The thread is a complex application and the web app will not be public, just a GUI of easy access to the app.