TheMeaningfulEngineer
TheMeaningfulEngineer

Reputation: 16329

Getting rid of the global variable in Django view?

I've created a Django app which relies on a global variable. It's actually a sort of a repository object which should be available to all the functions in my view.py.

As will be seen in the code, each of the view functions modify the rp global variable.

view.py

def index(request):
    global rp
    rp = repo.Repo()
    ...
    rp.function1()
    rp.function2()
    rp.attribute1 = value

    return render_to_response('result_pick.html',{'result_list': rp.parsed_output_data, 'input_file_name': rp.input_file_name }, context_instance = RequestContext(request))

def result(request):
    global rp
    rp.function3()
    local_atribute = rp.attribute1
    ....
    return render_to_response('result_show.html' ,{'rp':rp}, context_instance = RequestContext(request))

After browsing a bit, i got the impression that this would fail the moment multiple users would access the web page because they would share the global rp and that would cause problems.

What is the preferred solution to get rid of the global variable but still be able to access rp in both functions?

Upvotes: 2

Views: 3950

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174614

Use the session framework; which persists objects between requests (and hence, between your view methods).

Once you have it set up, its as simple as:

def a_method(request):
   shared_obj = request.session.get('myobj',{}) # set dict as default
   shared_obj['key'] = 'val'
   request.session['myobj'] = shared_obj
   # your normal code
   return render(request,'sometemplate.html') # no need to pass 'shared_obj'

def b_method(request):
    shared_obj = request.session.get('myobj',{})
    if not shared_obj:
       # session was terminated, so initialize this object
       shared_obj['key'] = 'value'
     else:
       the_value = shared_obj['key']
       # or, use the below to set a default value for 'key' if it doesn't exist
       the_value = shared_obj.get('key','default')
     # etc.

Upvotes: 5

Related Questions