Created
August 24, 2012 08:09
-
-
Save anemitz/3447356 to your computer and use it in GitHub Desktop.
MongoEngine RandomPKDocument
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
import os | |
from zbase62 import zbase62 | |
from mongoengine import * | |
from mongoengine.queryset import OperationError | |
class RandomPKDocument(Document): | |
id = StringField(unique=True, primary_key=True) | |
def get_pk_prefix(self): | |
return self._get_collection_name()[:4] | |
def save(self, *args, **kwargs): | |
old_id = self.id | |
# Don't cascade saves by default. | |
kwargs['cascade'] = kwargs.get('cascade', False) | |
try: | |
if not self.id: | |
self.id = u'%s_%s' % (self.get_pk_prefix(), zbase62.b2a(os.urandom(32))) | |
# Throw an exception if another object with this id already exists. | |
kwargs['force_insert'] = True | |
# But don't do that when cascading. | |
kwargs['cascade_kwargs'] = { 'force_insert': False } | |
return super(RandomPKDocument, self).save(*args, **kwargs) | |
except OperationError, err: | |
self.id = old_id | |
# Use "startswith" instead of "in". Otherwise, if a free form | |
# StringField had a unique constraint someone could inject that | |
# string into the error message. | |
if unicode(err).startswith(u'Tried to save duplicate unique keys (E11000 duplicate key error index: %s.%s.$_id_ ' % (self._get_db().name, self._get_collection_name())): | |
self.save(*args, **kwargs) | |
else: | |
raise | |
meta = { | |
'allow_inheritance': True, | |
'abstract': True, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment