django_api: Extract send_event_on_commit helper.

django-stubs 4.2.1 gives transaction.on_commit a more accurate type
annotation, but this exposed that mypy can’t handle the lambda default
parameters that we use to recapture loop variables such as

    for stream_id in public_stream_ids:
        peer_user_ids = …
        event = …

        transaction.on_commit(
            lambda event=event, peer_user_ids=peer_user_ids: send_event(
                realm, event, peer_user_ids
            )
        )

https://github.com/python/mypy/issues/15459

A workaround that mypy accepts is

        transaction.on_commit(
            (
                lambda event, peer_user_ids: lambda: send_event(
                    realm, event, peer_user_ids
                )
            )(event, peer_user_ids)
        )

But that’s kind of ugly and potentially error-prone, so let’s make a
helper function for this very common pattern.

        send_event_on_commit(realm, event, peer_user_ids)

Signed-off-by: Anders Kaseorg <anders@zulip.com>
This commit is contained in:
Anders Kaseorg
2023-06-17 11:53:07 -07:00
committed by Tim Abbott
parent 77c146b8b0
commit 7657cb4a0f
22 changed files with 114 additions and 180 deletions

View File

@@ -13,12 +13,12 @@ from zerver.models import (
active_user_ids,
get_realm_playgrounds,
)
from zerver.tornado.django_api import send_event
from zerver.tornado.django_api import send_event_on_commit
def notify_realm_playgrounds(realm: Realm, realm_playgrounds: List[RealmPlaygroundDict]) -> None:
event = dict(type="realm_playgrounds", realm_playgrounds=realm_playgrounds)
transaction.on_commit(lambda: send_event(realm, event, active_user_ids(realm.id)))
send_event_on_commit(realm, event, active_user_ids(realm.id))
@transaction.atomic(durable=True)