From 1b4b55ac23f434cb3123d4951d230636d8dcb184 Mon Sep 17 00:00:00 2001 From: Ian Gulliver Date: Sat, 7 Jun 2014 23:06:17 -0700 Subject: [PATCH] Cache named profiles in memory in the Python application, since they're immutable once written. --- lib/models.py | 15 +++++++++++++++ lib/session.py | 6 +----- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/lib/models.py b/lib/models.py index 44a5cdd..fb2388a 100644 --- a/lib/models.py +++ b/lib/models.py @@ -47,6 +47,21 @@ class AccessDenied(Exception): class Profile(db.Model): google_user = db.UserProperty() + _cache = {} + + @classmethod + @db.transactional() + def FindOrCreate(cls, google_user): + key_name = google_user.user_id() + if key_name in cls._cache: + return cls._cache[key_name] + profile = cls.get_by_key_name(key_name) + if not profile: + profile = cls(key_name=key_name, google_user=google_user) + profile.put() + cls._cache[key_name] = profile + return profile + def MergeFrom(self, source_profile): # This is non-transactional and racy (new messages can be introduced by the # old client after we start). This is hard to solve because we're not in diff --git a/lib/session.py b/lib/session.py index a06280d..68268a1 100644 --- a/lib/session.py +++ b/lib/session.py @@ -23,11 +23,7 @@ from cosmopolite.lib import models def CreateClientAndProfile(client_id, google_user): if google_user: # We're going to need a profile for this user regardless - profile = models.Profile.get_by_key_name(google_user.user_id()) - if not profile: - profile = models.Profile( - key_name=google_user.user_id(), google_user=google_user) - profile.put() + profile = models.Profile.FindOrCreate(google_user) else: profile = None