Skip to content

Instantly share code, notes, and snippets.

@specialunderwear
Last active May 12, 2016 13:35
Show Gist options
  • Save specialunderwear/206e3b868532cfb2db6cec03481d2bfa to your computer and use it in GitHub Desktop.
Save specialunderwear/206e3b868532cfb2db6cec03481d2bfa to your computer and use it in GitHub Desktop.
>>> import contextlib
>>> from django.db import models
>>>
>>> class Sequence(models.Model):
... pass
>>>
>>> @contextlib.contextmanager
>>> def unique_threadsafe_id():
... try:
... a, created = Sequence.objects.create()
... yield a.pk
... finally:
... a.delete()
>>>
>>>
>>> with unique_threadsafe_id() as id:
... print id
1
>>> with unique_threadsafe_id() as id:
... print id
2
>>>
>>>
>>> print Sequence.objects.get()
Exception Sequence.DoesNotExist
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment