Search code examples
python-2.7google-app-enginegoogle-cloud-datastorewebapp2

Keeping track of login status on webapp2


I am following a Udacity course on full stack development (Python2 and Google app engine) and in one of the lessons, in order to keep track of an user login status the professor uses the following function:

    def initialize(self, *a, **kw):
    webapp2.RequestHandler.initialize(self, *a, **kw)
    uid = self.read_secure_cookie('user_id')
    self.user = uid and User.by_id(int(uid))

The goal of this function is to return the User object so I can use its properties at different times.

He explains that this function is called on every single request. It looks like it is querying the datastore every time. In a real production environment, is this the most cost efficient way to do this?


Solution

  • Upon first inspection of the function you shared, it does not look like it is calling DataStore, as I guess that read_secure_cookie is a custom function which probably looks something like:

    def read_secure_cookie(self,name):
            cookie = self.request.cookies.get(name)
            return cookie
    

    In the case that this is the type of definition of this function, it is working with webapp2 Cookies, and not reading from DataStore.

    In any case, as @Alex suggested in the comment to your question, depending on your use case, you could consider using Memcache, as it is a recommended tool when many different requests use the same Datastore data. However, if the main purpose of the cookies being used is to track the user status, this might be a parameter bound to each connection, so maybe sticking with cookies is a better solution here.