Balakrishnan
Balakrishnan

Reputation: 2441

Django responding to different request from different browser with one python session

I'm actually a php(CodeIgniter) web developer though I love python I just installed Bitnami's Django Stack which has Apache, MySQL, PostgreSQL and Python 2.7.9 with Django installed. During installation itself it generated a simple Django project.

Though it looked familiar to me I started adding some lines of codes to it but when I save it and refresh the page or even restart the browser I found that python instance is still running the old script. The script updates only when I restart start the Apache Server(I believe that's where the Python instance got terminated).

So, to clarify this problem with Python I created a simple view and URLed it to r'^test/'

from django.http import HttpResponse

i = 0

def test_view(request):
    global i
    i += 1
    return HttpResponse(str(i))

Then I found that even switching between different browser the i value keep on increasing i.e increasing value continues with the other browse.

So, can anyone tell me is this a default behavior of Django or is there something wrong with my Apache installation.

Upvotes: 1

Views: 234

Answers (1)

Daniel Rucci
Daniel Rucci

Reputation: 2872

This is the default behavior, it may reset if you were running with gunicorn and killing workers after X requests or so, I don't remember. It's like this because the app continues to run after a request has been served.

Its been a while I've worked with PHP but I believe, a request comes in, php starts running a script which returns output and then that script terminates. Special global variables like $_SESSION aside, nothing can really cross requests.

Your Django app starts up and continues to run unless something tells it to reload (when running with ./manage.py runserver it will reload whenever it detects changes to the code, this is what you want during development).

If you are interested in per visitor data see session data. It would look something like:

request.session['i'] = request.session.get('i', 0) + 1

You can store data in there for the visitor and it will stick around until they lose their session.

Upvotes: 1

Related Questions