mrmo123
mrmo123

Reputation: 725

Will setting a global value affect other users - GAE Python

I'm thinking about setting a global value in python (example below) loosely based on this article: Using global variables in a function other than the one that created them

#get a variable; set global variable
class Home(webapp2.RequestHandler):
  def get(self):
    #use OAuth2 to get a variable (example UserId = 1234567890)
    #set the UserId here
    global userId

#use global variable
class Submit(webapp2.RequestHandler):
  def post(self):
    #Do something with userId 1234567890

Problem/Not sure what happens (numbers indicate chronological order):

  1. UserId 1234567890 goes to class Home
  2. UserId 5555555555 (different computer) goes to class Home
  3. UserId 1234567890 submits something class Submit (e.g. tries to store to database: UserId=1234567890; Comment=hi)

???. Will it store as UserId=1234567890; Comment = hi OR AS UserId =5555555555; Comment=hi)

Upvotes: 0

Views: 39

Answers (2)

Dave W. Smith
Dave W. Smith

Reputation: 24966

The only times it's safe to set globals in web apps is a) when you're setting up an immutable object (or object graph) during initialization, and b) when you're working on a single-user application, but that can get problematic if you ever have multiple tabs open to the app.

When you need to save state between requests, and that state is going to come back to you via a POST, you can externalize the state as a hidden form field, but the safer choice is to use sessions. For webapp2, webapp2 sessions seems popular.

Upvotes: 2

mrmo123
mrmo123

Reputation: 725

I just tested the code, it ends up being UserId=5555555555; Comment=hi. I guess this is why they say global variables are dangerous :(

Upvotes: 1

Related Questions