Skip to content

Instantly share code, notes, and snippets.

@adamchainz
Created February 28, 2020 17:18
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save adamchainz/51dad7990c073978f27a7e372cfb49db to your computer and use it in GitHub Desktop.
Save adamchainz/51dad7990c073978f27a7e372cfb49db to your computer and use it in GitHub Desktop.
double_checked_lock_iterator.py
# 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