From 79ae9175bb453802be247dd9c84cdd8224e8e543 Mon Sep 17 00:00:00 2001 From: Tim Abbott Date: Sun, 17 Mar 2019 14:08:53 -0700 Subject: [PATCH] context_processors: Avoid useless duplicate queries for realm object. We have a few code paths that call get_realm_from_request multiple times on the same request (e.g. the login page), once inside the view function and once inside the common context processor code. This change saves a useless duplicate database query in those code paths. --- zerver/context_processors.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/zerver/context_processors.py b/zerver/context_processors.py index d97c91fe6d..1264374c58 100644 --- a/zerver/context_processors.py +++ b/zerver/context_processors.py @@ -38,8 +38,14 @@ def common_context(user: UserProfile) -> Dict[str, Any]: def get_realm_from_request(request: HttpRequest) -> Optional[Realm]: if hasattr(request, "user") and hasattr(request.user, "realm"): return request.user.realm - subdomain = get_subdomain(request) - return get_realm(subdomain) + if not hasattr(request, "realm"): + # We cache the realm object from this function on the request, + # so that functions that call get_realm_from_request don't + # need to do duplicate queries on the same realm while + # processing a single request. + subdomain = get_subdomain(request) + request.realm = get_realm(subdomain) + return request.realm def zulip_default_context(request: HttpRequest) -> Dict[str, Any]: """Context available to all Zulip Jinja2 templates that have a request