Convert uses of Realm.objects.get() to get_realm().

get_realm is better in two key ways:
* It uses memcached to fetch the data from the cache and thus is faster.
* It does a case-insensitive query and thus is more safe.
This commit is contained in:
Tim Abbott 2015-10-13 16:54:35 -04:00
parent 51ed5028dc
commit 71a06d58de
23 changed files with 61 additions and 59 deletions

View File

@ -6,7 +6,7 @@ import pytz
from django.core.management.base import BaseCommand
from django.db.models import Count
from zerver.models import UserProfile, Realm, Stream, Message, Recipient, UserActivity, \
Subscription, UserMessage
Subscription, UserMessage, get_realm
MOBILE_CLIENT_LIST = ["Android", "ios"]
HUMAN_CLIENT_LIST = MOBILE_CLIENT_LIST + ["website"]
@ -70,7 +70,7 @@ class Command(BaseCommand):
def handle(self, *args, **options):
if options['realms']:
try:
realms = [Realm.objects.get(domain=domain) for domain in options['realms']]
realms = [get_realm(domain) for domain in options['realms']]
except Realm.DoesNotExist, e:
print e
exit(1)

View File

@ -2,7 +2,7 @@ from __future__ import absolute_import
from django.core.management.base import BaseCommand
from django.db.models import Q
from zerver.models import Realm, Stream, Message, Subscription, Recipient
from zerver.models import Realm, Stream, Message, Subscription, Recipient, get_realm
class Command(BaseCommand):
help = "Generate statistics on the streams for a realm."
@ -14,7 +14,7 @@ class Command(BaseCommand):
def handle(self, *args, **options):
if options['realms']:
try:
realms = [Realm.objects.get(domain=domain) for domain in options['realms']]
realms = [get_realm(domain) for domain in options['realms']]
except Realm.DoesNotExist, e:
print e
exit(1)

View File

@ -4,7 +4,7 @@ import datetime
import pytz
from django.core.management.base import BaseCommand
from zerver.models import UserProfile, Realm, Stream, Message
from zerver.models import UserProfile, Realm, Stream, Message, get_realm
class Command(BaseCommand):
help = "Generate statistics on user activity."
@ -21,7 +21,7 @@ class Command(BaseCommand):
def handle(self, *args, **options):
if options['realms']:
try:
realms = [Realm.objects.get(domain=domain) for domain in options['realms']]
realms = [get_realm(domain) for domain in options['realms']]
except Realm.DoesNotExist, e:
print e
exit(1)

View File

@ -816,7 +816,7 @@ def get_realm_activity(request, realm):
all_user_records = {}
try:
admins = Realm.objects.get(domain=realm).get_admin_users()
admins = get_realm(realm).get_admin_users()
except Realm.DoesNotExist:
return HttpResponseNotFound("Realm %s does not exist" % (realm,))

View File

@ -18,7 +18,7 @@ def has_valid_realm(value):
# Checks if there is a realm without invite_required
# matching the domain of the input e-mail.
try:
realm = Realm.objects.get(domain=resolve_email_to_domain(value))
realm = get_realm(resolve_email_to_domain(value))
except Realm.DoesNotExist:
return False
return not realm.invite_required

View File

@ -710,7 +710,7 @@ def recipient_for_emails(emails, not_forged_mirror_message,
# and one of users is a zuliper
if len(realm_domains) == 2:
# I'm assuming that cross-realm PMs with the "admin realm" are rare, and therefore can be slower
admin_realm = Realm.objects.get(domain=settings.ADMIN_DOMAIN)
admin_realm = get_realm(settings.ADMIN_DOMAIN)
admin_realm_admin_emails = {u.email for u in admin_realm.get_admin_users()}
# We allow settings.CROSS_REALM_BOT_EMAILS for the hardcoded emails for the feedback and notification bots
if not (normalized_emails & admin_realm_admin_emails or normalized_emails & settings.CROSS_REALM_BOT_EMAILS):

View File

@ -8,10 +8,12 @@ from zerver.worker import queue_processors
from zerver.lib.actions import (
check_send_message, create_stream_if_needed, do_add_subscription,
get_display_recipient, get_user_profile_by_email,
get_display_recipient,
)
from zerver.models import (
get_realm,
get_user_profile_by_email,
resolve_email_to_domain,
Client,
Message,
@ -271,7 +273,7 @@ class AuthedTestCase(TestCase):
return data['messages']
def users_subscribed_to_stream(self, stream_name, realm_domain):
realm = Realm.objects.get(domain=realm_domain)
realm = get_realm(realm_domain)
stream = Stream.objects.get(name=stream_name, realm=realm)
recipient = Recipient.objects.get(type_id=stream.id, type=Recipient.STREAM)
subscriptions = Subscription.objects.filter(recipient=recipient, active=True)
@ -321,7 +323,7 @@ class AuthedTestCase(TestCase):
# Subscribe to a stream directly
def subscribe_to_stream(self, email, stream_name, realm=None):
realm = Realm.objects.get(domain=resolve_email_to_domain(email))
realm = get_realm(resolve_email_to_domain(email))
stream, _ = create_stream_if_needed(realm, stream_name)
user_profile = get_user_profile_by_email(email)
do_add_subscription(user_profile, stream, no_log=True)

View File

@ -5,7 +5,7 @@ from optparse import make_option
from django.core.management.base import BaseCommand
from zerver.lib.actions import create_stream_if_needed, do_add_subscription
from zerver.models import Realm, UserProfile, get_user_profile_by_email
from zerver.models import UserProfile, get_realm, get_user_profile_by_email
class Command(BaseCommand):
help = """Add some or all users in a realm to a set of streams."""
@ -37,7 +37,7 @@ class Command(BaseCommand):
exit(1)
stream_names = set([stream.strip() for stream in options["streams"].split(",")])
realm = Realm.objects.get(domain=options["domain"])
realm = get_realm(options["domain"])
if options["all_users"]:
user_profiles = UserProfile.objects.filter(realm=realm)

View File

@ -8,7 +8,7 @@ from django.core.exceptions import ValidationError
from django.db.utils import IntegrityError
from django.core import validators
from zerver.models import Realm, email_to_username
from zerver.models import Realm, get_realm, email_to_username
from zerver.lib.actions import do_create_user
from zerver.views import notify_new_user
from zerver.lib.initial_password import initial_password
@ -46,7 +46,7 @@ Terms of Service by passing --this-user-has-accepted-the-tos.""")
raise CommandError("""Please specify a realm by passing --domain.""")
try:
realm = Realm.objects.get(domain=options["domain"])
realm = get_realm(options["domain"])
except Realm.DoesNotExist:
raise CommandError("Realm does not exist.")

View File

@ -2,7 +2,7 @@ from __future__ import absolute_import
from optparse import make_option
from django.core.management.base import BaseCommand
from zerver.models import Message, Realm, Stream, Recipient
from zerver.models import get_realm, Message, Realm, Stream, Recipient
import datetime
import time
@ -23,7 +23,7 @@ class Command(BaseCommand):
)
def handle(self, *args, **options):
realm = Realm.objects.get(domain=options["domain"])
realm = get_realm(options["domain"])
streams = Stream.objects.filter(realm=realm, invite_only=False)
recipients = Recipient.objects.filter(
type=Recipient.STREAM, type_id__in=[stream.id for stream in streams])

View File

@ -6,7 +6,7 @@ from django.core.management.base import BaseCommand
from zerver.lib.actions import delete_all_user_sessions, \
delete_realm_user_sessions
from zerver.models import Realm
from zerver.models import get_realm
class Command(BaseCommand):
help = "Log out all users."
@ -21,7 +21,7 @@ class Command(BaseCommand):
def handle(self, *args, **options):
if options["realm"]:
realm = Realm.objects.get(domain=options["realm"])
realm = get_realm(options["realm"])
delete_realm_user_sessions(realm)
else:
delete_all_user_sessions()

View File

@ -23,7 +23,7 @@ class Command(BaseCommand):
help="alias to add or remove")
def handle(self, *args, **options):
realm = Realm.objects.get(domain=options["domain"])
realm = get_realm(options["domain"])
if options["op"] == "show":
print "Aliases for %s:" % (realm.domain,)
for alias in realm_aliases(realm):

View File

@ -1,7 +1,7 @@
from __future__ import absolute_import
from django.core.management.base import BaseCommand
from zerver.models import Realm
from zerver.models import Realm, get_realm
from zerver.lib.actions import do_add_realm_emoji, do_remove_realm_emoji
import sys
@ -30,7 +30,7 @@ Example: python manage.py realm_emoji --realm=zulip.com --op=show
help="URL of image to display for the emoji")
def handle(self, *args, **options):
realm = Realm.objects.get(domain=options["domain"])
realm = get_realm(options["domain"])
if options["op"] == "show":
for name, url in realm.get_emoji().iteritems():
print name, url

View File

@ -2,7 +2,7 @@ from __future__ import absolute_import
from optparse import make_option
from django.core.management.base import BaseCommand
from zerver.models import RealmFilter, all_realm_filters, Realm
from zerver.models import RealmFilter, all_realm_filters, get_realm
from zerver.lib.actions import do_add_realm_filter, do_remove_realm_filter
import sys
@ -37,7 +37,7 @@ Example: python manage.py realm_filters --realm=zulip.com --op=show
help="format string to substitute")
def handle(self, *args, **options):
realm = Realm.objects.get(domain=options["domain"])
realm = get_realm(options["domain"])
if options["op"] == "show":
print "%s: %s" % (realm.domain, all_realm_filters().get(realm.domain, ""))
sys.exit(0)

View File

@ -5,7 +5,7 @@ from optparse import make_option
from django.core.management.base import BaseCommand
from zerver.lib.actions import do_remove_subscription
from zerver.models import Realm, UserProfile, get_stream, \
from zerver.models import Realm, UserProfile, get_realm, get_stream, \
get_user_profile_by_email
class Command(BaseCommand):
@ -37,7 +37,7 @@ class Command(BaseCommand):
self.print_help("python manage.py", "remove_users_from_stream")
exit(1)
realm = Realm.objects.get(domain=options["domain"])
realm = get_realm(options["domain"])
stream_name = options["stream"].strip()
stream = get_stream(stream_name, realm)

View File

@ -2,7 +2,7 @@ from __future__ import absolute_import
from django.core.management.base import BaseCommand
from zerver.models import Realm
from zerver.models import get_realm
from zerver.lib.actions import set_default_streams
from optparse import make_option
@ -41,5 +41,5 @@ set of streams (which can be empty, with `--streams=`)."
exit(1)
stream_names = [stream.strip() for stream in options["streams"].split(",")]
realm = Realm.objects.get(domain=options["domain"])
realm = get_realm(options["domain"])
set_default_streams(realm, stream_names)

View File

@ -1,7 +1,7 @@
from __future__ import absolute_import
from django.core.management.base import BaseCommand
from zerver.models import Realm
from zerver.models import get_realm, Realm
import sys
class Command(BaseCommand):
@ -15,7 +15,7 @@ class Command(BaseCommand):
realm = options['realm']
try:
realm = Realm.objects.get(domain=realm)
realm = get_realm(realm)
except Realm.DoesNotExist:
print 'There is no realm called %s.' % (realm,)
sys.exit(1)

View File

@ -5,7 +5,7 @@ from optparse import make_option
from django.core.management.base import BaseCommand
from zerver.lib.actions import do_change_enable_digest_emails
from zerver.models import Realm, UserProfile, get_user_profile_by_email
from zerver.models import Realm, UserProfile, get_realm, get_user_profile_by_email
class Command(BaseCommand):
help = """Turn off digests for a domain or specified set of email addresses."""
@ -27,7 +27,7 @@ class Command(BaseCommand):
exit(1)
if options["domain"]:
realm = Realm.objects.get(domain=options["domain"])
realm = get_realm(options["domain"])
user_profiles = UserProfile.objects.filter(realm=realm)
else:
emails = set([email.strip() for email in options["users"].split(",")])

View File

@ -488,7 +488,7 @@ class StreamMessagesTest(AuthedTestCase):
# Subscribe everyone to a stream with non-ASCII characters.
non_ascii_stream_name = u"hümbüǵ"
realm = Realm.objects.get(domain="zulip.com")
realm = get_realm("zulip.com")
stream, _ = create_stream_if_needed(realm, non_ascii_stream_name)
for user_profile in UserProfile.objects.filter(realm=realm):
do_add_subscription(user_profile, stream, no_log=True)
@ -499,7 +499,7 @@ class StreamMessagesTest(AuthedTestCase):
class MessageDictTest(AuthedTestCase):
@slow(1.6, 'builds lots of messages')
def test_bulk_message_fetching(self):
realm = Realm.objects.get(domain="zulip.com")
realm = get_realm("zulip.com")
sender = get_user_profile_by_email('othello@zulip.com')
receiver = get_user_profile_by_email('hamlet@zulip.com')
pm_recipient = Recipient.objects.get(type_id=receiver.id, type=Recipient.PERSONAL)
@ -838,7 +838,7 @@ class GetOldMessagesTest(AuthedTestCase):
# We need to susbcribe to a stream and then send a message to
# it to ensure that we actually have a stream message in this
# narrow view.
realm = Realm.objects.get(domain="zulip.com")
realm = get_realm("zulip.com")
stream, _ = create_stream_if_needed(realm, "Scotland")
do_add_subscription(get_user_profile_by_email("hamlet@zulip.com"),
stream, no_log=True)
@ -866,7 +866,7 @@ class GetOldMessagesTest(AuthedTestCase):
# We need to susbcribe to a stream and then send a message to
# it to ensure that we actually have a stream message in this
# narrow view.
realm = Realm.objects.get(domain="mit.edu")
realm = get_realm("mit.edu")
lambda_stream, _ = create_stream_if_needed(realm, u"\u03bb-stream")
do_add_subscription(get_user_profile_by_email("starnine@mit.edu"),
lambda_stream, no_log=True)
@ -901,7 +901,7 @@ class GetOldMessagesTest(AuthedTestCase):
# We need to susbcribe to a stream and then send a message to
# it to ensure that we actually have a stream message in this
# narrow view.
realm = Realm.objects.get(domain="mit.edu")
realm = get_realm("mit.edu")
stream, _ = create_stream_if_needed(realm, "Scotland")
do_add_subscription(get_user_profile_by_email("starnine@mit.edu"),
stream, no_log=True)
@ -1439,7 +1439,7 @@ class CheckMessageTest(AuthedTestCase):
sender = get_user_profile_by_email('othello@zulip.com')
client, _ = Client.objects.get_or_create(name="test suite")
stream_name = 'integration'
stream, _ = create_stream_if_needed(Realm.objects.get(domain="zulip.com"), stream_name)
stream, _ = create_stream_if_needed(get_realm("zulip.com"), stream_name)
message_type_name = 'stream'
message_to = None
message_to = [stream_name]
@ -1468,7 +1468,7 @@ class CheckMessageTest(AuthedTestCase):
sender = bot
client, _ = Client.objects.get_or_create(name="test suite")
stream_name = 'integration'
stream, _ = create_stream_if_needed(Realm.objects.get(domain="zulip.com"), stream_name)
stream, _ = create_stream_if_needed(get_realm("zulip.com"), stream_name)
message_type_name = 'stream'
message_to = None
message_to = [stream_name]

View File

@ -5,7 +5,7 @@ from django.test import TestCase
from zilencer.models import Deployment
from zerver.models import (
get_user_profile_by_email,
get_realm, get_user_profile_by_email,
PreregistrationUser, Realm, ScheduledJob, UserProfile,
)
@ -121,7 +121,7 @@ class LoginTest(AuthedTestCase):
self.assertIn("Please enter a correct email and password", result.content)
def test_register(self):
realm = Realm.objects.get(domain="zulip.com")
realm = get_realm("zulip.com")
streams = ["stream_%s" % i for i in xrange(40)]
for stream in streams:
create_stream_if_needed(realm, stream)
@ -139,7 +139,7 @@ class LoginTest(AuthedTestCase):
If you try to register for a deactivated realm, you get a clear error
page.
"""
realm = Realm.objects.get(domain="zulip.com")
realm = get_realm("zulip.com")
realm.deactivated = True
realm.save(update_fields=["deactivated"])
@ -153,7 +153,7 @@ class LoginTest(AuthedTestCase):
"""
If you try to log in to a deactivated realm, you get a clear error page.
"""
realm = Realm.objects.get(domain="zulip.com")
realm = get_realm("zulip.com")
realm.deactivated = True
realm.save(update_fields=["deactivated"])
@ -386,7 +386,7 @@ so we didn't send them an invitation. We did send invitations to everyone else!"
In a realm with `restricted_to_domain = True`, you can't invite people
with a different domain from that of the realm or your e-mail address.
"""
zulip_realm = Realm.objects.get(domain="zulip.com")
zulip_realm = get_realm("zulip.com")
zulip_realm.restricted_to_domain = True
zulip_realm.save()
@ -403,7 +403,7 @@ so we didn't send them an invitation. We did send invitations to everyone else!"
In a realm with `restricted_to_domain = False`, you can invite people
with a different domain from that of the realm or your e-mail address.
"""
zulip_realm = Realm.objects.get(domain="zulip.com")
zulip_realm = get_realm("zulip.com")
zulip_realm.restricted_to_domain = False
zulip_realm.save()
@ -421,7 +421,7 @@ so we didn't send them an invitation. We did send invitations to everyone else!"
invitee = "alice-test@zulip.com"
stream_name = u"hümbüǵ"
realm = Realm.objects.get(domain="zulip.com")
realm = get_realm("zulip.com")
stream, _ = create_stream_if_needed(realm, stream_name)
# Make sure we're subscribed before inviting someone.

View File

@ -417,7 +417,7 @@ class DefaultStreamTest(AuthedTestCase):
return set(stream_names)
def test_set_default_streams(self):
realm = Realm.objects.get(domain="zulip.com")
realm = get_realm("zulip.com")
stream_names = ['apple', 'banana', 'Carrot Cake']
expected_names = stream_names + ['zulip']
set_default_streams(realm, stream_names)
@ -425,7 +425,7 @@ class DefaultStreamTest(AuthedTestCase):
self.assertEqual(stream_names, set(expected_names))
def test_add_and_remove_default_stream(self):
realm = Realm.objects.get(domain="zulip.com")
realm = get_realm("zulip.com")
orig_stream_names = self.get_default_stream_names(realm)
do_add_default_stream(realm, 'Added Stream')
new_stream_names = self.get_default_stream_names(realm)
@ -882,7 +882,7 @@ class SubscriptionAPITest(AuthedTestCase):
def test_multi_user_subscription(self):
email1 = 'cordelia@zulip.com'
email2 = 'iago@zulip.com'
realm = Realm.objects.get(domain="zulip.com")
realm = get_realm("zulip.com")
streams_to_sub = ['multi_user_stream']
events = []
with tornado_redirected_to_list(events):
@ -960,7 +960,7 @@ class SubscriptionAPITest(AuthedTestCase):
def test_bulk_subscribe_MIT(self):
realm = Realm.objects.get(domain="mit.edu")
realm = get_realm("mit.edu")
streams = ["stream_%s" % i for i in xrange(40)]
for stream in streams:
create_stream_if_needed(realm, stream)
@ -979,7 +979,7 @@ class SubscriptionAPITest(AuthedTestCase):
def test_bulk_subscribe_many(self):
# Create a whole bunch of streams
realm = Realm.objects.get(domain="zulip.com")
realm = get_realm("zulip.com")
streams = ["stream_%s" % i for i in xrange(20)]
for stream in streams:
create_stream_if_needed(realm, stream)
@ -1400,7 +1400,7 @@ class GetSubscribersTest(AuthedTestCase):
"""
gather_subscriptions returns correct results with only 3 queries
"""
realm = Realm.objects.get(domain="zulip.com")
realm = get_realm("zulip.com")
streams = ["stream_%s" % i for i in xrange(10)]
for stream in streams:
create_stream_if_needed(realm, stream)

View File

@ -83,14 +83,14 @@ class RealmTest(AuthedTestCase):
# cache, and we start by populating the cache for Hamlet, and we end
# by checking the cache to ensure that the new value is there.
get_user_profile_by_email('hamlet@zulip.com')
realm = Realm.objects.get(domain='zulip.com')
realm = get_realm('zulip.com')
new_name = 'Zed You Elle Eye Pea'
do_set_realm_name(realm, new_name)
self.assertEqual(get_realm(realm.domain).name, new_name)
self.assert_user_profile_cache_gets_new_name('hamlet@zulip.com', new_name)
def test_do_set_realm_name_events(self):
realm = Realm.objects.get(domain='zulip.com')
realm = get_realm('zulip.com')
new_name = 'Puliz'
events = []
with tornado_redirected_to_list(events):
@ -135,7 +135,7 @@ class RealmTest(AuthedTestCase):
# by checking the cache to ensure that his realm appears to be deactivated.
# You can make this test fail by disabling cache.flush_realm().
get_user_profile_by_email('hamlet@zulip.com')
realm = Realm.objects.get(domain='zulip.com')
realm = get_realm('zulip.com')
do_deactivate_realm(realm)
user = get_user_profile_by_email('hamlet@zulip.com')
self.assertTrue(user.realm.deactivated)

View File

@ -18,7 +18,7 @@ from zerver.lib.bulk_create import bulk_create_realms, \
bulk_create_clients
from zerver.lib.timestamp import timestamp_to_datetime
from zerver.models import MAX_MESSAGE_LENGTH
from zerver.models import DefaultStream, get_stream
from zerver.models import DefaultStream, get_stream, get_realm
from zilencer.models import Deployment
import ujson
@ -147,7 +147,7 @@ class Command(BaseCommand):
subscriptions_to_add.append(s)
Subscription.objects.bulk_create(subscriptions_to_add)
else:
zulip_realm = Realm.objects.get(domain="zulip.com")
zulip_realm = get_realm("zulip.com")
recipient_streams = [klass.type_id for klass in
Recipient.objects.filter(type=Recipient.STREAM)]
@ -577,7 +577,7 @@ def restore_saved_messages():
user_profile.save(update_fields=["enable_offline_push_notifications"])
continue
elif message_type == "default_streams":
set_default_streams(Realm.objects.get(domain=old_message["domain"]),
set_default_streams(get_realm(old_message["domain"]),
old_message["streams"])
continue
elif message_type == "subscription_property":