0

I would like to obtain a value from the session and in case that value does not exist I would like to supply a default one. I got my current approach from here. This is what I am doing

fav_color = request.session.get('fav_color', 'red')

The above works fine however I noticed that if the key variable is placed in settings.py then the output is None.Which I would like to fix. For instance this is in my settings.py

VARIABLE_PATIENT_ID_DEFINE="patientID"

Now in some other app I am using it like this

    t = "somevar"
    s = settings.VARIABLE_PATIENT_ID_DEFINE
    print(s) # prints patientID
    fav_color = request.session.get(s, 'red') --->After this line Default is None
    fav_color = request.session.get(t, 'red') --->After this line Default is red

My questions is why does

fav_color = request.session.get(s, 'red')

fail and return none ? Why does assigning from settings.VARIABLE_PATIENT_ID_DEFINE cause an issue

Community
  • 1
  • 1
James Franco
  • 4,516
  • 10
  • 38
  • 80

1 Answers1

1

If request.session already contain {"patientID": None} then performing request.session.get("patientID", "red") will also return None since this is the value of patientID key.

you would only get "red" if the key doesn't exist at all in the session which doesn't seem to be the case here.

you can solve your problem by writing

fav_color = request.session.get(s, 'red') or 'red'

Ramast
  • 7,157
  • 3
  • 32
  • 32
  • the session does not contain a key called patientID why is it returning none when it should be returning red. it returns red in the second case but not in the first case. it shld be returning red in both cases – James Franco Feb 07 '17 at 01:13
  • can you `print dict(request.session)` ? what is the output? pretty sure you will find it there – Ramast Feb 07 '17 at 01:20
  • yes its in there. Thanks for clearing that up. Could you tell me what dict(request.session) does ? I already thought request.session is a dictionary what does dict(request.session) do ? – James Franco Feb 07 '17 at 01:26
  • session attribute is a dictionary-like object. It behave like dictionary but has some extra functions and properties. `dict(request.session)` convert the session into normal python dictionary. You shouldn't need to do that when using the session. I just suggested to use it for debugging purpose – Ramast Feb 07 '17 at 01:32
  • yes i know but i like the approach. Thanks for clearing this up – James Franco Feb 07 '17 at 01:36