Forked from adamchainz/double_checked_lock_iterator.py
Created
January 23, 2022 18:43
-
-
Save abodacs/401939a7776a0340dffb39c957acbd71 to your computer and use it in GitHub Desktop.
double_checked_lock_iterator.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# refactor of https://lukeplant.me.uk/blog/posts/double-checked-locking-with-django-orm/ | |
# untested | |
def double_checked_lock_iterator(queryset): | |
for item_pk in queryset.values_list("pk", flat=True): | |
with transaction.atomic(): | |
try: | |
yield queryset.select_for_update(skip_locked=True).get(id=item_pk) | |
except queryset.model.DoesNotExist: | |
pass | |
def send_pending_order_shipped_emails(): | |
orders_to_email = Order.objects.filter( | |
shipped_at__isnull=False, shipped_email_sent=False, | |
) | |
for order in double_checked_lock_iterator(orders_to_email): | |
send_shipped_email(order) | |
order.shipped_email_sent = True | |
order.save() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment