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.
This commit is contained in:
Tim Abbott
2019-03-17 14:08:53 -07:00
parent f270e354b1
commit 79ae9175bb

View File

@@ -38,8 +38,14 @@ def common_context(user: UserProfile) -> Dict[str, Any]:
def get_realm_from_request(request: HttpRequest) -> Optional[Realm]: def get_realm_from_request(request: HttpRequest) -> Optional[Realm]:
if hasattr(request, "user") and hasattr(request.user, "realm"): if hasattr(request, "user") and hasattr(request.user, "realm"):
return request.user.realm return request.user.realm
subdomain = get_subdomain(request) if not hasattr(request, "realm"):
return get_realm(subdomain) # 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]: def zulip_default_context(request: HttpRequest) -> Dict[str, Any]:
"""Context available to all Zulip Jinja2 templates that have a request """Context available to all Zulip Jinja2 templates that have a request