Carl Younger
Carl Younger

Reputation: 3070

When using Python2.7 on App Engine, is it ok to reference per-request globals?

I'm using the Python2.7 runtime with threadsafe set to false in the manifest.

Am I safe to do

user = users.get_current_user()

once at the top of the script, in the global space, and reference it from within various handlers without any namespace problems?

Upvotes: 2

Views: 233

Answers (1)

Lipis
Lipis

Reputation: 21835

It is better to create a base class, add some functions there and then extend from base class all your handlers, because get_current_user() has to do with the request handler and make sense only there.

Here is an example:

import webapp2
from google.appengine.api import users

class BaseHandler(webapp2.RequestHandler):
  def get_user(self):
    #Maybe also adding some logic here or returning your own User model
    return users.get_current_user()


class MainPage(BaseHandler):
  def get(self):
    if self.get_user():
      self.response.headers['Content-Type'] = 'text/plain'
      self.response.out.write('Hello, ' + self.get_user().nickname())
    else:
      self.redirect(users.create_login_url(self.request.uri))

Upvotes: 4

Related Questions