From 676d4f32fc208b58dc8d179e40d1bb69a730f8f2 Mon Sep 17 00:00:00 2001 From: Tim Abbott Date: Tue, 9 May 2017 21:44:26 -0700 Subject: [PATCH] avatar_url: Fix unnecessary database query. If we have a user_profile object, there's no reason to fetch it again from memcached. --- zerver/lib/avatar.py | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/zerver/lib/avatar.py b/zerver/lib/avatar.py index 70f0c610e3..66b0030b81 100644 --- a/zerver/lib/avatar.py +++ b/zerver/lib/avatar.py @@ -4,34 +4,43 @@ from django.conf import settings if False: from zerver.models import UserProfile -from typing import Text +from typing import Any, Dict, Optional, Text -from zerver.lib.avatar_hash import gravatar_hash, user_avatar_path +from zerver.lib.avatar_hash import gravatar_hash, user_avatar_path, \ + user_avatar_path_from_ids from zerver.lib.upload import upload_backend, MEDIUM_AVATAR_SIZE from zerver.models import get_user_profile_by_email def avatar_url(user_profile, medium=False): # type: (UserProfile, bool) -> Text - return get_avatar_url( + url = _get_unversioned_avatar_url( user_profile.avatar_source, - user_profile.email, - user_profile.avatar_version, + email=user_profile.email, + realm_id=user_profile.realm_id, + user_profile_id=user_profile.id, medium=medium) + url += '&version=%d' % (user_profile.avatar_version,) + return url def get_avatar_url(avatar_source, email, avatar_version, medium=False): # type: (Text, Text, int, bool) -> Text url = _get_unversioned_avatar_url( avatar_source, - email, - medium) + email=email, + medium=medium) url += '&version=%d' % (avatar_version,) return url -def _get_unversioned_avatar_url(avatar_source, email, medium=False): - # type: (Text, Text, bool) -> Text +def _get_unversioned_avatar_url(avatar_source, email=None, realm_id=None, + user_profile_id=None, medium=False): + # type: (Text, Text, Optional[int], Optional[int], bool) -> Text if avatar_source == u'U': - user_profile = get_user_profile_by_email(email) - hash_key = user_avatar_path(user_profile) + if user_profile_id is not None and realm_id is not None: + # If we can, avoid doing a database query to fetch user_profile + hash_key = user_avatar_path_from_ids(user_profile_id, realm_id) + else: + user_profile = get_user_profile_by_email(email) + hash_key = user_avatar_path(user_profile) return upload_backend.get_avatar_url(hash_key, medium=medium) elif settings.ENABLE_GRAVATAR: gravitar_query_suffix = "&s=%s" % (MEDIUM_AVATAR_SIZE,) if medium else ""